GNU Emacs Lisp Reference Manual

For Emacs Version 20.3

Revision 2.5, May 1998

by Bil Lewis, Dan LaLiberte, Richard Stallman
and the GNU Manual Group


Table of Contents


GNU GENERAL PUBLIC LICENSE

Version 2, June 1991

Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111, USA

Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

Preamble

The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.

For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.

Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.

Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.

The precise terms and conditions for copying, distribution and modification follow.

TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  1. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
  2. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
  3. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
    1. You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
    2. You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
    3. If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
    These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
  4. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
    1. Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
    2. Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
    3. Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
    The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
  5. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
  6. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
  7. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
  8. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
  9. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
  10. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
  11. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.

    NO WARRANTY

  12. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
  13. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

END OF TERMS AND CONDITIONS

How to Apply These Terms to Your New Programs

If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.

To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.

one line to give the program's name and an idea of what it does.
Copyright (C) 19yy  name of author

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this when it starts in an interactive mode:

Gnomovision version 69, Copyright (C) 19yy name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
type `show w'.  This is free software, and you are welcome
to redistribute it under certain conditions; type `show c' 
for details.

The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:

Yoyodyne, Inc., hereby disclaims all copyright
interest in the program `Gnomovision'
(which makes passes at compilers) written 
by James Hacker.

signature of Ty Coon, 1 April 1989
Ty Coon, President of Vice

This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License.

Introduction

Most of the GNU Emacs text editor is written in the programming language called Emacs Lisp. You can write new code in Emacs Lisp and install it as an extension to the editor. However, Emacs Lisp is more than a mere "extension language"; it is a full computer programming language in its own right. You can use it as you would any other programming language.

Because Emacs Lisp is designed for use in an editor, it has special features for scanning and parsing text as well as features for handling files, buffers, displays, subprocesses, and so on. Emacs Lisp is closely integrated with the editing facilities; thus, editing commands are functions that can also conveniently be called from Lisp programs, and parameters for customization are ordinary Lisp variables.

This manual attempts to be a full description of Emacs Lisp. For a beginner's introduction to Emacs Lisp, see An Introduction to Emacs Lisp Programming, by Bob Chassell, also published by the Free Software Foundation. This manual presumes considerable familiarity with the use of Emacs for editing; see The GNU Emacs Manual for this basic information.

Generally speaking, the earlier chapters describe features of Emacs Lisp that have counterparts in many programming languages, and later chapters describe features that are peculiar to Emacs Lisp or relate specifically to editing.

This is edition 2.5.

Caveats

This manual has gone through numerous drafts. It is nearly complete but not flawless. There are a few topics that are not covered, either because we consider them secondary (such as most of the individual modes) or because they are yet to be written. Because we are not able to deal with them completely, we have left out several parts intentionally. This includes most information about usage on VMS.

The manual should be fully correct in what it does cover, and it is therefore open to criticism on anything it says--from specific examples and descriptive text, to the ordering of chapters and sections. If something is confusing, or you find that you have to look at the sources or experiment to learn something not covered in the manual, then perhaps the manual should be fixed. Please let us know.

As you use the manual, we ask that you mark pages with corrections so you can later look them up and send them in. If you think of a simple, real-life example for a function or group of functions, please make an effort to write it up and send it in. Please reference any comments to the chapter name, section name, and function name, as appropriate, since page numbers and chapter and section numbers will change and we may have trouble finding the text you are talking about. Also state the number of the edition you are criticizing.

Please mail comments and corrections to

[email protected]

We let mail to this list accumulate unread until someone decides to apply the corrections. Months, and sometimes years, go by between updates. So please attach no significance to the lack of a reply--your mail will be acted on in due time. If you want to contact the Emacs maintainers more quickly, send mail to [email protected].

Lisp History

Lisp (LISt Processing language) was first developed in the late 1950s at the Massachusetts Institute of Technology for research in artificial intelligence. The great power of the Lisp language makes it ideal for other purposes as well, such as writing editing commands.

Dozens of Lisp implementations have been built over the years, each with its own idiosyncrasies. Many of them were inspired by Maclisp, which was written in the 1960s at MIT's Project MAC. Eventually the implementors of the descendants of Maclisp came together and developed a standard for Lisp systems, called Common Lisp. In the meantime, Gerry Sussman and Guy Steele at MIT developed a simplified but very powerful dialect of Lisp, called Scheme.

GNU Emacs Lisp is largely inspired by Maclisp, and a little by Common Lisp. If you know Common Lisp, you will notice many similarities. However, many features of Common Lisp have been omitted or simplified in order to reduce the memory requirements of GNU Emacs. Sometimes the simplifications are so drastic that a Common Lisp user might be very confused. We will occasionally point out how GNU Emacs Lisp differs from Common Lisp. If you don't know Common Lisp, don't worry about it; this manual is self-contained.

A certain amount of Common Lisp emulation is available via the `cl' library See section `Common Lisp Extension' in Common Lisp Extensions.

Emacs Lisp is not at all influenced by Scheme; but the GNU project has an implementation of Scheme, called Guile. We use Guile in all new GNU software that calls for extensibility.

Conventions

This section explains the notational conventions that are used in this manual. You may want to skip this section and refer back to it later.

Some Terms

Throughout this manual, the phrases "the Lisp reader" and "the Lisp printer" refer to those routines in Lisp that convert textual representations of Lisp objects into actual Lisp objects, and vice versa. See section Printed Representation and Read Syntax, for more details. You, the person reading this manual, are thought of as "the programmer" and are addressed as "you". "The user" is the person who uses Lisp programs, including those you write.

Examples of Lisp code appear in this font or form: (list 1 2 3). Names that represent metasyntactic variables, or arguments to a function being described, appear in this font or form: first-number.

nil and t

In Lisp, the symbol nil has three separate meanings: it is a symbol with the name `nil'; it is the logical truth value false; and it is the empty list--the list of zero elements. When used as a variable, nil always has the value nil.

As far as the Lisp reader is concerned, `()' and `nil' are identical: they stand for the same object, the symbol nil. The different ways of writing the symbol are intended entirely for human readers. After the Lisp reader has read either `()' or `nil', there is no way to determine which representation was actually written by the programmer.

In this manual, we use () when we wish to emphasize that it means the empty list, and we use nil when we wish to emphasize that it means the truth value false. That is a good convention to use in Lisp programs also.

(cons 'foo ())                ; Emphasize the empty list
(not nil)                     ; Emphasize the truth value false

In contexts where a truth value is expected, any non-nil value is considered to be true. However, t is the preferred way to represent the truth value true. When you need to choose a value which represents true, and there is no other basis for choosing, use t. The symbol t always has the value t.

In Emacs Lisp, nil and t are special symbols that always evaluate to themselves. This is so that you do not need to quote them to use them as constants in a program. An attempt to change their values results in a setting-constant error. The same is true of any symbol whose name starts with a colon (`:'). See section Variables That Never Change.

Evaluation Notation

A Lisp expression that you can evaluate is called a form. Evaluating a form always produces a result, which is a Lisp object. In the examples in this manual, this is indicated with `=>':

(car '(1 2))
     => 1

You can read this as "(car '(1 2)) evaluates to 1".

When a form is a macro call, it expands into a new form for Lisp to evaluate. We show the result of the expansion with `==>'. We may or may not show the result of the evaluation of the expanded form.

(third '(a b c))
     ==> (car (cdr (cdr '(a b c))))
     => c

Sometimes to help describe one form we show another form that produces identical results. The exact equivalence of two forms is indicated with `=='.

(make-sparse-keymap) == (list 'keymap)

Printing Notation

Many of the examples in this manual print text when they are evaluated. If you execute example code in a Lisp Interaction buffer (such as the buffer `*scratch*'), the printed text is inserted into the buffer. If you execute the example by other means (such as by evaluating the function eval-region), the printed text is displayed in the echo area. You should be aware that text displayed in the echo area is truncated to a single line.

Examples in this manual indicate printed text with `-|', irrespective of where that text goes. The value returned by evaluating the form (here bar) follows on a separate line.

(progn (print 'foo) (print 'bar))
     -| foo
     -| bar
     => bar

Error Messages

Some examples signal errors. This normally displays an error message in the echo area. We show the error message on a line starting with `error-->'. Note that `error-->' itself does not appear in the echo area.

(+ 23 'x)
error--> Wrong type argument: number-or-marker-p, x

Buffer Text Notation

Some examples show modifications to text in a buffer, with "before" and "after" versions of the text. These examples show the contents of the buffer in question between two lines of dashes containing the buffer name. In addition, `-!-' indicates the location of point. (The symbol for point, of course, is not part of the text in the buffer; it indicates the place between two characters where point is currently located.)

---------- Buffer: foo ----------
This is the -!-contents of foo.
---------- Buffer: foo ----------

(insert "changed ")
     => nil
---------- Buffer: foo ----------
This is the changed -!-contents of foo.
---------- Buffer: foo ----------

Format of Descriptions

Functions, variables, macros, commands, user options, and special forms are described in this manual in a uniform format. The first line of a description contains the name of the item followed by its arguments, if any. The category--function, variable, or whatever--is printed next to the right margin. The description follows on succeeding lines, sometimes with examples.

A Sample Function Description

In a function description, the name of the function being described appears first. It is followed on the same line by a list of argument names. These names are also used in the body of the description, to stand for the values of the arguments.

The appearance of the keyword &optional in the argument list indicates that the subsequent arguments may be omitted (omitted arguments default to nil). Do not write &optional when you call the function.

The keyword &rest (which must be followed by a single argument name) indicates that any number of arguments can follow. The single following argument name will have a value, as a variable, which is a list of all these remaining arguments. Do not write &rest when you call the function.

Here is a description of an imaginary function foo:

Function: foo integer1 &optional integer2 &rest integers
The function foo subtracts integer1 from integer2, then adds all the rest of the arguments to the result. If integer2 is not supplied, then the number 19 is used by default.

(foo 1 5 3 9)
     => 16
(foo 5)
     => 14

More generally,

(foo w x y...)
==
(+ (- x w) y...)

Any argument whose name contains the name of a type (e.g., integer, integer1 or buffer) is expected to be of that type. A plural of a type (such as buffers) often means a list of objects of that type. Arguments named object may be of any type. (See section Lisp Data Types, for a list of Emacs object types.) Arguments with other sorts of names (e.g., new-file) are discussed specifically in the description of the function. In some sections, features common to the arguments of several functions are described at the beginning.

See section Lambda Expressions, for a more complete description of optional and rest arguments.

Command, macro, and special form descriptions have the same format, but the word `Function' is replaced by `Command', `Macro', or `Special Form', respectively. Commands are simply functions that may be called interactively; macros process their arguments differently from functions (the arguments are not evaluated), but are presented the same way.

Special form descriptions use a more complex notation to specify optional and repeated arguments because they can break the argument list down into separate arguments in more complicated ways. `[optional-arg]' means that optional-arg is optional and `repeated-args...' stands for zero or more arguments. Parentheses are used when several arguments are grouped into additional levels of list structure. Here is an example:

Special Form: count-loop (var [from to [inc]]) body...
This imaginary special form implements a loop that executes the body forms and then increments the variable var on each iteration. On the first iteration, the variable has the value from; on subsequent iterations, it is incremented by one (or by inc if that is given). The loop exits before executing body if var equals to. Here is an example:

(count-loop (i 0 10)
  (prin1 i) (princ " ")
  (prin1 (aref vector i))
  (terpri))

If from and to are omitted, var is bound to nil before the loop begins, and the loop exits if var is non-nil at the beginning of an iteration. Here is an example:

(count-loop (done)
  (if (pending)
      (fixit)
    (setq done t)))

In this special form, the arguments from and to are optional, but must both be present or both absent. If they are present, inc may optionally be specified as well. These arguments are grouped with the argument var into a list, to distinguish them from body, which includes all remaining elements of the form.

A Sample Variable Description

A variable is a name that can hold a value. Although any variable can be set by the user, certain variables that exist specifically so that users can change them are called user options. Ordinary variables and user options are described using a format like that for functions except that there are no arguments.

Here is a description of the imaginary electric-future-map variable.

Variable: electric-future-map
The value of this variable is a full keymap used by Electric Command Future mode. The functions in this map allow you to edit commands you have not yet thought about executing.

User option descriptions have the same format, but `Variable' is replaced by `User Option'.

Version Information

These facilities provide information about which version of Emacs is in use.

Command: emacs-version
This function returns a string describing the version of Emacs that is running. It is useful to include this string in bug reports.

(emacs-version)
  => "GNU Emacs 20.3.5 (i486-pc-linux-gnulibc1, X toolkit)
 of Sat Feb 14 1998 on psilocin.gnu.org"

Called interactively, the function prints the same information in the echo area.

Variable: emacs-build-time
The value of this variable indicates the time at which Emacs was built at the local site. It is a list of three integers, like the value of current-time (see section Time of Day).

emacs-build-time
     => (13623 62065 344633)

Variable: emacs-version
The value of this variable is the version of Emacs being run. It is a string such as "20.3.1". The last number in this string is not really part of the Emacs release version number; it is incremented each time you build Emacs in any given directory.

The following two variables have existed since Emacs version 19.23:

Variable: emacs-major-version
The major version number of Emacs, as an integer. For Emacs version 20.3, the value is 20.

Variable: emacs-minor-version
The minor version number of Emacs, as an integer. For Emacs version 20.3, the value is 3.

Acknowledgements

This manual was written by Robert Krawitz, Bil Lewis, Dan LaLiberte, Richard M. Stallman and Chris Welty, the volunteers of the GNU manual group, in an effort extending over several years. Robert J. Chassell helped to review and edit the manual, with the support of the Defense Advanced Research Projects Agency, ARPA Order 6082, arranged by Warren A. Hunt, Jr. of Computational Logic, Inc.

Corrections were supplied by Karl Berry, Jim Blandy, Bard Bloom, Stephane Boucher, David Boyes, Alan Carroll, Richard Davis, Lawrence R. Dodd, Peter Doornbosch, David A. Duff, Chris Eich, Beverly Erlebacher, David Eckelkamp, Ralf Fassel, Eirik Fuller, Stephen Gildea, Bob Glickstein, Eric Hanchrow, George Hartzell, Nathan Hess, Masayuki Ida, Dan Jacobson, Jak Kirman, Bob Knighten, Frederick M. Korz, Joe Lammens, Glenn M. Lewis, K. Richard Magill, Brian Marick, Roland McGrath, Skip Montanaro, John Gardiner Myers, Thomas A. Peterson, Francesco Potorti, Friedrich Pukelsheim, Arnold D. Robbins, Raul Rockwell, Per Starback, Shinichirou Sugou, Kimmo Suominen, Edward Tharp, Bill Trost, Rickard Westman, Jean White, Matthew Wilding, Carl Witty, Dale Worley, Rusty Wright, and David D. Zuhn.

Lisp Data Types

A Lisp object is a piece of data used and manipulated by Lisp programs. For our purposes, a type or data type is a set of possible objects.

Every object belongs to at least one type. Objects of the same type have similar structures and may usually be used in the same contexts. Types can overlap, and objects can belong to two or more types. Consequently, we can ask whether an object belongs to a particular type, but not for "the" type of an object.

A few fundamental object types are built into Emacs. These, from which all other types are constructed, are called primitive types. Each object belongs to one and only one primitive type. These types include integer, float, cons, symbol, string, vector, subr, byte-code function, plus several special types, such as buffer, that are related to editing. (See section Editing Types.)

Each primitive type has a corresponding Lisp function that checks whether an object is a member of that type.

Note that Lisp is unlike many other languages in that Lisp objects are self-typing: the primitive type of the object is implicit in the object itself. For example, if an object is a vector, nothing can treat it as a number; Lisp knows it is a vector, not a number.

In most languages, the programmer must declare the data type of each variable, and the type is known by the compiler but not represented in the data. Such type declarations do not exist in Emacs Lisp. A Lisp variable can have any type of value, and it remembers whatever value you store in it, type and all.

This chapter describes the purpose, printed representation, and read syntax of each of the standard types in GNU Emacs Lisp. Details on how to use these types can be found in later chapters.

Printed Representation and Read Syntax

The printed representation of an object is the format of the output generated by the Lisp printer (the function prin1) for that object. The read syntax of an object is the format of the input accepted by the Lisp reader (the function read) for that object. See section Reading and Printing Lisp Objects.

Most objects have more than one possible read syntax. Some types of object have no read syntax, since it may not make sense to enter objects of these types directly in a Lisp program. Except for these cases, the printed representation of an object is also a read syntax for it.

In other languages, an expression is text; it has no other form. In Lisp, an expression is primarily a Lisp object and only secondarily the text that is the object's read syntax. Often there is no need to emphasize this distinction, but you must keep it in the back of your mind, or you will occasionally be very confused.

Every type has a printed representation. Some types have no read syntax--for example, the buffer type has none. Objects of these types are printed in hash notation: the characters `#<' followed by a descriptive string (typically the type name followed by the name of the object), and closed with a matching `>'. Hash notation cannot be read at all, so the Lisp reader signals the error invalid-read-syntax whenever it encounters `#<'.

(current-buffer)
     => #<buffer objects.texi>

When you evaluate an expression interactively, the Lisp interpreter first reads the textual representation of it, producing a Lisp object, and then evaluates that object (see section Evaluation). However, evaluation and reading are separate activities. Reading returns the Lisp object represented by the text that is read; the object may or may not be evaluated later. See section Input Functions, for a description of read, the basic function for reading objects.

Comments

A comment is text that is written in a program only for the sake of humans that read the program, and that has no effect on the meaning of the program. In Lisp, a semicolon (`;') starts a comment if it is not within a string or character constant. The comment continues to the end of line. The Lisp reader discards comments; they do not become part of the Lisp objects which represent the program within the Lisp system.

The `#@count' construct, which skips the next count characters, is useful for program-generated comments containing binary data. The Emacs Lisp byte compiler uses this in its output files (see section Byte Compilation). It isn't meant for source files, however.

See section Tips on Writing Comments, for conventions for formatting comments.

Programming Types

There are two general categories of types in Emacs Lisp: those having to do with Lisp programming, and those having to do with editing. The former exist in many Lisp implementations, in one form or another. The latter are unique to Emacs Lisp.

Integer Type

The range of values for integers in Emacs Lisp is -134217728 to 134217727 (28 bits; i.e., to on most machines. (Some machines may provide a wider range.) It is important to note that the Emacs Lisp arithmetic functions do not check for overflow. Thus (1+ 134217727) is -134217728 on most machines.

The read syntax for integers is a sequence of (base ten) digits with an optional sign at the beginning and an optional period at the end. The printed representation produced by the Lisp interpreter never has a leading `+' or a final `.'.

-1               ; The integer -1.
1                ; The integer 1.
1.               ; Also The integer 1.
+1               ; Also the integer 1.
268435457        ; Also the integer 1 on a 28-bit implementation.

See section Numbers, for more information.

Floating Point Type

Emacs supports floating point numbers (though there is a compilation option to disable them). The precise range of floating point numbers is machine-specific.

The printed representation for floating point numbers requires either a decimal point (with at least one digit following), an exponent, or both. For example, `1500.0', `15e2', `15.0e2', `1.5e3', and `.15e4' are five ways of writing a floating point number whose value is 1500. They are all equivalent.

See section Numbers, for more information.

Character Type

A character in Emacs Lisp is nothing more than an integer. In other words, characters are represented by their character codes. For example, the character A is represented as the integer 65.

Individual characters are not often used in programs. It is far more common to work with strings, which are sequences composed of characters. See section String Type.

Characters in strings, buffers, and files are currently limited to the range of 0 to 524287--nineteen bits. But not all values in that range are valid character codes. Codes 0 through 127 are ASCII codes; the rest are non-ASCII (see section Non-ASCII Characters). Characters that represent keyboard input have a much wider range, to encode modifier keys such as Control, Meta and Shift.

Since characters are really integers, the printed representation of a character is a decimal number. This is also a possible read syntax for a character, but writing characters that way in Lisp programs is a very bad idea. You should always use the special read syntax formats that Emacs Lisp provides for characters. These syntax formats start with a question mark.

The usual read syntax for alphanumeric characters is a question mark followed by the character; thus, `?A' for the character A, `?B' for the character B, and `?a' for the character a.

For example:

?Q => 81     ?q => 113

You can use the same syntax for punctuation characters, but it is often a good idea to add a `\' so that the Emacs commands for editing Lisp code don't get confused. For example, `?\ ' is the way to write the space character. If the character is `\', you must use a second `\' to quote it: `?\\'.

You can express the characters Control-g, backspace, tab, newline, vertical tab, formfeed, return, and escape as `?\a', `?\b', `?\t', `?\n', `?\v', `?\f', `?\r', `?\e', respectively. Thus,

?\a => 7                 ; C-g
?\b => 8                 ; backspace, BS, C-h
?\t => 9                 ; tab, TAB, C-i
?\n => 10                ; newline, C-j
?\v => 11                ; vertical tab, C-k
?\f => 12                ; formfeed character, C-l
?\r => 13                ; carriage return, RET, C-m
?\e => 27                ; escape character, ESC, C-[
?\\ => 92                ; backslash character, \

These sequences which start with backslash are also known as escape sequences, because backslash plays the role of an escape character; this usage has nothing to do with the character ESC.

Control characters may be represented using yet another read syntax. This consists of a question mark followed by a backslash, caret, and the corresponding non-control character, in either upper or lower case. For example, both `?\^I' and `?\^i' are valid read syntax for the character C-i, the character whose value is 9.

Instead of the `^', you can use `C-'; thus, `?\C-i' is equivalent to `?\^I' and to `?\^i':

?\^I => 9     ?\C-I => 9

In strings and buffers, the only control characters allowed are those that exist in ASCII; but for keyboard input purposes, you can turn any character into a control character with `C-'. The character codes for these non-ASCII control characters include the bit as well as the code for the corresponding non-control character. Ordinary terminals have no way of generating non-ASCII control characters, but you can generate them straightforwardly using X and other window systems.

For historical reasons, Emacs treats the DEL character as the control equivalent of ?:

?\^? => 127     ?\C-? => 127

As a result, it is currently not possible to represent the character Control-?, which is a meaningful input character under X, using `\C-'. It is not easy to change this, as various Lisp files refer to DEL in this way.

For representing control characters to be found in files or strings, we recommend the `^' syntax; for control characters in keyboard input, we prefer the `C-' syntax. Which one you use does not affect the meaning of the program, but may guide the understanding of people who read it.

A meta character is a character typed with the META modifier key. The integer that represents such a character has the bit set (which on most machines makes it a negative number). We use high bits for this and other modifiers to make possible a wide range of basic character codes.

In a string, the bit attached to an ASCII character indicates a meta character; thus, the meta characters that can fit in a string have codes in the range from 128 to 255, and are the meta versions of the ordinary ASCII characters. (In Emacs versions 18 and older, this convention was used for characters outside of strings as well.)

The read syntax for meta characters uses `\M-'. For example, `?\M-A' stands for M-A. You can use `\M-' together with octal character codes (see below), with `\C-', or with any other syntax for a character. Thus, you can write M-A as `?\M-A', or as `?\M-\101'. Likewise, you can write C-M-b as `?\M-\C-b', `?\C-\M-b', or `?\M-\002'.

The case of a graphic character is indicated by its character code; for example, ASCII distinguishes between the characters `a' and `A'. But ASCII has no way to represent whether a control character is upper case or lower case. Emacs uses the bit to indicate that the shift key was used in typing a control character. This distinction is possible only when you use X terminals or other special terminals; ordinary terminals do not report the distinction to the computer in any way.

The X Window System defines three other modifier bits that can be set in a character: hyper, super and alt. The syntaxes for these bits are `\H-', `\s-' and `\A-'. (Case is significant in these prefixes.) Thus, `?\H-\M-\A-x' represents Alt-Hyper-Meta-x.

Finally, the most general read syntax for a character represents the character code in either octal or hex. To use octal, write a question mark followed by a backslash and the octal character code (up to three octal digits); thus, `?\101' for the character A, `?\001' for the character C-a, and ?\002 for the character C-b. Although this syntax can represent any ASCII character, it is preferred only when the precise octal value is more important than the ASCII representation.

?\012 => 10         ?\n => 10         ?\C-j => 10
?\101 => 65         ?A => 65

To use hex, write a question mark followed by a backslash, `x', and the hexadecimal character code. You can use any number of hex digits, so you can represent any character code in this way. Thus, `?\x41' for the character A, `?\x1' for the character C-a, and ?\x8e0 for the character ``a'.

A backslash is allowed, and harmless, preceding any character without a special escape meaning; thus, `?\+' is equivalent to `?+'. There is no reason to add a backslash before most characters. However, you should add a backslash before any of the characters `()\|;'`"#.,' to avoid confusing the Emacs commands for editing Lisp code. Also add a backslash before whitespace characters such as space, tab, newline and formfeed. However, it is cleaner to use one of the easily readable escape sequences, such as `\t', instead of an actual whitespace character such as a tab.

Symbol Type

A symbol in GNU Emacs Lisp is an object with a name. The symbol name serves as the printed representation of the symbol. In ordinary use, the name is unique--no two symbols have the same name.

A symbol can serve as a variable, as a function name, or to hold a property list. Or it may serve only to be distinct from all other Lisp objects, so that its presence in a data structure may be recognized reliably. In a given context, usually only one of these uses is intended. But you can use one symbol in all of these ways, independently.

A symbol name can contain any characters whatever. Most symbol names are written with letters, digits, and the punctuation characters `-+=*/'. Such names require no special punctuation; the characters of the name suffice as long as the name does not look like a number. (If it does, write a `\' at the beginning of the name to force interpretation as a symbol.) The characters `[email protected]$%^&:<>{}' are less often used but also require no special punctuation. Any other characters may be included in a symbol's name by escaping them with a backslash. In contrast to its use in strings, however, a backslash in the name of a symbol simply quotes the single character that follows the backslash. For example, in a string, `\t' represents a tab character; in the name of a symbol, however, `\t' merely quotes the letter `t'. To have a symbol with a tab character in its name, you must actually use a tab (preceded with a backslash). But it's rare to do such a thing.

Common Lisp note: In Common Lisp, lower case letters are always "folded" to upper case, unless they are explicitly escaped. In Emacs Lisp, upper case and lower case letters are distinct.

Here are several examples of symbol names. Note that the `+' in the fifth example is escaped to prevent it from being read as a number. This is not necessary in the sixth example because the rest of the name makes it invalid as a number.

foo                 ; A symbol named `foo'.
FOO                 ; A symbol named `FOO', different from `foo'.
char-to-string      ; A symbol named `char-to-string'.
1+                  ; A symbol named `1+'
                    ;   (not `+1', which is an integer).
\+1                 ; A symbol named `+1'
                    ;   (not a very readable name).
\(*\ 1\ 2\)         ; A symbol named `(* 1 2)' (a worse name).
+-*/[email protected]$%^&=:<>{}  ; A symbol named `+-*/[email protected]$%^&=:<>{}'.
                    ;   These characters need not be escaped.

Sequence Types

A sequence is a Lisp object that represents an ordered set of elements. There are two kinds of sequence in Emacs Lisp, lists and arrays. Thus, an object of type list or of type array is also considered a sequence.

Arrays are further subdivided into strings, vectors, char-tables and bool-vectors. Vectors can hold elements of any type, but string elements must be characters, and bool-vector elements must be t or nil. The characters in a string can have text properties like characters in a buffer (see section Text Properties); vectors and bool-vectors do not support text properties even when their elements happen to be characters. Char-tables are like vectors except that they are indexed by any valid character code.

Lists, strings and the other array types are different, but they have important similarities. For example, all have a length l, and all have elements which can be indexed from zero to l minus one. Several functions, called sequence functions, accept any kind of sequence. For example, the function elt can be used to extract an element of a sequence, given its index. See section Sequences, Arrays, and Vectors.

It is generally impossible to read the same sequence twice, since sequences are always created anew upon reading. If you read the read syntax for a sequence twice, you get two sequences with equal contents. There is one exception: the empty list () always stands for the same object, nil.

Cons Cell and List Types

A cons cell is an object that consists of two pointers or slots, called the CAR slot and the CDR slot. Each slot can point to or hold to any Lisp object. We also say that the "the CAR of this cons cell is" whatever object its CAR slot currently points to, and likewise for the CDR.

A list is a series of cons cells, linked together so that the CDR slot of each cons cell holds either the next cons cell or the empty list. See section Lists, for functions that work on lists. Because most cons cells are used as part of lists, the phrase list structure has come to refer to any structure made out of cons cells.

The names CAR and CDR derive from the history of Lisp. The original Lisp implementation ran on an IBM 704 computer which divided words into two parts, called the "address" part and the "decrement"; CAR was an instruction to extract the contents of the address part of a register, and CDR an instruction to extract the contents of the decrement. By contrast, "cons cells" are named for the function cons that creates them, which in turn is named for its purpose, the construction of cells.

Because cons cells are so central to Lisp, we also have a word for "an object which is not a cons cell". These objects are called atoms.

The read syntax and printed representation for lists are identical, and consist of a left parenthesis, an arbitrary number of elements, and a right parenthesis.

Upon reading, each object inside the parentheses becomes an element of the list. That is, a cons cell is made for each element. The CAR slot of the cons cell points to the element, and its CDR slot points to the next cons cell of the list, which holds the next element in the list. The CDR slot of the last cons cell is set to point to nil.

A list can be illustrated by a diagram in which the cons cells are shown as pairs of boxes, like dominoes. (The Lisp reader cannot read such an illustration; unlike the textual notation, which can be understood by both humans and computers, the box illustrations can be understood only by humans.) This picture represents the three-element list (rose violet buttercup):

    --- ---      --- ---      --- ---
   |   |   |--> |   |   |--> |   |   |--> nil
    --- ---      --- ---      --- ---
     |            |            |
     |            |            |
      --> rose     --> violet   --> buttercup

In this diagram, each box represents a slot that can point to any Lisp object. Each pair of boxes represents a cons cell. Each arrow is a pointer to a Lisp object, either an atom or another cons cell.

In this example, the first box, which holds the CAR of the first cons cell, points to or "contains" rose (a symbol). The second box, holding the CDR of the first cons cell, points to the next pair of boxes, the second cons cell. The CAR of the second cons cell is violet, and its CDR is the third cons cell. The CDR of the third (and last) cons cell is nil.

Here is another diagram of the same list, (rose violet buttercup), sketched in a different manner:

 ---------------       ----------------       -------------------
| car   | cdr   |     | car    | cdr   |     | car       | cdr   |
| rose  |   o-------->| violet |   o-------->| buttercup |  nil  |
|       |       |     |        |       |     |           |       |
 ---------------       ----------------       -------------------

A list with no elements in it is the empty list; it is identical to the symbol nil. In other words, nil is both a symbol and a list.

Here are examples of lists written in Lisp syntax:

(A 2 "A")            ; A list of three elements.
()                   ; A list of no elements (the empty list).
nil                  ; A list of no elements (the empty list).
("A ()")             ; A list of one element: the string "A ()".
(A ())               ; A list of two elements: A and the empty list.
(A nil)              ; Equivalent to the previous.
((A B C))            ; A list of one element
                     ;   (which is a list of three elements).

Here is the list (A ()), or equivalently (A nil), depicted with boxes and arrows:

    --- ---      --- ---
   |   |   |--> |   |   |--> nil
    --- ---      --- ---
     |            |
     |            |
      --> A        --> nil

Dotted Pair Notation

Dotted pair notation is an alternative syntax for cons cells that represents the CAR and CDR explicitly. In this syntax, (a . b) stands for a cons cell whose CAR is the object a, and whose CDR is the object b. Dotted pair notation is therefore more general than list syntax. In the dotted pair notation, the list `(1 2 3)' is written as `(1 . (2 . (3 . nil)))'. For nil-terminated lists, you can use either notation, but list notation is usually clearer and more convenient. When printing a list, the dotted pair notation is only used if the CDR of a cons cell is not a list.

Here's an example using boxes to illustrate dotted pair notation. This example shows the pair (rose . violet):

    --- ---
   |   |   |--> violet
    --- ---
     |
     |
      --> rose

You can combine dotted pair notation with list notation to represent conveniently a chain of cons cells with a non-nil final CDR. You write a dot after the last element of the list, followed by the CDR of the final cons cell. For example, (rose violet . buttercup) is equivalent to (rose . (violet . buttercup)). The object looks like this:

    --- ---      --- ---
   |   |   |--> |   |   |--> buttercup
    --- ---      --- ---
     |            |
     |            |
      --> rose     --> violet

The syntax (rose . violet . buttercup) is invalid because there is nothing that it could mean. If anything, it would say to put buttercup in the CDR of a cons cell whose CDR is already used for violet.

The list (rose violet) is equivalent to (rose . (violet)), and looks like this:

    --- ---      --- ---
   |   |   |--> |   |   |--> nil
    --- ---      --- ---
     |            |
     |            |
      --> rose     --> violet

Similarly, the three-element list (rose violet buttercup) is equivalent to (rose . (violet . (buttercup))).

Association List Type

An association list or alist is a specially-constructed list whose elements are cons cells. In each element, the CAR is considered a key, and the CDR is considered an associated value. (In some cases, the associated value is stored in the CAR of the CDR.) Association lists are often used as stacks, since it is easy to add or remove associations at the front of the list.

For example,

(setq alist-of-colors
      '((rose . red) (lily . white)  (buttercup . yellow)))

sets the variable alist-of-colors to an alist of three elements. In the first element, rose is the key and red is the value.

See section Association Lists, for a further explanation of alists and for functions that work on alists.

Array Type

An array is composed of an arbitrary number of slots for pointing to other Lisp objects, arranged in a contiguous block of memory. Accessing any element of an array takes approximately the same amount of time. In contrast, accessing an element of a list requires time proportional to the position of the element in the list. (Elements at the end of a list take longer to access than elements at the beginning of a list.)

Emacs defines four types of array: strings, vectors, bool-vectors, and char-tables.

A string is an array of characters and a vector is an array of arbitrary objects. A bool-vector can hold only t or nil. These kinds of array may have any length up to the largest integer. Char-tables are sparse arrays indexed by any valid character code; they can hold arbitrary objects.

The first element of an array has index zero, the second element has index 1, and so on. This is called zero-origin indexing. For example, an array of four elements has indices 0, 1, 2, and 3. The largest possible index value is one less than the length of the array. Once an array is created, its length is fixed.

All Emacs Lisp arrays are one-dimensional. (Most other programming languages support multidimensional arrays, but they are not essential; you can get the same effect with an array of arrays.) Each type of array has its own read syntax; see the following sections for details.

The array type is contained in the sequence type and contains the string type, the vector type, the bool-vector type, and the char-table type.

String Type

A string is an array of characters. Strings are used for many purposes in Emacs, as can be expected in a text editor; for example, as the names of Lisp symbols, as messages for the user, and to represent text extracted from buffers. Strings in Lisp are constants: evaluation of a string returns the same string.

See section Strings and Characters, for functions that operate on strings.

Syntax for Strings

The read syntax for strings is a double-quote, an arbitrary number of characters, and another double-quote, "like this". To include a double-quote in a string, precede it with a backslash; thus, "\"" is a string containing just a single double-quote character. Likewise, you can include a backslash by preceding it with another backslash, like this: "this \\ is a single embedded backslash".

The newline character is not special in the read syntax for strings; if you write a new line between the double-quotes, it becomes a character in the string. But an escaped newline--one that is preceded by `\'---does not become part of the string; i.e., the Lisp reader ignores an escaped newline while reading a string. An escaped space `\ ' is likewise ignored.

"It is useful to include newlines
in documentation strings,
but the newline is \
ignored if escaped."
     => "It is useful to include newlines 
in documentation strings, 
but the newline is ignored if escaped."

Non-ASCII Characters in Strings

You can include a non-ASCII international character in a string constant by writing it literally. There are two text representations for non-ASCII characters in Emacs strings (and in buffers): unibyte and multibyte. If the string constant is read from a multibyte source, such as a multibyte buffer or string, or a file that would be visited as multibyte, then the character is read as a multibyte character, and that makes the string multibyte. If the string constant is read from a unibyte source, then the character is read as unibyte and that makes the string unibyte.

You can also represent a multibyte non-ASCII character with its character code, using a hex escape, `\xnnnnnnn', with as many digits as necessary. (Multibyte non-ASCII character codes are all greater than 256.) Any character which is not a valid hex digit terminates this construct. If the character that would follow is a hex digit, write `\ ' (backslash and space) to terminate the hex escape--for example, `\x8e0\ ' represents one character, `a' with grave accent. `\ ' in a string constant is just like backslash-newline; it does not contribute any character to the string, but it does terminate the preceding hex escape.

Using a multibyte hex escape forces the string to multibyte. You can represent a unibyte non-ASCII character with its character code, which must be in the range from 128 (0200 octal) to 255 (0377 octal). This forces a unibyte string. See section Text Representations, for more information about the two text representations.

Nonprinting Characters in Strings

You can use the same backslash escape-sequences in a string constant as in character literals (but do not use the question mark that begins a character constant). For example, you can write a string containing the nonprinting characters tab and C-a, with commas and spaces between them, like this: "\t, \C-a". See section Character Type, for a description of the read syntax for characters.

However, not all of the characters you can write with backslash escape-sequences are valid in strings. The only control characters that a string can hold are the ASCII control characters. Strings do not distinguish case in ASCII control characters.

Properly speaking, strings cannot hold meta characters; but when a string is to be used as a key sequence, there is a special convention that provides a way to represent meta versions of ASCII characters in a string. If you use the `\M-' syntax to indicate a meta character in a string constant, this sets the bit of the character in the string. If the string is used in define-key or lookup-key, this numeric code is translated into the equivalent meta character. See section Character Type.

Strings cannot hold characters that have the hyper, super, or alt modifiers.

Text Properties in Strings

A string can hold properties for the characters it contains, in addition to the characters themselves. This enables programs that copy text between strings and buffers to copy the text's properties with no special effort. See section Text Properties, for an explanation of what text properties mean. Strings with text properties use a special read and print syntax:

#("characters" property-data...)

where property-data consists of zero or more elements, in groups of three as follows:

beg end plist

The elements beg and end are integers, and together specify a range of indices in the string; plist is the property list for that range. For example,

#("foo bar" 0 3 (face bold) 3 4 nil 4 7 (face italic))

represents a string whose textual contents are `foo bar', in which the first three characters have a face property with value bold, and the last three have a face property with value italic. (The fourth character has no text properties, so its property list is nil. It is not actually necessary to mention ranges with nil as the property list, since any characters not mentioned in any range will default to having no properties.)

Vector Type

A vector is a one-dimensional array of elements of any type. It takes a constant amount of time to access any element of a vector. (In a list, the access time of an element is proportional to the distance of the element from the beginning of the list.)

The printed representation of a vector consists of a left square bracket, the elements, and a right square bracket. This is also the read syntax. Like numbers and strings, vectors are considered constants for evaluation.

[1 "two" (three)]      ; A vector of three elements.
     => [1 "two" (three)]

See section Vectors, for functions that work with vectors.

Char-Table Type

A char-table is a one-dimensional array of elements of any type, indexed by character codes. Char-tables have certain extra features to make them more useful for many jobs that involve assigning information to character codes--for example, a char-table can have a parent to inherit from, a default value, and a small number of extra slots to use for special purposes. A char-table can also specify a single value for a whole character set.

The printed representation of a char-table is like a vector except that there is an extra `#^' at the beginning.

See section Char-Tables, for special functions to operate on char-tables. Uses of char-tables include:

Bool-Vector Type

A bool-vector is a one-dimensional array of elements that must be t or nil.

The printed representation of a Bool-vector is like a string, except that it begins with `#&' followed by the length. The string constant that follows actually specifies the contents of the bool-vector as a bitmap--each "character" in the string contains 8 bits, which specify the next 8 elements of the bool-vector (1 stands for t, and 0 for nil). The least significant bits of the character correspond to the lowest indices in the bool-vector. If the length is not a multiple of 8, the printed representation shows extra elements, but these extras really make no difference.

(make-bool-vector 3 t)
     => #&3"\007"
(make-bool-vector 3 nil)
     => #&3"\0"
;; These are equal since only the first 3 bits are used.
(equal #&3"\377" #&3"\007")
     => t

Function Type

Just as functions in other programming languages are executable, Lisp function objects are pieces of executable code. However, functions in Lisp are primarily Lisp objects, and only secondarily the text which represents them. These Lisp objects are lambda expressions: lists whose first element is the symbol lambda (see section Lambda Expressions).

In most programming languages, it is impossible to have a function without a name. In Lisp, a function has no intrinsic name. A lambda expression is also called an anonymous function (see section Anonymous Functions). A named function in Lisp is actually a symbol with a valid function in its function cell (see section Defining Functions).

Most of the time, functions are called when their names are written in Lisp expressions in Lisp programs. However, you can construct or obtain a function object at run time and then call it with the primitive functions funcall and apply. See section Calling Functions.

Macro Type

A Lisp macro is a user-defined construct that extends the Lisp language. It is represented as an object much like a function, but with different argument-passing semantics. A Lisp macro has the form of a list whose first element is the symbol macro and whose CDR is a Lisp function object, including the lambda symbol.

Lisp macro objects are usually defined with the built-in defmacro function, but any list that begins with macro is a macro as far as Emacs is concerned. See section Macros, for an explanation of how to write a macro.

Warning: Lisp macros and keyboard macros (see section Keyboard Macros) are entirely different things. When we use the word "macro" without qualification, we mean a Lisp macro, not a keyboard macro.

Primitive Function Type

A primitive function is a function callable from Lisp but written in the C programming language. Primitive functions are also called subrs or built-in functions. (The word "subr" is derived from "subroutine".) Most primitive functions evaluate all their arguments when they are called. A primitive function that does not evaluate all its arguments is called a special form (see section Special Forms).

It does not matter to the caller of a function whether the function is primitive. However, this does matter if you try to redefine a primitive with a function written in Lisp. The reason is that the primitive function may be called directly from C code. Calls to the redefined function from Lisp will use the new definition, but calls from C code may still use the built-in definition. Therefore, we discourage redefinition of primitive functions.

The term function refers to all Emacs functions, whether written in Lisp or C. See section Function Type, for information about the functions written in Lisp.

Primitive functions have no read syntax and print in hash notation with the name of the subroutine.

(symbol-function 'car)          ; Access the function cell
                                ;   of the symbol.
     => #<subr car>
(subrp (symbol-function 'car))  ; Is this a primitive function?
     => t                       ; Yes.

Byte-Code Function Type

The byte compiler produces byte-code function objects. Internally, a byte-code function object is much like a vector; however, the evaluator handles this data type specially when it appears as a function to be called. See section Byte Compilation, for information about the byte compiler.

The printed representation and read syntax for a byte-code function object is like that for a vector, with an additional `#' before the opening `['.

Autoload Type

An autoload object is a list whose first element is the symbol autoload. It is stored as the function definition of a symbol as a placeholder for the real definition; it says that the real definition is found in a file of Lisp code that should be loaded when necessary. The autoload object contains the name of the file, plus some other information about the real definition.

After the file has been loaded, the symbol should have a new function definition that is not an autoload object. The new definition is then called as if it had been there to begin with. From the user's point of view, the function call works as expected, using the function definition in the loaded file.

An autoload object is usually created with the function autoload, which stores the object in the function cell of a symbol. See section Autoload, for more details.

Editing Types

The types in the previous section are used for general programming purposes, and most of them are common to most Lisp dialects. Emacs Lisp provides several additional data types for purposes connected with editing.

Buffer Type

A buffer is an object that holds text that can be edited (see section Buffers). Most buffers hold the contents of a disk file (see section Files) so they can be edited, but some are used for other purposes. Most buffers are also meant to be seen by the user, and therefore displayed, at some time, in a window (see section Windows). But a buffer need not be displayed in any window.

The contents of a buffer are much like a string, but buffers are not used like strings in Emacs Lisp, and the available operations are different. For example, you can insert text efficiently into an existing buffer, whereas "inserting" text into a string requires concatenating substrings, and the result is an entirely new string object.

Each buffer has a designated position called point (see section Positions). At any time, one buffer is the current buffer. Most editing commands act on the contents of the current buffer in the neighborhood of point. Many of the standard Emacs functions manipulate or test the characters in the current buffer; a whole chapter in this manual is devoted to describing these functions (see section Text).

Several other data structures are associated with each buffer:

The local keymap and variable list contain entries that individually override global bindings or values. These are used to customize the behavior of programs in different buffers, without actually changing the programs.

A buffer may be indirect, which means it shares the text of another buffer, but presents it differently. See section Indirect Buffers.

Buffers have no read syntax. They print in hash notation, showing the buffer name.

(current-buffer)
     => #<buffer objects.texi>

Marker Type

A marker denotes a position in a specific buffer. Markers therefore have two components: one for the buffer, and one for the position. Changes in the buffer's text automatically relocate the position value as necessary to ensure that the marker always points between the same two characters in the buffer.

Markers have no read syntax. They print in hash notation, giving the current character position and the name of the buffer.

(point-marker)
     => #<marker at 10779 in objects.texi>

See section Markers, for information on how to test, create, copy, and move markers.

Window Type

A window describes the portion of the terminal screen that Emacs uses to display a buffer. Every window has one associated buffer, whose contents appear in the window. By contrast, a given buffer may appear in one window, no window, or several windows.

Though many windows may exist simultaneously, at any time one window is designated the selected window. This is the window where the cursor is (usually) displayed when Emacs is ready for a command. The selected window usually displays the current buffer, but this is not necessarily the case.

Windows are grouped on the screen into frames; each window belongs to one and only one frame. See section Frame Type.

Windows have no read syntax. They print in hash notation, giving the window number and the name of the buffer being displayed. The window numbers exist to identify windows uniquely, since the buffer displayed in any given window can change frequently.

(selected-window)
     => #<window 1 on objects.texi>

See section Windows, for a description of the functions that work on windows.

Frame Type

A frame is a rectangle on the screen that contains one or more Emacs windows. A frame initially contains a single main window (plus perhaps a minibuffer window) which you can subdivide vertically or horizontally into smaller windows.

Frames have no read syntax. They print in hash notation, giving the frame's title, plus its address in core (useful to identify the frame uniquely).

(selected-frame)
     => #<frame [email protected] 0xdac80>

See section Frames, for a description of the functions that work on frames.

Window Configuration Type

A window configuration stores information about the positions, sizes, and contents of the windows in a frame, so you can recreate the same arrangement of windows later.

Window configurations do not have a read syntax; their print syntax looks like `#<window-configuration>'. See section Window Configurations, for a description of several functions related to window configurations.

Frame Configuration Type

A frame configuration stores information about the positions, sizes, and contents of the windows in all frames. It is actually a list whose CAR is frame-configuration and whose CDR is an alist. Each alist element describes one frame, which appears as the CAR of that element.

See section Frame Configurations, for a description of several functions related to frame configurations.

Process Type

The word process usually means a running program. Emacs itself runs in a process of this sort. However, in Emacs Lisp, a process is a Lisp object that designates a subprocess created by the Emacs process. Programs such as shells, GDB, ftp, and compilers, running in subprocesses of Emacs, extend the capabilities of Emacs.

An Emacs subprocess takes textual input from Emacs and returns textual output to Emacs for further manipulation. Emacs can also send signals to the subprocess.

Process objects have no read syntax. They print in hash notation, giving the name of the process:

(process-list)
     => (#<process shell>)

See section Processes, for information about functions that create, delete, return information about, send input or signals to, and receive output from processes.

Stream Type

A stream is an object that can be used as a source or sink for characters--either to supply characters for input or to accept them as output. Many different types can be used this way: markers, buffers, strings, and functions. Most often, input streams (character sources) obtain characters from the keyboard, a buffer, or a file, and output streams (character sinks) send characters to a buffer, such as a `*Help*' buffer, or to the echo area.

The object nil, in addition to its other meanings, may be used as a stream. It stands for the value of the variable standard-input or standard-output. Also, the object t as a stream specifies input using the minibuffer (see section Minibuffers) or output in the echo area (see section The Echo Area).

Streams have no special printed representation or read syntax, and print as whatever primitive type they are.

See section Reading and Printing Lisp Objects, for a description of functions related to streams, including parsing and printing functions.

Keymap Type

A keymap maps keys typed by the user to commands. This mapping controls how the user's command input is executed. A keymap is actually a list whose CAR is the symbol keymap.

See section Keymaps, for information about creating keymaps, handling prefix keys, local as well as global keymaps, and changing key bindings.

Overlay Type

An overlay specifies properties that apply to a part of a buffer. Each overlay applies to a specified range of the buffer, and contains a property list (a list whose elements are alternating property names and values). Overlay properties are used to present parts of the buffer temporarily in a different display style. Overlays have no read syntax, and print in hash notation, giving the buffer name and range of positions.

See section Overlays, for how to create and use overlays.

Type Predicates

The Emacs Lisp interpreter itself does not perform type checking on the actual arguments passed to functions when they are called. It could not do so, since function arguments in Lisp do not have declared data types, as they do in other programming languages. It is therefore up to the individual function to test whether each actual argument belongs to a type that the function can use.

All built-in functions do check the types of their actual arguments when appropriate, and signal a wrong-type-argument error if an argument is of the wrong type. For example, here is what happens if you pass an argument to + that it cannot handle:

(+ 2 'a)
     error--> Wrong type argument: number-or-marker-p, a

If you want your program to handle different types differently, you must do explicit type checking. The most common way to check the type of an object is to call a type predicate function. Emacs has a type predicate for each type, as well as some predicates for combinations of types.

A type predicate function takes one argument; it returns t if the argument belongs to the appropriate type, and nil otherwise. Following a general Lisp convention for predicate functions, most type predicates' names end with `p'.

Here is an example which uses the predicates listp to check for a list and symbolp to check for a symbol.

(defun add-on (x)
  (cond ((symbolp x)
         ;; If X is a symbol, put it on LIST.
         (setq list (cons x list)))
        ((listp x)
         ;; If X is a list, add its elements to LIST.
         (setq list (append x list)))
        (t
         ;; We handle only symbols and lists.
         (error "Invalid argument %s in add-on" x))))

Here is a table of predefined type predicates, in alphabetical order, with references to further information.

atom
See section Predicates on Lists.
arrayp
See section Functions that Operate on Arrays.
bool-vector-p
See section Bool-vectors.
bufferp
See section Buffer Basics.
byte-code-function-p
See section Byte-Code Function Type.
case-table-p
See section The Case Table.
char-or-string-p
See section The Predicates for Strings.
char-table-p
See section Char-Tables.
commandp
See section Interactive Call.
consp
See section Predicates on Lists.
display-table-p
See section Display Tables.
floatp
See section Type Predicates for Numbers.
frame-configuration-p
See section Frame Configurations.
frame-live-p
See section Deleting Frames.
framep
See section Frames.
functionp
See section Functions.
integer-or-marker-p
See section Predicates on Markers.
integerp
See section Type Predicates for Numbers.
keymapp
See section Creating Keymaps.
listp
See section Predicates on Lists.
markerp
See section Predicates on Markers.
wholenump
See section Type Predicates for Numbers.
nlistp
See section Predicates on Lists.
numberp
See section Type Predicates for Numbers.
number-or-marker-p
See section Predicates on Markers.
overlayp
See section Overlays.
processp
See section Processes.
sequencep
See section Sequences.
stringp
See section The Predicates for Strings.
subrp
See section Accessing Function Cell Contents.
symbolp
See section Symbols.
syntax-table-p
See section Syntax Tables.
user-variable-p
See section Defining Global Variables.
vectorp
See section Vectors.
window-configuration-p
See section Window Configurations.
window-live-p
See section Deleting Windows.
windowp
See section Basic Concepts of Emacs Windows.

The most general way to check the type of an object is to call the function type-of. Recall that each object belongs to one and only one primitive type; type-of tells you which one (see section Lisp Data Types). But type-of knows nothing about non-primitive types. In most cases, it is more convenient to use type predicates than type-of.

Function: type-of object
This function returns a symbol naming the primitive type of object. The value is one of the symbols symbol, integer, float, string, cons, vector, char-table, bool-vector, subr, compiled-function, marker, overlay, window, buffer, frame, process, or window-configuration.

(type-of 1)
     => integer
(type-of 'nil)
     => symbol
(type-of '())    ; () is nil.
     => symbol
(type-of '(x))
     => cons

Equality Predicates

Here we describe two functions that test for equality between any two objects. Other functions test equality between objects of specific types, e.g., strings. For these predicates, see the appropriate chapter describing the data type.

Function: eq object1 object2
This function returns t if object1 and object2 are the same object, nil otherwise. The "same object" means that a change in one will be reflected by the same change in the other.

eq returns t if object1 and object2 are integers with the same value. Also, since symbol names are normally unique, if the arguments are symbols with the same name, they are eq. For other types (e.g., lists, vectors, strings), two arguments with the same contents or elements are not necessarily eq to each other: they are eq only if they are the same object.

(eq 'foo 'foo)
     => t

(eq 456 456)
     => t

(eq "asdf" "asdf")
     => nil

(eq '(1 (2 (3))) '(1 (2 (3))))
     => nil

(setq foo '(1 (2 (3))))
     => (1 (2 (3)))
(eq foo foo)
     => t
(eq foo '(1 (2 (3))))
     => nil

(eq [(1 2) 3] [(1 2) 3])
     => nil

(eq (point-marker) (point-marker))
     => nil

The make-symbol function returns an uninterned symbol, distinct from the symbol that is used if you write the name in a Lisp expression. Distinct symbols with the same name are not eq. See section Creating and Interning Symbols.

(eq (make-symbol "foo") 'foo)
     => nil

Function: equal object1 object2
This function returns t if object1 and object2 have equal components, nil otherwise. Whereas eq tests if its arguments are the same object, equal looks inside nonidentical arguments to see if their elements are the same. So, if two objects are eq, they are equal, but the converse is not always true.

(equal 'foo 'foo)
     => t

(equal 456 456)
     => t

(equal "asdf" "asdf")
     => t
(eq "asdf" "asdf")
     => nil

(equal '(1 (2 (3))) '(1 (2 (3))))
     => t
(eq '(1 (2 (3))) '(1 (2 (3))))
     => nil

(equal [(1 2) 3] [(1 2) 3])
     => t
(eq [(1 2) 3] [(1 2) 3])
     => nil

(equal (point-marker) (point-marker))
     => t

(eq (point-marker) (point-marker))
     => nil

Comparison of strings is case-sensitive, but does not take account of text properties--it compares only the characters in the strings. A unibyte string never equals a multibyte string unless the contents are entirely ASCII (see section Text Representations).

(equal "asdf" "ASDF")
     => nil

Two distinct buffers are never equal, even if their contents are the same.

The test for equality is implemented recursively, and circular lists may therefore cause infinite recursion (leading to an error).

Numbers

GNU Emacs supports two numeric data types: integers and floating point numbers. Integers are whole numbers such as -3, 0, 7, 13, and 511. Their values are exact. Floating point numbers are numbers with fractional parts, such as -4.5, 0.0, or 2.71828. They can also be expressed in exponential notation: 1.5e2 equals 150; in this example, `e2' stands for ten to the second power, and that is multiplied by 1.5. Floating point values are not exact; they have a fixed, limited amount of precision.

Integer Basics

The range of values for an integer depends on the machine. The minimum range is -134217728 to 134217727 (28 bits; i.e., to but some machines may provide a wider range. Many examples in this chapter assume an integer has 28 bits.

The Lisp reader reads an integer as a sequence of digits with optional initial sign and optional final period.

 1               ; The integer 1.
 1.              ; The integer 1.
+1               ; Also the integer 1.
-1               ; The integer -1.
 268435457       ; Also the integer 1, due to overflow.
 0               ; The integer 0.
-0               ; The integer 0.

To understand how various functions work on integers, especially the bitwise operators (see section Bitwise Operations on Integers), it is often helpful to view the numbers in their binary form.

In 28-bit binary, the decimal integer 5 looks like this:

0000  0000 0000  0000 0000  0000 0101

(We have inserted spaces between groups of 4 bits, and two spaces between groups of 8 bits, to make the binary integer easier to read.)

The integer -1 looks like this:

1111  1111 1111  1111 1111  1111 1111

-1 is represented as 28 ones. (This is called two's complement notation.)

The negative integer, -5, is creating by subtracting 4 from -1. In binary, the decimal integer 4 is 100. Consequently, -5 looks like this:

1111  1111 1111  1111 1111  1111 1011

In this implementation, the largest 28-bit binary integer value is 134,217,727 in decimal. In binary, it looks like this:

0111  1111 1111  1111 1111  1111 1111

Since the arithmetic functions do not check whether integers go outside their range, when you add 1 to 134,217,727, the value is the negative integer -134,217,728:

(+ 1 134217727)
     => -134217728
     => 1000  0000 0000  0000 0000  0000 0000

Many of the functions described in this chapter accept markers for arguments in place of numbers. (See section Markers.) Since the actual arguments to such functions may be either numbers or markers, we often give these arguments the name number-or-marker. When the argument value is a marker, its position value is used and its buffer is ignored.

Floating Point Basics

Floating point numbers are useful for representing numbers that are not integral. The precise range of floating point numbers is machine-specific; it is the same as the range of the C data type double on the machine you are using.

The read-syntax for floating point numbers requires either a decimal point (with at least one digit following), an exponent, or both. For example, `1500.0', `15e2', `15.0e2', `1.5e3', and `.15e4' are five ways of writing a floating point number whose value is 1500. They are all equivalent. You can also use a minus sign to write negative floating point numbers, as in `-1.0'.

Most modern computers support the IEEE floating point standard, which provides for positive infinity and negative infinity as floating point values. It also provides for a class of values called NaN or "not-a-number"; numerical functions return such values in cases where there is no correct answer. For example, (sqrt -1.0) returns a NaN. For practical purposes, there's no significant difference between different NaN values in Emacs Lisp, and there's no rule for precisely which NaN value should be used in a particular case, so Emacs Lisp doesn't try to distinguish them. Here are the read syntaxes for these special floating point values:

positive infinity
`1.0e+INF'
negative infinity
`-1.0e+INF'
Not-a-number
`0.0e+NaN'.

In addition, the value -0.0 is distinguishable from ordinary zero in IEEE floating point (although equal and = consider them equal values).

You can use logb to extract the binary exponent of a floating point number (or estimate the logarithm of an integer):

Function: logb number
This function returns the binary exponent of number. More precisely, the value is the logarithm of number base 2, rounded down to an integer.

(logb 10)
     => 3
(logb 10.0e20)
     => 69

Type Predicates for Numbers

The functions in this section test whether the argument is a number or whether it is a certain sort of number. The functions integerp and floatp can take any type of Lisp object as argument (the predicates would not be of much use otherwise); but the zerop predicate requires a number as its argument. See also integer-or-marker-p and number-or-marker-p, in section Predicates on Markers.

Function: floatp object
This predicate tests whether its argument is a floating point number and returns t if so, nil otherwise.

floatp does not exist in Emacs versions 18 and earlier.

Function: integerp object
This predicate tests whether its argument is an integer, and returns t if so, nil otherwise.

Function: numberp object
This predicate tests whether its argument is a number (either integer or floating point), and returns t if so, nil otherwise.

Function: wholenump object
The wholenump predicate (whose name comes from the phrase "whole-number-p") tests to see whether its argument is a nonnegative integer, and returns t if so, nil otherwise. 0 is considered non-negative.

natnump is an obsolete synonym for wholenump.

Function: zerop number
This predicate tests whether its argument is zero, and returns t if so, nil otherwise. The argument must be a number.

These two forms are equivalent: (zerop x) == (= x 0).

Comparison of Numbers

To test numbers for numerical equality, you should normally use =, not eq. There can be many distinct floating point number objects with the same numeric value. If you use eq to compare them, then you test whether two values are the same object. By contrast, = compares only the numeric values of the objects.

At present, each integer value has a unique Lisp object in Emacs Lisp. Therefore, eq is equivalent to = where integers are concerned. It is sometimes convenient to use eq for comparing an unknown value with an integer, because eq does not report an error if the unknown value is not a number--it accepts arguments of any type. By contrast, = signals an error if the arguments are not numbers or markers. However, it is a good idea to use = if you can, even for comparing integers, just in case we change the representation of integers in a future Emacs version.

Sometimes it is useful to compare numbers with equal; it treats two numbers as equal if they have the same data type (both integers, or both floating point) and the same value. By contrast, = can treat an integer and a floating point number as equal.

There is another wrinkle: because floating point arithmetic is not exact, it is often a bad idea to check for equality of two floating point values. Usually it is better to test for approximate equality. Here's a function to do this:

(defvar fuzz-factor 1.0e-6)
(defun approx-equal (x y)
  (or (and (= x 0) (= y 0))
      (< (/ (abs (- x y))
            (max (abs x) (abs y)))
         fuzz-factor)))

Common Lisp note: Comparing numbers in Common Lisp always requires = because Common Lisp implements multi-word integers, and two distinct integer objects can have the same numeric value. Emacs Lisp can have just one integer object for any given value because it has a limited range of integer values.

Function: = number-or-marker1 number-or-marker2
This function tests whether its arguments are numerically equal, and returns t if so, nil otherwise.

Function: /= number-or-marker1 number-or-marker2
This function tests whether its arguments are numerically equal, and returns t if they are not, and nil if they are.

Function: < number-or-marker1 number-or-marker2
This function tests whether its first argument is strictly less than its second argument. It returns t if so, nil otherwise.

Function: <= number-or-marker1 number-or-marker2
This function tests whether its first argument is less than or equal to its second argument. It returns t if so, nil otherwise.

Function: > number-or-marker1 number-or-marker2
This function tests whether its first argument is strictly greater than its second argument. It returns t if so, nil otherwise.

Function: >= number-or-marker1 number-or-marker2
This function tests whether its first argument is greater than or equal to its second argument. It returns t if so, nil otherwise.

Function: max number-or-marker &rest numbers-or-markers
This function returns the largest of its arguments.

(max 20)
     => 20
(max 1 2.5)
     => 2.5
(max 1 3 2.5)
     => 3

Function: min number-or-marker &rest numbers-or-markers
This function returns the smallest of its arguments.

(min -4 1)
     => -4

Function: abs number
This function returns the absolute value of number.

Numeric Conversions

To convert an integer to floating point, use the function float.

Function: float number
This returns number converted to floating point. If number is already a floating point number, float returns it unchanged.

There are four functions to convert floating point numbers to integers; they differ in how they round. These functions accept integer arguments also, and return such arguments unchanged.

Function: truncate number
This returns number, converted to an integer by rounding towards zero.

Function: floor number &optional divisor
This returns number, converted to an integer by rounding downward (towards negative infinity).

If divisor is specified, number is divided by divisor before the floor is taken; this uses the kind of division operation that corresponds to mod, rounding downward. An arith-error results if divisor is 0.

Function: ceiling number
This returns number, converted to an integer by rounding upward (towards positive infinity).

Function: round number
This returns number, converted to an integer by rounding towards the nearest integer. Rounding a value equidistant between two integers may choose the integer closer to zero, or it may prefer an even integer, depending on your machine.

Arithmetic Operations

Emacs Lisp provides the traditional four arithmetic operations: addition, subtraction, multiplication, and division. Remainder and modulus functions supplement the division functions. The functions to add or subtract 1 are provided because they are traditional in Lisp and commonly used.

All of these functions except % return a floating point value if any argument is floating.

It is important to note that in Emacs Lisp, arithmetic functions do not check for overflow. Thus (1+ 134217727) may evaluate to -134217728, depending on your hardware.

Function: 1+ number-or-marker
This function returns number-or-marker plus 1. For example,

(setq foo 4)
     => 4
(1+ foo)
     => 5

This function is not analogous to the C operator ++---it does not increment a variable. It just computes a sum. Thus, if we continue,

foo
     => 4

If you want to increment the variable, you must use setq, like this:

(setq foo (1+ foo))
     => 5

Function: 1- number-or-marker
This function returns number-or-marker minus 1.

Function: + &rest numbers-or-markers
This function adds its arguments together. When given no arguments, + returns 0.

(+)
     => 0
(+ 1)
     => 1
(+ 1 2 3 4)
     => 10

Function: - &optional number-or-marker &rest more-numbers-or-markers
The - function serves two purposes: negation and subtraction. When - has a single argument, the value is the negative of the argument. When there are multiple arguments, - subtracts each of the more-numbers-or-markers from number-or-marker, cumulatively. If there are no arguments, the result is 0.

(- 10 1 2 3 4)
     => 0
(- 10)
     => -10
(-)
     => 0

Function: * &rest numbers-or-markers
This function multiplies its arguments together, and returns the product. When given no arguments, * returns 1.

(*)
     => 1
(* 1)
     => 1
(* 1 2 3 4)
     => 24

Function: / dividend divisor &rest divisors
This function divides dividend by divisor and returns the quotient. If there are additional arguments divisors, then it divides dividend by each divisor in turn. Each argument may be a number or a marker.

If all the arguments are integers, then the result is an integer too. This means the result has to be rounded. On most machines, the result is rounded towards zero after each division, but some machines may round differently with negative arguments. This is because the Lisp function / is implemented using the C division operator, which also permits machine-dependent rounding. As a practical matter, all known machines round in the standard fashion.

If you divide an integer by 0, an arith-error error is signaled. (See section Errors.) Floating point division by zero returns either infinity or a NaN if your machine supports IEEE floating point; otherwise, it signals an arith-error error.

(/ 6 2)
     => 3
(/ 5 2)
     => 2
(/ 5.0 2)
     => 2.5
(/ 5 2.0)
     => 2.5
(/ 5.0 2.0)
     => 2.5
(/ 25 3 2)
     => 4
(/ -17 6)
     => -2

The result of (/ -17 6) could in principle be -3 on some machines.

Function: % dividend divisor
This function returns the integer remainder after division of dividend by divisor. The arguments must be integers or markers.

For negative arguments, the remainder is in principle machine-dependent since the quotient is; but in practice, all known machines behave alike.

An arith-error results if divisor is 0.

(% 9 4)
     => 1
(% -9 4)
     => -1
(% 9 -4)
     => 1
(% -9 -4)
     => -1

For any two integers dividend and divisor,

(+ (% dividend divisor)
   (* (/ dividend divisor) divisor))

always equals dividend.

Function: mod dividend divisor
This function returns the value of dividend modulo divisor; in other words, the remainder after division of dividend by divisor, but with the same sign as divisor. The arguments must be numbers or markers.

Unlike %, mod returns a well-defined result for negative arguments. It also permits floating point arguments; it rounds the quotient downward (towards minus infinity) to an integer, and uses that quotient to compute the remainder.

An arith-error results if divisor is 0.

(mod 9 4)
     => 1
(mod -9 4)
     => 3
(mod 9 -4)
     => -3
(mod -9 -4)
     => -1
(mod 5.5 2.5)
     => .5

For any two numbers dividend and divisor,

(+ (mod dividend divisor)
   (* (floor dividend divisor) divisor))

always equals dividend, subject to rounding error if either argument is floating point. For floor, see section Numeric Conversions.

Rounding Operations

The functions ffloor, fceiling, fround, and ftruncate take a floating point argument and return a floating point result whose value is a nearby integer. ffloor returns the nearest integer below; fceiling, the nearest integer above; ftruncate, the nearest integer in the direction towards zero; fround, the nearest integer.

Function: ffloor float
This function rounds float to the next lower integral value, and returns that value as a floating point number.

Function: fceiling float
This function rounds float to the next higher integral value, and returns that value as a floating point number.

Function: ftruncate float
This function rounds float towards zero to an integral value, and returns that value as a floating point number.

Function: fround float
This function rounds float to the nearest integral value, and returns that value as a floating point number.

Bitwise Operations on Integers

In a computer, an integer is represented as a binary number, a sequence of bits (digits which are either zero or one). A bitwise operation acts on the individual bits of such a sequence. For example, shifting moves the whole sequence left or right one or more places, reproducing the same pattern "moved over".

The bitwise operations in Emacs Lisp apply only to integers.

Function: lsh integer1 count
lsh, which is an abbreviation for logical shift, shifts the bits in integer1 to the left count places, or to the right if count is negative, bringing zeros into the vacated bits. If count is negative, lsh shifts zeros into the leftmost (most-significant) bit, producing a positive result even if integer1 is negative. Contrast this with ash, below.

Here are two examples of lsh, shifting a pattern of bits one place to the left. We show only the low-order eight bits of the binary pattern; the rest are all zero.

(lsh 5 1)
     => 10
;; Decimal 5 becomes decimal 10.
00000101 => 00001010

(lsh 7 1)
     => 14
;; Decimal 7 becomes decimal 14.
00000111 => 00001110

As the examples illustrate, shifting the pattern of bits one place to the left produces a number that is twice the value of the previous number.

Shifting a pattern of bits two places to the left produces results like this (with 8-bit binary numbers):

(lsh 3 2)
     => 12
;; Decimal 3 becomes decimal 12.
00000011 => 00001100       

On the other hand, shifting one place to the right looks like this:

(lsh 6 -1)
     => 3
;; Decimal 6 becomes decimal 3.
00000110 => 00000011       

(lsh 5 -1)
     => 2
;; Decimal 5 becomes decimal 2.
00000101 => 00000010       

As the example illustrates, shifting one place to the right divides the value of a positive integer by two, rounding downward.

The function lsh, like all Emacs Lisp arithmetic functions, does not check for overflow, so shifting left can discard significant bits and change the sign of the number. For example, left shifting 134,217,727 produces -2 on a 28-bit machine:

(lsh 134217727 1)          ; left shift
     => -2

In binary, in the 28-bit implementation, the argument looks like this:

;; Decimal 134,217,727
0111  1111 1111  1111 1111  1111 1111         

which becomes the following when left shifted:

;; Decimal -2
1111  1111 1111  1111 1111  1111 1110         

Function: ash integer1 count
ash (arithmetic shift) shifts the bits in integer1 to the left count places, or to the right if count is negative.

ash gives the same results as lsh except when integer1 and count are both negative. In that case, ash puts ones in the empty bit positions on the left, while lsh puts zeros in those bit positions.

Thus, with ash, shifting the pattern of bits one place to the right looks like this:

(ash -6 -1) => -3            
;; Decimal -6 becomes decimal -3.
1111  1111 1111  1111 1111  1111 1010
     => 
1111  1111 1111  1111 1111  1111 1101

In contrast, shifting the pattern of bits one place to the right with lsh looks like this:

(lsh -6 -1) => 134217725
;; Decimal -6 becomes decimal 134,217,725.
1111  1111 1111  1111 1111  1111 1010
     => 
0111  1111 1111  1111 1111  1111 1101

Here are other examples:

                   ;               28-bit binary values

(lsh 5 2)          ;   5  =  0000  0000 0000  0000 0000  0000 0101
     => 20         ;      =  0000  0000 0000  0000 0000  0001 0100
(ash 5 2)
     => 20
(lsh -5 2)         ;  -5  =  1111  1111 1111  1111 1111  1111 1011
     => -20        ;      =  1111  1111 1111  1111 1111  1110 1100
(ash -5 2)
     => -20
(lsh 5 -2)         ;   5  =  0000  0000 0000  0000 0000  0000 0101
     => 1          ;      =  0000  0000 0000  0000 0000  0000 0001
(ash 5 -2)
     => 1
(lsh -5 -2)        ;  -5  =  1111  1111 1111  1111 1111  1111 1011
     => 4194302    ;      =  0011  1111 1111  1111 1111  1111 1110
(ash -5 -2)        ;  -5  =  1111  1111 1111  1111 1111  1111 1011
     => -2         ;      =  1111  1111 1111  1111 1111  1111 1110

Function: logand &rest ints-or-markers
This function returns the "logical and" of the arguments: the nth bit is set in the result if, and only if, the nth bit is set in all the arguments. ("Set" means that the value of the bit is 1 rather than 0.)

For example, using 4-bit binary numbers, the "logical and" of 13 and 12 is 12: 1101 combined with 1100 produces 1100. In both the binary numbers, the leftmost two bits are set (i.e., they are 1's), so the leftmost two bits of the returned value are set. However, for the rightmost two bits, each is zero in at least one of the arguments, so the rightmost two bits of the returned value are 0's.

Therefore,

(logand 13 12)
     => 12

If logand is not passed any argument, it returns a value of -1. This number is an identity element for logand because its binary representation consists entirely of ones. If logand is passed just one argument, it returns that argument.

                   ;                28-bit binary values

(logand 14 13)     ; 14  =  0000  0000 0000  0000 0000  0000 1110
                   ; 13  =  0000  0000 0000  0000 0000  0000 1101
     => 12         ; 12  =  0000  0000 0000  0000 0000  0000 1100

(logand 14 13 4)   ; 14  =  0000  0000 0000  0000 0000  0000 1110
                   ; 13  =  0000  0000 0000  0000 0000  0000 1101
                   ;  4  =  0000  0000 0000  0000 0000  0000 0100
     => 4          ;  4  =  0000  0000 0000  0000 0000  0000 0100

(logand)
     => -1         ; -1  =  1111  1111 1111  1111 1111  1111 1111

Function: logior &rest ints-or-markers
This function returns the "inclusive or" of its arguments: the nth bit is set in the result if, and only if, the nth bit is set in at least one of the arguments. If there are no arguments, the result is zero, which is an identity element for this operation. If logior is passed just one argument, it returns that argument.

                   ;               28-bit binary values

(logior 12 5)      ; 12  =  0000  0000 0000  0000 0000  0000 1100
                   ;  5  =  0000  0000 0000  0000 0000  0000 0101
     => 13         ; 13  =  0000  0000 0000  0000 0000  0000 1101

(logior 12 5 7)    ; 12  =  0000  0000 0000  0000 0000  0000 1100
                   ;  5  =  0000  0000 0000  0000 0000  0000 0101
                   ;  7  =  0000  0000 0000  0000 0000  0000 0111
     => 15         ; 15  =  0000  0000 0000  0000 0000  0000 1111

Function: logxor &rest ints-or-markers
This function returns the "exclusive or" of its arguments: the nth bit is set in the result if, and only if, the nth bit is set in an odd number of the arguments. If there are no arguments, the result is 0, which is an identity element for this operation. If logxor is passed just one argument, it returns that argument.

                   ;               28-bit binary values

(logxor 12 5)      ; 12  =  0000  0000 0000  0000 0000  0000 1100
                   ;  5  =  0000  0000 0000  0000 0000  0000 0101
     => 9          ;  9  =  0000  0000 0000  0000 0000  0000 1001

(logxor 12 5 7)    ; 12  =  0000  0000 0000  0000 0000  0000 1100
                   ;  5  =  0000  0000 0000  0000 0000  0000 0101
                   ;  7  =  0000  0000 0000  0000 0000  0000 0111
     => 14         ; 14  =  0000  0000 0000  0000 0000  0000 1110

Function: lognot integer
This function returns the logical complement of its argument: the nth bit is one in the result if, and only if, the nth bit is zero in integer, and vice-versa.

(lognot 5)             
     => -6
;;  5  =  0000  0000 0000  0000 0000  0000 0101
;; becomes
;; -6  =  1111  1111 1111  1111 1111  1111 1010

Standard Mathematical Functions

These mathematical functions allow integers as well as floating point numbers as arguments.

Function: sin arg
Function: cos arg
Function: tan arg
These are the ordinary trigonometric functions, with argument measured in radians.

Function: asin arg
The value of (asin arg) is a number between -pi/2 and pi/2 (inclusive) whose sine is arg; if, however, arg is out of range (outside [-1, 1]), then the result is a NaN.

Function: acos arg
The value of (acos arg) is a number between 0 and pi (inclusive) whose cosine is arg; if, however, arg is out of range (outside [-1, 1]), then the result is a NaN.

Function: atan arg
The value of (atan arg) is a number between -pi/2 and pi/2 (exclusive) whose tangent is arg.

Function: exp arg
This is the exponential function; it returns to the power arg. is a fundamental mathematical constant also called the base of natural logarithms.

Function: log arg &optional base
This function returns the logarithm of arg, with base base. If you don't specify base, the base is used. If arg is negative, the result is a NaN.

Function: log10 arg
This function returns the logarithm of arg, with base 10. If arg is negative, the result is a NaN. (log10 x) == (log x 10), at least approximately.

Function: expt x y
This function returns x raised to power y. If both arguments are integers and y is positive, the result is an integer; in this case, it is truncated to fit the range of possible integer values.

Function: sqrt arg
This returns the square root of arg. If arg is negative, the value is a NaN.

Random Numbers

A deterministic computer program cannot generate true random numbers. For most purposes, pseudo-random numbers suffice. A series of pseudo-random numbers is generated in a deterministic fashion. The numbers are not truly random, but they have certain properties that mimic a random series. For example, all possible values occur equally often in a pseudo-random series.

In Emacs, pseudo-random numbers are generated from a "seed" number. Starting from any given seed, the random function always generates the same sequence of numbers. Emacs always starts with the same seed value, so the sequence of values of random is actually the same in each Emacs run! For example, in one operating system, the first call to (random) after you start Emacs always returns -1457731, and the second one always returns -7692030. This repeatability is helpful for debugging.

If you want truly unpredictable random numbers, execute (random t). This chooses a new seed based on the current time of day and on Emacs's process ID number.

Function: random &optional limit
This function returns a pseudo-random integer. Repeated calls return a series of pseudo-random integers.

If limit is a positive integer, the value is chosen to be nonnegative and less than limit.

If limit is t, it means to choose a new seed based on the current time of day and on Emacs's process ID number.

On some machines, any integer representable in Lisp may be the result of random. On other machines, the result can never be larger than a certain maximum or less than a certain (negative) minimum.

Strings and Characters

A string in Emacs Lisp is an array that contains an ordered sequence of characters. Strings are used as names of symbols, buffers, and files, to send messages to users, to hold text being copied between buffers, and for many other purposes. Because strings are so important, Emacs Lisp has many functions expressly for manipulating them. Emacs Lisp programs use strings more often than individual characters.

See section Putting Keyboard Events in Strings, for special considerations for strings of keyboard character events.

String and Character Basics

Strings in Emacs Lisp are arrays that contain an ordered sequence of characters. Characters are represented in Emacs Lisp as integers; whether an integer is a character or not is determined only by how it is used. Thus, strings really contain integers.

The length of a string (like any array) is fixed, and cannot be altered once the string exists. Strings in Lisp are not terminated by a distinguished character code. (By contrast, strings in C are terminated by a character with ASCII code 0.)

Since strings are arrays, and therefore sequences as well, you can operate on them with the general array and sequence functions. (See section Sequences, Arrays, and Vectors.) For example, you can access or change individual characters in a string using the functions aref and aset (see section Functions that Operate on Arrays).

There are two text representations for non-ASCII characters in Emacs strings (and in buffers): unibyte and multibyte (see section Text Representations). ASCII characters always occupy one byte in a string; in fact, there is no real difference between the two representation for a string which is all ASCII. For most Lisp programming, you don't need to be concerned with these two representations.

Sometimes key sequences are represented as strings. When a string is a key sequence, string elements in the range 128 to 255 represent meta characters (which are extremely large integers) rather than character codes in the range 128 to 255.

Strings cannot hold characters that have the hyper, super or alt modifiers; they can hold ASCII control characters, but no other control characters. They do not distinguish case in ASCII control characters. If you want to store such characters in a sequence, such as a key sequence, you must use a vector instead of a string. See section Character Type, for more information about representation of meta and other modifiers for keyboard input characters.

Strings are useful for holding regular expressions. You can also match regular expressions against strings (see section Regular Expression Searching). The functions match-string (see section Simple Match Data Access) and replace-match (see section Replacing the Text That Matched) are useful for decomposing and modifying strings based on regular expression matching.

Like a buffer, a string can contain text properties for the characters in it, as well as the characters themselves. See section Text Properties. All the Lisp primitives that copy text from strings to buffers or other strings also copy the properties of the characters being copied.

See section Text, for information about functions that display strings or copy them into buffers. See section Character Type, and section String Type, for information about the syntax of characters and strings. See section Non-ASCII Characters, for functions to convert between text representations and encode and decode character codes.

The Predicates for Strings

For more information about general sequence and array predicates, see section Sequences, Arrays, and Vectors, and section Arrays.

Function: stringp object
This function returns t if object is a string, nil otherwise.

Function: char-or-string-p object
This function returns t if object is a string or a character (i.e., an integer), nil otherwise.

Creating Strings

The following functions create strings, either from scratch, or by putting strings together, or by taking them apart.

Function: make-string count character
This function returns a string made up of count repetitions of character. If count is negative, an error is signaled.

(make-string 5 ?x)
     => "xxxxx"
(make-string 0 ?x)
     => ""

Other functions to compare with this one include char-to-string (see section Conversion of Characters and Strings), make-vector (see section Vectors), and make-list (see section Building Cons Cells and Lists).

Function: string &rest characters
This returns a string containing the characters characters.

(string ?a ?b ?c)
     => "abc"

Function: substring string start &optional end
This function returns a new string which consists of those characters from string in the range from (and including) the character at the index start up to (but excluding) the character at the index end. The first character is at index zero.

(substring "abcdefg" 0 3)
     => "abc"

Here the index for `a' is 0, the index for `b' is 1, and the index for `c' is 2. Thus, three letters, `abc', are copied from the string "abcdefg". The index 3 marks the character position up to which the substring is copied. The character whose index is 3 is actually the fourth character in the string.

A negative number counts from the end of the string, so that -1 signifies the index of the last character of the string. For example:

(substring "abcdefg" -3 -1)
     => "ef"

In this example, the index for `e' is -3, the index for `f' is -2, and the index for `g' is -1. Therefore, `e' and `f' are included, and `g' is excluded.

When nil is used as an index, it stands for the length of the string. Thus,

(substring "abcdefg" -3 nil)
     => "efg"

Omitting the argument end is equivalent to specifying nil. It follows that (substring string 0) returns a copy of all of string.

(substring "abcdefg" 0)
     => "abcdefg"

But we recommend copy-sequence for this purpose (see section Sequences).

If the characters copied from string have text properties, the properties are copied into the new string also. See section Text Properties.

substring also allows vectors for the first argument. For example:

(substring [a b (c) "d"] 1 3)
     => [b (c)]

A wrong-type-argument error is signaled if either start or end is not an integer or nil. An args-out-of-range error is signaled if start indicates a character following end, or if either integer is out of range for string.

Contrast this function with buffer-substring (see section Examining Buffer Contents), which returns a string containing a portion of the text in the current buffer. The beginning of a string is at index 0, but the beginning of a buffer is at index 1.

Function: concat &rest sequences
This function returns a new string consisting of the characters in the arguments passed to it (along with their text properties, if any). The arguments may be strings, lists of numbers, or vectors of numbers; they are not themselves changed. If concat receives no arguments, it returns an empty string.

(concat "abc" "-def")
     => "abc-def"
(concat "abc" (list 120 121) [122])
     => "abcxyz"
;; nil is an empty sequence.
(concat "abc" nil "-def")
     => "abc-def"
(concat "The " "quick brown " "fox.")
     => "The quick brown fox."
(concat)
     => ""

The concat function always constructs a new string that is not eq to any existing string.

When an argument is an integer (not a sequence of integers), it is converted to a string of digits making up the decimal printed representation of the integer. Don't use this feature; we plan to eliminate it. If you already use this feature, change your programs now! The proper way to convert an integer to a decimal number in this way is with format (see section Formatting Strings) or number-to-string (see section Conversion of Characters and Strings).

(concat 137)
     => "137"
(concat 54 321)
     => "54321"

For information about other concatenation functions, see the description of mapconcat in section Mapping Functions, vconcat in section Vectors, and append in section Building Cons Cells and Lists.

Function: split-string string separators
Split string into substrings in between matches for the regular expression separators. Each match for separators defines a splitting point; the substrings between the splitting points are made into a list, which is the value. If separators is nil (or omitted), the default is "[ \f\t\n\r\v]+".

For example,

(split-string "Soup is good food" "o")
=> ("S" "up is g" "" "d f" "" "d")
(split-string "Soup is good food" "o+")
=> ("S" "up is g" "d f" "d")

When there is a match adjacent to the beginning or end of the string, this does not cause a null string to appear at the beginning or end of the list:

(split-string "out to moo" "o+")
=> ("ut t" " m")

Empty matches do count, when not adjacent to another match:

(split-string "Soup is good food" "o*")
=>("S" "u" "p" " " "i" "s" " " "g" "d" " " "f" "d")
(split-string "Nice doggy!" "")
=>("N" "i" "c" "e" " " "d" "o" "g" "g" "y" "!")

Modifying Strings

The most basic way to alter the contents of an existing string is with aset (see section Functions that Operate on Arrays). (aset string idx char) stores char into string at index idx. Each character occupies one or more bytes, and if char needs a different number of bytes from the character already present at that index, aset signals an error.

A more powerful function is store-substring:

Function: store-substring string idx obj
This function alters part of the contents of the string string, by storing obj starting at index idx. The argument obj may be either a character or a (smaller) string.

Since it is impossible to change the length of an existing string, it is an error if obj doesn't fit within string's actual length, of if any new character requires a different number of bytes from the character currently present at that point in string.

Comparison of Characters and Strings

Function: char-equal character1 character2
This function returns t if the arguments represent the same character, nil otherwise. This function ignores differences in case if case-fold-search is non-nil.

(char-equal ?x ?x)
     => t
(let ((case-fold-search nil))
  (char-equal ?x ?X))
     => nil

Function: string= string1 string2
This function returns t if the characters of the two strings match exactly; case is significant.

(string= "abc" "abc")
     => t
(string= "abc" "ABC")
     => nil
(string= "ab" "ABC")
     => nil

The function string= ignores the text properties of the two strings. When equal (see section Equality Predicates) compares two strings, it uses string=.

If the strings contain non-ASCII characters, and one is unibyte while the other is multibyte, then they cannot be equal. See section Text Representations.

Function: string-equal string1 string2
string-equal is another name for string=.

Function: string< string1 string2
This function compares two strings a character at a time. First it scans both the strings at once to find the first pair of corresponding characters that do not match. If the lesser character of those two is the character from string1, then string1 is less, and this function returns t. If the lesser character is the one from string2, then string1 is greater, and this function returns nil. If the two strings match entirely, the value is nil.

Pairs of characters are compared according to their character codes. Keep in mind that lower case letters have higher numeric values in the ASCII character set than their upper case counterparts; digits and many punctuation characters have a lower numeric value than upper case letters. An ASCII character is less than any non-ASCII character; a unibyte non-ASCII character is always less than any multibyte non-ASCII character (see section Text Representations).

(string< "abc" "abd")
     => t
(string< "abd" "abc")
     => nil
(string< "123" "abc")
     => t

When the strings have different lengths, and they match up to the length of string1, then the result is t. If they match up to the length of string2, the result is nil. A string of no characters is less than any other string.

(string< "" "abc")
     => t
(string< "ab" "abc")
     => t
(string< "abc" "")
     => nil
(string< "abc" "ab")
     => nil
(string< "" "")
     => nil                   

Function: string-lessp string1 string2
string-lessp is another name for string<.

Function: compare-strings string1 start1 end1 string2 start2 end2 &optional ignore-case
This function compares a specified part of string1 with a specified part of string2. The specified part of string1 runs from index start1 up to index end1 (default, the end of the string). The specified part of string2 runs from index start2 up to index end2 (default, the end of the string).

The strings are both converted to multibyte for the comparison (see section Text Representations) so that a unibyte string can be equal to a multibyte string. If ignore-case is non-nil, then case is ignored, so that upper case letters can be equal to lower case letters.

If the specified portions of the two strings match, the value is t. Otherwise, the value is an integer which indicates how many leading characters agree, and which string is less. Its absolute value is one plus the number of characters that agree at the beginning of the two strings. The sign is negative if string1 (or its specified portion) is less.

Function: assoc-ignore-case key alist
This function works like assoc, except that key must be a string, and comparison is done using compare-strings. Case differences are ignored in this comparison.

Function: assoc-ignore-representation key alist
This function works like assoc, except that key must be a string, and comparison is done using compare-strings. Case differences are significant.

See also compare-buffer-substrings in section Comparing Text, for a way to compare text in buffers. The function string-match, which matches a regular expression against a string, can be used for a kind of string comparison; see section Regular Expression Searching.

Conversion of Characters and Strings

This section describes functions for conversions between characters, strings and integers. format and prin1-to-string (see section Output Functions) can also convert Lisp objects into strings. read-from-string (see section Input Functions) can "convert" a string representation of a Lisp object into an object. The functions string-make-multibyte and string-make-unibyte convert the text representation of a string (see section Converting Text Representations).

See section Documentation, for functions that produce textual descriptions of text characters and general input events (single-key-description and text-char-description). These functions are used primarily for making help messages.

Function: char-to-string character
This function returns a new string containing one character, character. This function is semi-obsolete because the function string is more general. See section Creating Strings.

Function: string-to-char string
This function returns the first character in string. If the string is empty, the function returns 0. The value is also 0 when the first character of string is the null character, ASCII code 0.

(string-to-char "ABC")
     => 65
(string-to-char "xyz")
     => 120
(string-to-char "")
     => 0
(string-to-char "\000")
     => 0

This function may be eliminated in the future if it does not seem useful enough to retain.

Function: number-to-string number
This function returns a string consisting of the printed representation of number, which may be an integer or a floating point number. The value starts with a sign if the argument is negative.

(number-to-string 256)
     => "256"
(number-to-string -23)
     => "-23"
(number-to-string -23.5)
     => "-23.5"

int-to-string is a semi-obsolete alias for this function.

See also the function format in section Formatting Strings.

Function: string-to-number string &optional base
This function returns the numeric value of the characters in string. If base is non-nil, integers are converted in that base. If base is nil, then base ten is used. Floating point conversion always uses base ten; we have not implemented other radices for floating point numbers, because that would be much more work and does not seem useful.

The parsing skips spaces and tabs at the beginning of string, then reads as much of string as it can interpret as a number. (On some systems it ignores other whitespace at the beginning, not just spaces and tabs.) If the first character after the ignored whitespace is not a digit or a plus or minus sign, this function returns 0.

(string-to-number "256")
     => 256
(string-to-number "25 is a perfect square.")
     => 25
(string-to-number "X256")
     => 0
(string-to-number "-4.5")
     => -4.5

string-to-int is an obsolete alias for this function.

Here are some other functions that can convert to or from a string:

concat
concat can convert a vector or a list into a string. See section Creating Strings.
vconcat
vconcat can convert a string into a vector. See section Functions for Vectors.
append
append can convert a string into a list. See section Building Cons Cells and Lists.

Formatting Strings

Formatting means constructing a string by substitution of computed values at various places in a constant string. This string controls how the other values are printed as well as where they appear; it is called a format string.

Formatting is often useful for computing messages to be displayed. In fact, the functions message and error provide the same formatting feature described here; they differ from format only in how they use the result of formatting.

Function: format string &rest objects
This function returns a new string that is made by copying string and then replacing any format specification in the copy with encodings of the corresponding objects. The arguments objects are the computed values to be formatted.

A format specification is a sequence of characters beginning with a `%'. Thus, if there is a `%d' in string, the format function replaces it with the printed representation of one of the values to be formatted (one of the arguments objects). For example:

(format "The value of fill-column is %d." fill-column)
     => "The value of fill-column is 72."

If string contains more than one format specification, the format specifications correspond with successive values from objects. Thus, the first format specification in string uses the first such value, the second format specification uses the second such value, and so on. Any extra format specifications (those for which there are no corresponding values) cause unpredictable behavior. Any extra values to be formatted are ignored.

Certain format specifications require values of particular types. If you supply a value that doesn't fit the requirements, an error is signaled.

Here is a table of valid format specifications:

`%s'
Replace the specification with the printed representation of the object, made without quoting (that is, using princ, not prin1---see section Output Functions). Thus, strings are represented by their contents alone, with no `"' characters, and symbols appear without `\' characters. If there is no corresponding object, the empty string is used.
`%S'
Replace the specification with the printed representation of the object, made with quoting (that is, using prin1---see section Output Functions). Thus, strings are enclosed in `"' characters, and `\' characters appear where necessary before special characters. If there is no corresponding object, the empty string is used.
`%o'
Replace the specification with the base-eight representation of an integer.
`%d'
Replace the specification with the base-ten representation of an integer.
`%x'
Replace the specification with the base-sixteen representation of an integer.
`%c'
Replace the specification with the character which is the value given.
`%e'
Replace the specification with the exponential notation for a floating point number.
`%f'
Replace the specification with the decimal-point notation for a floating point number.
`%g'
Replace the specification with notation for a floating point number, using either exponential notation or decimal-point notation, whichever is shorter.
`%%'
A single `%' is placed in the string. This format specification is unusual in that it does not use a value. For example, (format "%% %d" 30) returns "% 30".

Any other format character results in an `Invalid format operation' error.

Here are several examples:

(format "The name of this buffer is %s." (buffer-name))
     => "The name of this buffer is strings.texi."

(format "The buffer object prints as %s." (current-buffer))
     => "The buffer object prints as strings.texi."

(format "The octal value of %d is %o, 
         and the hex value is %x." 18 18 18)
     => "The octal value of 18 is 22, 
         and the hex value is 12."

All the specification characters allow an optional numeric prefix between the `%' and the character. The optional numeric prefix defines the minimum width for the object. If the printed representation of the object contains fewer characters than this, then it is padded. The padding is on the left if the prefix is positive (or starts with zero) and on the right if the prefix is negative. The padding character is normally a space, but if the numeric prefix starts with a zero, zeros are used for padding. Here are some examples of padding:

(format "%06d is padded on the left with zeros" 123)
     => "000123 is padded on the left with zeros"

(format "%-6d is padded on the right" 123)
     => "123    is padded on the right"

format never truncates an object's printed representation, no matter what width you specify. Thus, you can use a numeric prefix to specify a minimum spacing between columns with no risk of losing information.

In the following three examples, `%7s' specifies a minimum width of 7. In the first case, the string inserted in place of `%7s' has only 3 letters, so 4 blank spaces are inserted for padding. In the second case, the string "specification" is 13 letters wide but is not truncated. In the third case, the padding is on the right.

(format "The word `%7s' actually has %d letters in it."
        "foo" (length "foo"))
     => "The word `    foo' actually has 3 letters in it."  

(format "The word `%7s' actually has %d letters in it."
        "specification" (length "specification")) 
     => "The word `specification' actually has 13 letters in it."  

(format "The word `%-7s' actually has %d letters in it."
        "foo" (length "foo"))
     => "The word `foo    ' actually has 3 letters in it."  

Case Conversion in Lisp

The character case functions change the case of single characters or of the contents of strings. The functions normally convert only alphabetic characters (the letters `A' through `Z' and `a' through `z', as well as non-ASCII letters); other characters are not altered. (You can specify a different case conversion mapping by specifying a case table---see section The Case Table.)

These functions do not modify the strings that are passed to them as arguments.

The examples below use the characters `X' and `x' which have ASCII codes 88 and 120 respectively.

Function: downcase string-or-char
This function converts a character or a string to lower case.

When the argument to downcase is a string, the function creates and returns a new string in which each letter in the argument that is upper case is converted to lower case. When the argument to downcase is a character, downcase returns the corresponding lower case character. This value is an integer. If the original character is lower case, or is not a letter, then the value equals the original character.

(downcase "The cat in the hat")
     => "the cat in the hat"

(downcase ?X)
     => 120

Function: upcase string-or-char
This function converts a character or a string to upper case.

When the argument to upcase is a string, the function creates and returns a new string in which each letter in the argument that is lower case is converted to upper case.

When the argument to upcase is a character, upcase returns the corresponding upper case character. This value is an integer. If the original character is upper case, or is not a letter, then the value equals the original character.

(upcase "The cat in the hat")
     => "THE CAT IN THE HAT"

(upcase ?x)
     => 88

Function: capitalize string-or-char
This function capitalizes strings or characters. If string-or-char is a string, the function creates and returns a new string, whose contents are a copy of string-or-char in which each word has been capitalized. This means that the first character of each word is converted to upper case, and the rest are converted to lower case.

The definition of a word is any sequence of consecutive characters that are assigned to the word constituent syntax class in the current syntax table (See section Table of Syntax Classes).

When the argument to capitalize is a character, capitalize has the same result as upcase.

(capitalize "The cat in the hat")
     => "The Cat In The Hat"

(capitalize "THE 77TH-HATTED CAT")
     => "The 77th-Hatted Cat"

(capitalize ?x)
     => 88

Function: upcase-initials string
This function capitalizes the initials of the words in string. without altering any letters other than the initials. It returns a new string whose contents are a copy of string, in which each word has been converted to upper case.

The definition of a word is any sequence of consecutive characters that are assigned to the word constituent syntax class in the current syntax table (See section Table of Syntax Classes).

(upcase-initials "The CAT in the hAt")
     => "The CAT In The HAt"

See section Comparison of Characters and Strings, for functions that compare strings; some of them ignore case differences, or can optionally ignore case differences.

The Case Table

You can customize case conversion by installing a special case table. A case table specifies the mapping between upper case and lower case letters. It affects both the case conversion functions for Lisp objects (see the previous section) and those that apply to text in the buffer (see section Case Changes). Each buffer has a case table; there is also a standard case table which is used to initialize the case table of new buffers.

A case table is a char-table (see section Char-Tables) whose subtype is case-table. This char-table maps each character into the corresponding lower case character. It has three extra slots, which hold related tables:

upcase
The upcase table maps each character into the corresponding upper case character.
canonicalize
The canonicalize table maps all of a set of case-related characters into a particular member of that set.
equivalences
The equivalences table maps each one of a set of case-related characters into the next character in that set.

In simple cases, all you need to specify is the mapping to lower-case; the three related tables will be calculated automatically from that one.

For some languages, upper and lower case letters are not in one-to-one correspondence. There may be two different lower case letters with the same upper case equivalent. In these cases, you need to specify the maps for both lower case and upper case.

The extra table canonicalize maps each character to a canonical equivalent; any two characters that are related by case-conversion have the same canonical equivalent character. For example, since `a' and `A' are related by case-conversion, they should have the same canonical equivalent character (which should be either `a' for both of them, or `A' for both of them).

The extra table equivalences is a map that cyclicly permutes each equivalence class (of characters with the same canonical equivalent). (For ordinary ASCII, this would map `a' into `A' and `A' into `a', and likewise for each set of equivalent characters.)

When you construct a case table, you can provide nil for canonicalize; then Emacs fills in this slot from the lower case and upper case mappings. You can also provide nil for equivalences; then Emacs fills in this slot from canonicalize. In a case table that is actually in use, those components are non-nil. Do not try to specify equivalences without also specifying canonicalize.

Here are the functions for working with case tables:

Function: case-table-p object
This predicate returns non-nil if object is a valid case table.

Function: set-standard-case-table table
This function makes table the standard case table, so that it will be used in any buffers created subsequently.

Function: standard-case-table
This returns the standard case table.

Function: current-case-table
This function returns the current buffer's case table.

Function: set-case-table table
This sets the current buffer's case table to table.

The following three functions are convenient subroutines for packages that define non-ASCII character sets. They modify the specified case table case-table; they also modify the standard syntax table. See section Syntax Tables. Normally you would use these functions to change the standard case table.

Function: set-case-syntax-pair uc lc case-table
This function specifies a pair of corresponding letters, one upper case and one lower case.

Function: set-case-syntax-delims l r case-table
This function makes characters l and r a matching pair of case-invariant delimiters.

Function: set-case-syntax char syntax case-table
This function makes char case-invariant, with syntax syntax.

Command: describe-buffer-case-table
This command displays a description of the contents of the current buffer's case table.

Lists

A list represents a sequence of zero or more elements (which may be any Lisp objects). The important difference between lists and vectors is that two or more lists can share part of their structure; in addition, you can insert or delete elements in a list without copying the whole list.

Lists and Cons Cells

Lists in Lisp are not a primitive data type; they are built up from cons cells. A cons cell is a data object that represents an ordered pair. It holds, or "points to," two Lisp objects, one labeled as the CAR, and the other labeled as the CDR. These names are traditional; see section Cons Cell and List Types. CDR is pronounced "could-er."

A list is a series of cons cells chained together, one cons cell per element of the list. By convention, the CARs of the cons cells are the elements of the list, and the CDRs are used to chain the list: the CDR of each cons cell is the following cons cell. The CDR of the last cons cell is nil. This asymmetry between the CAR and the CDR is entirely a matter of convention; at the level of cons cells, the CAR and CDR slots have the same characteristics.

Because most cons cells are used as part of lists, the phrase list structure has come to mean any structure made out of cons cells.

The symbol nil is considered a list as well as a symbol; it is the list with no elements. For convenience, the symbol nil is considered to have nil as its CDR (and also as its CAR).

The CDR of any nonempty list l is a list containing all the elements of l except the first.

Lists as Linked Pairs of Boxes

A cons cell can be illustrated as a pair of boxes. The first box represents the CAR and the second box represents the CDR. Here is an illustration of the two-element list, (tulip lily), made from two cons cells:

 ---------------         ---------------
| car   | cdr   |       | car   | cdr   |
| tulip |   o---------->| lily  |  nil  |
|       |       |       |       |       |
 ---------------         ---------------

Each pair of boxes represents a cons cell. Each box "refers to", "points to" or "contains" a Lisp object. (These terms are synonymous.) The first box, which describes the CAR of the first cons cell, contains the symbol tulip. The arrow from the CDR box of the first cons cell to the second cons cell indicates that the CDR of the first cons cell is the second cons cell.

The same list can be illustrated in a different sort of box notation like this:

    --- ---      --- ---
   |   |   |--> |   |   |--> nil
    --- ---      --- ---
     |            |
     |            |
      --> tulip    --> lily

Here is a more complex illustration, showing the three-element list, ((pine needles) oak maple), the first element of which is a two-element list:

    --- ---      --- ---      --- ---
   |   |   |--> |   |   |--> |   |   |--> nil
    --- ---      --- ---      --- ---
     |            |            |
     |            |            |
     |             --> oak      --> maple
     |
     |     --- ---      --- ---
      --> |   |   |--> |   |   |--> nil
           --- ---      --- ---
            |            |
            |            |
             --> pine     --> needles

The same list represented in the first box notation looks like this:

 --------------       --------------       --------------
| car   | cdr  |     | car   | cdr  |     | car   | cdr  |
|   o   |   o------->| oak   |   o------->| maple |  nil |
|   |   |      |     |       |      |     |       |      |
 -- | ---------       --------------       --------------
    |
    |
    |        --------------       ----------------
    |       | car   | cdr  |     | car     | cdr  |
     ------>| pine  |   o------->| needles |  nil |
            |       |      |     |         |      |
             --------------       ----------------

See section Cons Cell and List Types, for the read and print syntax of cons cells and lists, and for more "box and arrow" illustrations of lists.

Predicates on Lists

The following predicates test whether a Lisp object is an atom, is a cons cell or is a list, or whether it is the distinguished object nil. (Many of these predicates can be defined in terms of the others, but they are used so often that it is worth having all of them.)

Function: consp object
This function returns t if object is a cons cell, nil otherwise. nil is not a cons cell, although it is a list.

Function: atom object
This function returns t if object is an atom, nil otherwise. All objects except cons cells are atoms. The symbol nil is an atom and is also a list; it is the only Lisp object that is both.

(atom object) == (not (consp object))

Function: listp object
This function returns t if object is a cons cell or nil. Otherwise, it returns nil.

(listp '(1))
     => t
(listp '())
     => t

Function: nlistp object
This function is the opposite of listp: it returns t if object is not a list. Otherwise, it returns nil.

(listp object) == (not (nlistp object))

Function: null object
This function returns t if object is nil, and returns nil otherwise. This function is identical to not, but as a matter of clarity we use null when object is considered a list and not when it is considered a truth value (see not in section Constructs for Combining Conditions).

(null '(1))
     => nil
(null '())
     => t

Accessing Elements of Lists

Function: car cons-cell
This function returns the value pointed to by the first pointer of the cons cell cons-cell. Expressed another way, this function returns the CAR of cons-cell.

As a special case, if cons-cell is nil, then car is defined to return nil; therefore, any list is a valid argument for car. An error is signaled if the argument is not a cons cell or nil.

(car '(a b c))
     => a
(car '())
     => nil

Function: cdr cons-cell
This function returns the value pointed to by the second pointer of the cons cell cons-cell. Expressed another way, this function returns the CDR of cons-cell.

As a special case, if cons-cell is nil, then cdr is defined to return nil; therefore, any list is a valid argument for cdr. An error is signaled if the argument is not a cons cell or nil.

(cdr '(a b c))
     => (b c)
(cdr '())
     => nil

Function: car-safe object
This function lets you take the CAR of a cons cell while avoiding errors for other data types. It returns the CAR of object if object is a cons cell, nil otherwise. This is in contrast to car, which signals an error if object is not a list.

(car-safe object)
==
(let ((x object))
  (if (consp x)
      (car x)
    nil))

Function: cdr-safe object
This function lets you take the CDR of a cons cell while avoiding errors for other data types. It returns the CDR of object if object is a cons cell, nil otherwise. This is in contrast to cdr, which signals an error if object is not a list.

(cdr-safe object)
==
(let ((x object))
  (if (consp x)
      (cdr x)
    nil))

Function: nth n list
This function returns the nth element of list. Elements are numbered starting with zero, so the CAR of list is element number zero. If the length of list is n or less, the value is nil.

If n is negative, nth returns the first element of list.

(nth 2 '(1 2 3 4))
     => 3
(nth 10 '(1 2 3 4))
     => nil
(nth -3 '(1 2 3 4))
     => 1

(nth n x) == (car (nthcdr n x))

The function elt is similar, but applies to any kind of sequence. For historical reasons, it takes its arguments in the opposite order. See section Sequences.

Function: nthcdr n list
This function returns the nth CDR of list. In other words, it skips past the first n links of list and returns what follows.

If n is zero or negative, nthcdr returns all of list. If the length of list is n or less, nthcdr returns nil.

(nthcdr 1 '(1 2 3 4))
     => (2 3 4)
(nthcdr 10 '(1 2 3 4))
     => nil
(nthcdr -3 '(1 2 3 4))
     => (1 2 3 4)

Function: safe-length list
This function returns the length of list, with no risk of either an error or an infinite loop.

If list is not really a list, safe-length returns 0. If list is circular, it returns a finite value which is at least the number of distinct elements.

The most common way to compute the length of a list, when you are not worried that it may be circular, is with length. See section Sequences.

Function: caar cons-cell
This is the same as (car (car cons-cell)).

Function: cadr cons-cell
This is the same as (car (cdr cons-cell)) or (nth 1 cons-cell).

Function: cdar cons-cell
This is the same as (cdr (car cons-cell)).

Function: cddr cons-cell
This is the same as (cdr (cdr cons-cell)) or (nthcdr 2 cons-cell).

Building Cons Cells and Lists

Many functions build lists, as lists reside at the very heart of Lisp. cons is the fundamental list-building function; however, it is interesting to note that list is used more times in the source code for Emacs than cons.

Function: cons object1 object2
This function is the fundamental function used to build new list structure. It creates a new cons cell, making object1 the CAR, and object2 the CDR. It then returns the new cons cell. The arguments object1 and object2 may be any Lisp objects, but most often object2 is a list.

(cons 1 '(2))
     => (1 2)
(cons 1 '())
     => (1)
(cons 1 2)
     => (1 . 2)

cons is often used to add a single element to the front of a list. This is called consing the element onto the list. For example:

(setq list (cons newelt list))

Note that there is no conflict between the variable named list used in this example and the function named list described below; any symbol can serve both purposes.

Function: list &rest objects
This function creates a list with objects as its elements. The resulting list is always nil-terminated. If no objects are given, the empty list is returned.

(list 1 2 3 4 5)
     => (1 2 3 4 5)
(list 1 2 '(3 4 5) 'foo)
     => (1 2 (3 4 5) foo)
(list)
     => nil

Function: make-list length object
This function creates a list of length length, in which all the elements have the identical value object. Compare make-list with make-string (see section Creating Strings).

(make-list 3 'pigs)
     => (pigs pigs pigs)
(make-list 0 'pigs)
     => nil

Function: append &rest sequences
This function returns a list containing all the elements of sequences. The sequences may be lists, vectors, bool-vectors, or strings, but the last one should usually be a list. All arguments except the last one are copied, so none of the arguments is altered. (See nconc in section Functions that Rearrange Lists, for a way to join lists with no copying.)

More generally, the final argument to append may be any Lisp object. The final argument is not copied or converted; it becomes the CDR of the last cons cell in the new list. If the final argument is itself a list, then its elements become in effect elements of the result list. If the final element is not a list, the result is a "dotted list" since its final CDR is not nil as required in a true list.

The append function also allows integers as arguments. It converts them to strings of digits, making up the decimal print representation of the integer, and then uses the strings instead of the original integers. Don't use this feature; we plan to eliminate it. If you already use this feature, change your programs now! The proper way to convert an integer to a decimal number in this way is with format (see section Formatting Strings) or number-to-string (see section Conversion of Characters and Strings).

Here is an example of using append:

(setq trees '(pine oak))
     => (pine oak)
(setq more-trees (append '(maple birch) trees))
     => (maple birch pine oak)

trees
     => (pine oak)
more-trees
     => (maple birch pine oak)
(eq trees (cdr (cdr more-trees)))
     => t

You can see how append works by looking at a box diagram. The variable trees is set to the list (pine oak) and then the variable more-trees is set to the list (maple birch pine oak). However, the variable trees continues to refer to the original list:

more-trees                trees
|                           |
|     --- ---      --- ---   -> --- ---      --- ---
 --> |   |   |--> |   |   |--> |   |   |--> |   |   |--> nil
      --- ---      --- ---      --- ---      --- ---
       |            |            |            |
       |            |            |            |
        --> maple    -->birch     --> pine     --> oak

An empty sequence contributes nothing to the value returned by append. As a consequence of this, a final nil argument forces a copy of the previous argument:

trees
     => (pine oak)
(setq wood (append trees nil))
     => (pine oak)
wood
     => (pine oak)
(eq wood trees)
     => nil

This once was the usual way to copy a list, before the function copy-sequence was invented. See section Sequences, Arrays, and Vectors.

Here we show the use of vectors and strings as arguments to append:

(append [a b] "cd" nil)
     => (a b 99 100)

With the help of apply (see section Calling Functions), we can append all the lists in a list of lists:

(apply 'append '((a b c) nil (x y z) nil))
     => (a b c x y z)

If no sequences are given, nil is returned:

(append)
     => nil

Here are some examples where the final argument is not a list:

(append '(x y) 'z)
     => (x y . z)
(append '(x y) [z])
     => (x y . [z])

The second example shows that when the final argument is a sequence but not a list, the sequence's elements do not become elements of the resulting list. Instead, the sequence becomes the final CDR, like any other non-list final argument.

Function: reverse list
This function creates a new list whose elements are the elements of list, but in reverse order. The original argument list is not altered.

(setq x '(1 2 3 4))
     => (1 2 3 4)
(reverse x)
     => (4 3 2 1)
x
     => (1 2 3 4)

Modifying Existing List Structure

You can modify the CAR and CDR contents of a cons cell with the primitives setcar and setcdr. We call these "destructive" operations because they change existing list structure.

Common Lisp note: Common Lisp uses functions rplaca and rplacd to alter list structure; they change structure the same way as setcar and setcdr, but the Common Lisp functions return the cons cell while setcar and setcdr return the new CAR or CDR.

Altering List Elements with setcar

Changing the CAR of a cons cell is done with setcar. When used on a list, setcar replaces one element of a list with a different element.

Function: setcar cons object
This function stores object as the new CAR of cons, replacing its previous CAR. In other words, it changes the CAR slot of cons to point to object. It returns the value object. For example:

(setq x '(1 2))
     => (1 2)
(setcar x 4)
     => 4
x
     => (4 2)

When a cons cell is part of the shared structure of several lists, storing a new CAR into the cons changes one element of each of these lists. Here is an example:

;; Create two lists that are partly shared.
(setq x1 '(a b c))
     => (a b c)
(setq x2 (cons 'z (cdr x1)))
     => (z b c)

;; Replace the CAR of a shared link.
(setcar (cdr x1) 'foo)
     => foo
x1                           ; Both lists are changed.
     => (a foo c)
x2
     => (z foo c)

;; Replace the CAR of a link that is not shared.
(setcar x1 'baz)
     => baz
x1                           ; Only one list is changed.
     => (baz foo c)
x2
     => (z foo c)

Here is a graphical depiction of the shared structure of the two lists in the variables x1 and x2, showing why replacing b changes them both:

        --- ---        --- ---      --- ---
x1---> |   |   |----> |   |   |--> |   |   |--> nil
        --- ---        --- ---      --- ---
         |        -->   |            |
         |       |      |            |
          --> a  |       --> b        --> c
                 |
       --- ---   |
x2--> |   |   |--
       --- ---
        |
        |
         --> z

Here is an alternative form of box diagram, showing the same relationship:

x1:
 --------------       --------------       --------------
| car   | cdr  |     | car   | cdr  |     | car   | cdr  |
|   a   |   o------->|   b   |   o------->|   c   |  nil |
|       |      |  -->|       |      |     |       |      |
 --------------  |    --------------       --------------
                 |
x2:              |
 --------------  |
| car   | cdr  | |
|   z   |   o----
|       |      |
 --------------

Altering the CDR of a List

The lowest-level primitive for modifying a CDR is setcdr:

Function: setcdr cons object
This function stores object as the new CDR of cons, replacing its previous CDR. In other words, it changes the CDR slot of cons to point to object. It returns the value object.

Here is an example of replacing the CDR of a list with a different list. All but the first element of the list are removed in favor of a different sequence of elements. The first element is unchanged, because it resides in the CAR of the list, and is not reached via the CDR.

(setq x '(1 2 3))
     => (1 2 3)
(setcdr x '(4))
     => (4)
x
     => (1 4)

You can delete elements from the middle of a list by altering the CDRs of the cons cells in the list. For example, here we delete the second element, b, from the list (a b c), by changing the CDR of the first cons cell:

(setq x1 '(a b c))
     => (a b c)
(setcdr x1 (cdr (cdr x1)))
     => (c)
x1
     => (a c)

Here is the result in box notation:

                   --------------------
                  |                    |
 --------------   |   --------------   |    --------------
| car   | cdr  |  |  | car   | cdr  |   -->| car   | cdr  |
|   a   |   o-----   |   b   |   o-------->|   c   |  nil |
|       |      |     |       |      |      |       |      |
 --------------       --------------        --------------

The second cons cell, which previously held the element b, still exists and its CAR is still b, but it no longer forms part of this list.

It is equally easy to insert a new element by changing CDRs:

(setq x1 '(a b c))
     => (a b c)
(setcdr x1 (cons 'd (cdr x1)))
     => (d b c)
x1
     => (a d b c)

Here is this result in box notation:

 --------------        -------------       -------------
| car  | cdr   |      | car  | cdr  |     | car  | cdr  |
|   a  |   o   |   -->|   b  |   o------->|   c  |  nil |
|      |   |   |  |   |      |      |     |      |      |
 --------- | --   |    -------------       -------------
           |      |
     -----         --------
    |                      |
    |    ---------------   |
    |   | car   | cdr   |  |
     -->|   d   |   o------
        |       |       |
         ---------------

Functions that Rearrange Lists

Here are some functions that rearrange lists "destructively" by modifying the CDRs of their component cons cells. We call these functions "destructive" because they chew up the original lists passed to them as arguments, relinking their cons cells to form a new list that is the returned value.

The function delq in the following section is another example of destructive list manipulation.

Function: nconc &rest lists
This function returns a list containing all the elements of lists. Unlike append (see section Building Cons Cells and Lists), the lists are not copied. Instead, the last CDR of each of the lists is changed to refer to the following list. The last of the lists is not altered. For example:

(setq x '(1 2 3))
     => (1 2 3)
(nconc x '(4 5))
     => (1 2 3 4 5)
x
     => (1 2 3 4 5)

Since the last argument of nconc is not itself modified, it is reasonable to use a constant list, such as '(4 5), as in the above example. For the same reason, the last argument need not be a list:

(setq x '(1 2 3))
     => (1 2 3)
(nconc x 'z)
     => (1 2 3 . z)
x
     => (1 2 3 . z)

However, the other arguments (all but the last) must be lists.

A common pitfall is to use a quoted constant list as a non-last argument to nconc. If you do this, your program will change each time you run it! Here is what happens:

(defun add-foo (x)            ; We want this function to add
  (nconc '(foo) x))           ;   foo to the front of its arg.

(symbol-function 'add-foo)
     => (lambda (x) (nconc (quote (foo)) x))

(setq xx (add-foo '(1 2)))    ; It seems to work.
     => (foo 1 2)
(setq xy (add-foo '(3 4)))    ; What happened?
     => (foo 1 2 3 4)
(eq xx xy)
     => t

(symbol-function 'add-foo)
     => (lambda (x) (nconc (quote (foo 1 2 3 4) x)))

Function: nreverse list
This function reverses the order of the elements of list. Unlike reverse, nreverse alters its argument by reversing the CDRs in the cons cells forming the list. The cons cell that used to be the last one in list becomes the first cons cell of the value.

For example:

(setq x '(1 2 3 4))
     => (1 2 3 4)
x
     => (1 2 3 4)
(nreverse x)
     => (4 3 2 1)
;; The cons cell that was first is now last.
x
     => (1)

To avoid confusion, we usually store the result of nreverse back in the same variable which held the original list:

(setq x (nreverse x))

Here is the nreverse of our favorite example, (a b c), presented graphically:

Original list head:                       Reversed list:
 -------------        -------------        ------------
| car  | cdr  |      | car  | cdr  |      | car | cdr  |
|   a  |  nil |<--   |   b  |   o  |<--   |   c |   o  |
|      |      |   |  |      |   |  |   |  |     |   |  |
 -------------    |   --------- | -    |   -------- | -
                  |             |      |            |
                   -------------        ------------

Function: sort list predicate
This function sorts list stably, though destructively, and returns the sorted list. It compares elements using predicate. A stable sort is one in which elements with equal sort keys maintain their relative order before and after the sort. Stability is important when successive sorts are used to order elements according to different criteria.

The argument predicate must be a function that accepts two arguments. It is called with two elements of list. To get an increasing order sort, the predicate should return t if the first element is "less than" the second, or nil if not.

The comparison function predicate must give reliable results for any given pair of arguments, at least within a single call to sort. It must be antisymmetric; that is, if a is less than b, b must not be less than a. It must be transitive---that is, if a is less than b, and b is less than c, then a must be less than c. If you use a comparison function which does not meet these requirements, the result of sort is unpredictable.

The destructive aspect of sort is that it rearranges the cons cells forming list by changing CDRs. A nondestructive sort function would create new cons cells to store the elements in their sorted order. If you wish to make a sorted copy without destroying the original, copy it first with copy-sequence and then sort.

Sorting does not change the CARs of the cons cells in list; the cons cell that originally contained the element a in list still has a in its CAR after sorting, but it now appears in a different position in the list due to the change of CDRs. For example:

(setq nums '(1 3 2 6 5 4 0))
     => (1 3 2 6 5 4 0)
(sort nums '<)
     => (0 1 2 3 4 5 6)
nums
     => (1 2 3 4 5 6)

Warning: Note that the list in nums no longer contains 0; this is the same cons cell that it was before, but it is no longer the first one in the list. Don't assume a variable that formerly held the argument now holds the entire sorted list! Instead, save the result of sort and use that. Most often we store the result back into the variable that held the original list:

(setq nums (sort nums '<))

See section Sorting Text, for more functions that perform sorting. See documentation in section Access to Documentation Strings, for a useful example of sort.

Using Lists as Sets

A list can represent an unordered mathematical set--simply consider a value an element of a set if it appears in the list, and ignore the order of the list. To form the union of two sets, use append (as long as you don't mind having duplicate elements). Other useful functions for sets include memq and delq, and their equal versions, member and delete.

Common Lisp note: Common Lisp has functions union (which avoids duplicate elements) and intersection for set operations, but GNU Emacs Lisp does not have them. You can write them in Lisp if you wish.

Function: memq object list
This function tests to see whether object is a member of list. If it is, memq returns a list starting with the first occurrence of object. Otherwise, it returns nil. The letter `q' in memq says that it uses eq to compare object against the elements of the list. For example:

(memq 'b '(a b c b a))
     => (b c b a)
(memq '(2) '((1) (2)))    ; (2) and (2) are not eq.
     => nil

Function: delq object list
This function destructively removes all elements eq to object from list. The letter `q' in delq says that it uses eq to compare object against the elements of the list, like memq.

When delq deletes elements from the front of the list, it does so simply by advancing down the list and returning a sublist that starts after those elements:

(delq 'a '(a b c)) == (cdr '(a b c))

When an element to be deleted appears in the middle of the list, removing it involves changing the CDRs (see section Altering the CDR of a List).

(setq sample-list '(a b c (4)))
     => (a b c (4))
(delq 'a sample-list)
     => (b c (4))
sample-list
     => (a b c (4))
(delq 'c sample-list)
     => (a b (4))
sample-list
     => (a b (4))

Note that (delq 'c sample-list) modifies sample-list to splice out the third element, but (delq 'a sample-list) does not splice anything--it just returns a shorter list. Don't assume that a variable which formerly held the argument list now has fewer elements, or that it still holds the original list! Instead, save the result of delq and use that. Most often we store the result back into the variable that held the original list:

(setq flowers (delq 'rose flowers))

In the following example, the (4) that delq attempts to match and the (4) in the sample-list are not eq:

(delq '(4) sample-list)
     => (a c (4))

The following two functions are like memq and delq but use equal rather than eq to compare elements. See section Equality Predicates.

Function: member object list
The function member tests to see whether object is a member of list, comparing members with object using equal. If object is a member, member returns a list starting with its first occurrence in list. Otherwise, it returns nil.

Compare this with memq:

(member '(2) '((1) (2)))  ; (2) and (2) are equal.
     => ((2))
(memq '(2) '((1) (2)))    ; (2) and (2) are not eq.
     => nil
;; Two strings with the same contents are equal.
(member "foo" '("foo" "bar"))
     => ("foo" "bar")

Function: delete object list
This function destructively removes all elements equal to object from list. It is to delq as member is to memq: it uses equal to compare elements with object, like member; when it finds an element that matches, it removes the element just as delq would. For example:

(delete '(2) '((2) (1) (2)))
     => ((1))

Common Lisp note: The functions member and delete in GNU Emacs Lisp are derived from Maclisp, not Common Lisp. The Common Lisp versions do not use equal to compare elements.

See also the function add-to-list, in section How to Alter a Variable Value, for another way to add an element to a list stored in a variable.

Association Lists

An association list, or alist for short, records a mapping from keys to values. It is a list of cons cells called associations: the CAR of each cons cell is the key, and the CDR is the associated value.(1)

Here is an example of an alist. The key pine is associated with the value cones; the key oak is associated with acorns; and the key maple is associated with seeds.

'((pine . cones)
  (oak . acorns)
  (maple . seeds))

The associated values in an alist may be any Lisp objects; so may the keys. For example, in the following alist, the symbol a is associated with the number 1, and the string "b" is associated with the list (2 3), which is the CDR of the alist element:

((a . 1) ("b" 2 3))

Sometimes it is better to design an alist to store the associated value in the CAR of the CDR of the element. Here is an example:

'((rose red) (lily white) (buttercup yellow))

Here we regard red as the value associated with rose. One advantage of this kind of alist is that you can store other related information--even a list of other items--in the CDR of the CDR. One disadvantage is that you cannot use rassq (see below) to find the element containing a given value. When neither of these considerations is important, the choice is a matter of taste, as long as you are consistent about it for any given alist.

Note that the same alist shown above could be regarded as having the associated value in the CDR of the element; the value associated with rose would be the list (red).

Association lists are often used to record information that you might otherwise keep on a stack, since new associations may be added easily to the front of the list. When searching an association list for an association with a given key, the first one found is returned, if there is more than one.

In Emacs Lisp, it is not an error if an element of an association list is not a cons cell. The alist search functions simply ignore such elements. Many other versions of Lisp signal errors in such cases.

Note that property lists are similar to association lists in several respects. A property list behaves like an association list in which each key can occur only once. See section Property Lists, for a comparison of property lists and association lists.

Function: assoc key alist
This function returns the first association for key in alist. It compares key against the alist elements using equal (see section Equality Predicates). It returns nil if no association in alist has a CAR equal to key. For example:

(setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
     => ((pine . cones) (oak . acorns) (maple . seeds))
(assoc 'oak trees)
     => (oak . acorns)
(cdr (assoc 'oak trees))
     => acorns
(assoc 'birch trees)
     => nil

Here is another example, in which the keys and values are not symbols:

(setq needles-per-cluster
      '((2 "Austrian Pine" "Red Pine")
        (3 "Pitch Pine")
        (5 "White Pine")))

(cdr (assoc 3 needles-per-cluster))
     => ("Pitch Pine")
(cdr (assoc 2 needles-per-cluster))
     => ("Austrian Pine" "Red Pine")

The functions assoc-ignore-representation and assoc-ignore-case are much like assoc except using compare-strings to do the comparison. See section Comparison of Characters and Strings.

Function: rassoc value alist
This function returns the first association with value value in alist. It returns nil if no association in alist has a CDR equal to value.

rassoc is like assoc except that it compares the CDR of each alist association instead of the CAR. You can think of this as "reverse assoc", finding the key for a given value.

Function: assq key alist
This function is like assoc in that it returns the first association for key in alist, but it makes the comparison using eq instead of equal. assq returns nil if no association in alist has a CAR eq to key. This function is used more often than assoc, since eq is faster than equal and most alists use symbols as keys. See section Equality Predicates.

(setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
     => ((pine . cones) (oak . acorns) (maple . seeds))
(assq 'pine trees)
     => (pine . cones)

On the other hand, assq is not usually useful in alists where the keys may not be symbols:

(setq leaves
      '(("simple leaves" . oak)
        ("compound leaves" . horsechestnut)))

(assq "simple leaves" leaves)
     => nil
(assoc "simple leaves" leaves)
     => ("simple leaves" . oak)

Function: rassq value alist
This function returns the first association with value value in alist. It returns nil if no association in alist has a CDR eq to value.

rassq is like assq except that it compares the CDR of each alist association instead of the CAR. You can think of this as "reverse assq", finding the key for a given value.

For example:

(setq trees '((pine . cones) (oak . acorns) (maple . seeds)))

(rassq 'acorns trees)
     => (oak . acorns)
(rassq 'spores trees)
     => nil

Note that rassq cannot search for a value stored in the CAR of the CDR of an element:

(setq colors '((rose red) (lily white) (buttercup yellow)))

(rassq 'white colors)
     => nil

In this case, the CDR of the association (lily white) is not the symbol white, but rather the list (white). This becomes clearer if the association is written in dotted pair notation:

(lily white) == (lily . (white))

Function: assoc-default key alist test default
This function searches alist for a match for key. For each element of alist, it compares the element (if it is an atom) or the element's CAR (if it is a cons) against key, by calling test with two arguments: the element or its CAR, and key. The arguments are passed in that order so that you can get useful results using string-match with an alist that contains regular expressions (see section Regular Expression Searching). If test is omitted or nil, equal is used for comparison.

If an alist element matches key by this criterion, then assoc-default returns a value based on this element. If the element is a cons, then the value is the element's CDR. Otherwise, the return value is default.

If no alist element matches key, assoc-default returns nil.

Function: copy-alist alist
This function returns a two-level deep copy of alist: it creates a new copy of each association, so that you can alter the associations of the new alist without changing the old one.

(setq needles-per-cluster
      '((2 . ("Austrian Pine" "Red Pine"))
        (3 . ("Pitch Pine"))
        (5 . ("White Pine"))))
=>
((2 "Austrian Pine" "Red Pine")
 (3 "Pitch Pine")
 (5 "White Pine"))

(setq copy (copy-alist needles-per-cluster))
=>
((2 "Austrian Pine" "Red Pine")
 (3 "Pitch Pine")
 (5 "White Pine"))

(eq needles-per-cluster copy)
     => nil
(equal needles-per-cluster copy)
     => t
(eq (car needles-per-cluster) (car copy))
     => nil
(cdr (car (cdr needles-per-cluster)))
     => ("Pitch Pine")
(eq (cdr (car (cdr needles-per-cluster)))
    (cdr (car (cdr copy))))
     => t

This example shows how copy-alist makes it possible to change the associations of one copy without affecting the other:

(setcdr (assq 3 copy) '("Martian Vacuum Pine"))
(cdr (assq 3 needles-per-cluster))
     => ("Pitch Pine")

Sequences, Arrays, and Vectors

Recall that the sequence type is the union of two other Lisp types: lists and arrays. In other words, any list is a sequence, and any array is a sequence. The common property that all sequences have is that each is an ordered collection of elements.

An array is a single primitive object that has a slot for each of its elements. All the elements are accessible in constant time, but the length of an existing array cannot be changed. Strings, vectors, char-tables and bool-vectors are the four types of arrays.

A list is a sequence of elements, but it is not a single primitive object; it is made of cons cells, one cell per element. Finding the nth element requires looking through n cons cells, so elements farther from the beginning of the list take longer to access. But it is possible to add elements to the list, or remove elements.

The following diagram shows the relationship between these types:

          _____________________________________________
         |                                             |
         |          Sequence                           |
         |  ______   ________________________________  |
         | |      | |                                | |
         | | List | |             Array              | |
         | |      | |    ________       ________     | |
         | |______| |   |        |     |        |    | |
         |          |   | Vector |     | String |    | |
         |          |   |________|     |________|    | |
         |          |  ____________   _____________  | |
         |          | |            | |             | | |
         |          | | Char-table | | Bool-vector | | |
         |          | |____________| |_____________| | |
         |          |________________________________| |
         |_____________________________________________|

The elements of vectors and lists may be any Lisp objects. The elements of strings are all characters.

Sequences

In Emacs Lisp, a sequence is either a list or an array. The common property of all sequences is that they are ordered collections of elements. This section describes functions that accept any kind of sequence.

Function: sequencep object
Returns t if object is a list, vector, or string, nil otherwise.

Function: length sequence
This function returns the number of elements in sequence. If sequence is a cons cell that is not a list (because the final CDR is not nil), a wrong-type-argument error is signaled.

See section Accessing Elements of Lists, for the related function safe-length.

(length '(1 2 3))
    => 3
(length ())
    => 0
(length "foobar")
    => 6
(length [1 2 3])
    => 3
(length (make-bool-vector 5 nil))
    => 5

Function: elt sequence index
This function returns the element of sequence indexed by index. Legitimate values of index are integers ranging from 0 up to one less than the length of sequence. If sequence is a list, then out-of-range values of index return nil; otherwise, they trigger an args-out-of-range error.

(elt [1 2 3 4] 2)
     => 3
(elt '(1 2 3 4) 2)
     => 3
;; We use string to show clearly which character elt returns.
(string (elt "1234" 2))
     => "3"
(elt [1 2 3 4] 4)
     error--> Args out of range: [1 2 3 4], 4
(elt [1 2 3 4] -1)
     error--> Args out of range: [1 2 3 4], -1

This function generalizes aref (see section Functions that Operate on Arrays) and nth (see section Accessing Elements of Lists).

Function: copy-sequence sequence
Returns a copy of sequence. The copy is the same type of object as the original sequence, and it has the same elements in the same order.

Storing a new element into the copy does not affect the original sequence, and vice versa. However, the elements of the new sequence are not copies; they are identical (eq) to the elements of the original. Therefore, changes made within these elements, as found via the copied sequence, are also visible in the original sequence.

If the sequence is a string with text properties, the property list in the copy is itself a copy, not shared with the original's property list. However, the actual values of the properties are shared. See section Text Properties.

See also append in section Building Cons Cells and Lists, concat in section Creating Strings, and vconcat in section Vectors, for others ways to copy sequences.

(setq bar '(1 2))
     => (1 2)
(setq x (vector 'foo bar))
     => [foo (1 2)]
(setq y (copy-sequence x))
     => [foo (1 2)]

(eq x y)
     => nil
(equal x y)
     => t
(eq (elt x 1) (elt y 1))
     => t

;; Replacing an element of one sequence.
(aset x 0 'quux)
x => [quux (1 2)]
y => [foo (1 2)]

;; Modifying the inside of a shared element.
(setcar (aref x 1) 69)
x => [quux (69 2)]
y => [foo (69 2)]

Arrays

An array object has slots that hold a number of other Lisp objects, called the elements of the array. Any element of an array may be accessed in constant time. In contrast, an element of a list requires access time that is proportional to the position of the element in the list.

Emacs defines four types of array, all one-dimensional: strings, vectors, bool-vectors and char-tables. A vector is a general array; its elements can be any Lisp objects. A string is a specialized array; its elements must be characters (i.e., integers between 0 and 255). Each type of array has its own read syntax. See section String Type, and section Vector Type.

All four kinds of array share these characteristics:

When you create an array, other than a char-table, you must specify its length. You cannot specify the length of a char-table, because that is determined by the range of character codes.

In principle, if you want an array of text characters, you could use either a string or a vector. In practice, we always choose strings for such applications, for four reasons:

By contrast, for an array of keyboard input characters (such as a key sequence), a vector may be necessary, because many keyboard input characters are outside the range that will fit in a string. See section Key Sequence Input.

Functions that Operate on Arrays

In this section, we describe the functions that accept all types of arrays.

Function: arrayp object
This function returns t if object is an array (i.e., a vector, a string, a bool-vector or a char-table).

(arrayp [a])
     => t
(arrayp "asdf")
     => t
(arrayp (syntax-table))    ;; A char-table.
     => t

Function: aref array index
This function returns the indexth element of array. The first element is at index zero.

(setq primes [2 3 5 7 11 13])
     => [2 3 5 7 11 13]
(aref primes 4)
     => 11
(aref "abcdefg" 1)
     => 98           ; `b' is ASCII code 98.

See also the function elt, in section Sequences.

Function: aset array index object
This function sets the indexth element of array to be object. It returns object.

(setq w [foo bar baz])
     => [foo bar baz]
(aset w 0 'fu)
     => fu
w
     => [fu bar baz]

(setq x "asdfasfd")
     => "asdfasfd"
(aset x 3 ?Z)
     => 90
x
     => "asdZasfd"

If array is a string and object is not a character, a wrong-type-argument error results. If array is a string and object is character, but object does not use the same number of bytes as the character currently stored in (aref object index), that is also an error. See section Splitting Characters.

Function: fillarray array object
This function fills the array array with object, so that each element of array is object. It returns array.

(setq a [a b c d e f g])
     => [a b c d e f g]
(fillarray a 0)
     => [0 0 0 0 0 0 0]
a
     => [0 0 0 0 0 0 0]
(setq s "When in the course")
     => "When in the course"
(fillarray s ?-)
     => "------------------"

If array is a string and object is not a character, a wrong-type-argument error results.

The general sequence functions copy-sequence and length are often useful for objects known to be arrays. See section Sequences.

Vectors

Arrays in Lisp, like arrays in most languages, are blocks of memory whose elements can be accessed in constant time. A vector is a general-purpose array of specified length; its elements can be any Lisp objects. (By contrast, a string can hold only characters as elements.) Vectors in Emacs are used for obarrays (vectors of symbols), and as part of keymaps (vectors of commands). They are also used internally as part of the representation of a byte-compiled function; if you print such a function, you will see a vector in it.

In Emacs Lisp, the indices of the elements of a vector start from zero and count up from there.

Vectors are printed with square brackets surrounding the elements. Thus, a vector whose elements are the symbols a, b and a is printed as [a b a]. You can write vectors in the same way in Lisp input.

A vector, like a string or a number, is considered a constant for evaluation: the result of evaluating it is the same vector. This does not evaluate or even examine the elements of the vector. See section Self-Evaluating Forms.

Here are examples illustrating these principles:

(setq avector [1 two '(three) "four" [five]])
     => [1 two (quote (three)) "four" [five]]
(eval avector)
     => [1 two (quote (three)) "four" [five]]
(eq avector (eval avector))
     => t

Functions for Vectors

Here are some functions that relate to vectors:

Function: vectorp object
This function returns t if object is a vector.

(vectorp [a])
     => t
(vectorp "asdf")
     => nil

Function: vector &rest objects
This function creates and returns a vector whose elements are the arguments, objects.

(vector 'foo 23 [bar baz] "rats")
     => [foo 23 [bar baz] "rats"]
(vector)
     => []

Function: make-vector length object
This function returns a new vector consisting of length elements, each initialized to object.

(setq sleepy (make-vector 9 'Z))
     => [Z Z Z Z Z Z Z Z Z]

Function: vconcat &rest sequences
This function returns a new vector containing all the elements of the sequences. The arguments sequences may be any kind of arrays, including lists, vectors, or strings. If no sequences are given, an empty vector is returned.

The value is a newly constructed vector that is not eq to any existing vector.

(setq a (vconcat '(A B C) '(D E F)))
     => [A B C D E F]
(eq a (vconcat a))
     => nil
(vconcat)
     => []
(vconcat [A B C] "aa" '(foo (6 7)))
     => [A B C 97 97 foo (6 7)]

The vconcat function also allows byte-code function objects as arguments. This is a special feature to make it easy to access the entire contents of a byte-code function object. See section Byte-Code Function Objects.

The vconcat function also allows integers as arguments. It converts them to strings of digits, making up the decimal print representation of the integer, and then uses the strings instead of the original integers. Don't use this feature; we plan to eliminate it. If you already use this feature, change your programs now! The proper way to convert an integer to a decimal number in this way is with format (see section Formatting Strings) or number-to-string (see section Conversion of Characters and Strings).

For other concatenation functions, see mapconcat in section Mapping Functions, concat in section Creating Strings, and append in section Building Cons Cells and Lists.

The append function provides a way to convert a vector into a list with the same elements (see section Building Cons Cells and Lists):

(setq avector [1 two (quote (three)) "four" [five]])
     => [1 two (quote (three)) "four" [five]]
(append avector nil)
     => (1 two (quote (three)) "four" [five])

Char-Tables

A char-table is much like a vector, except that it is indexed by character codes. Any valid character code, without modifiers, can be used as an index in a char-table. You can access a char-table's elements with aref and aset, as with any array. In addition, a char-table can have extra slots to hold additional data not associated with particular character codes. Char-tables are constants when evaluated.

Each char-table has a subtype which is a symbol. The subtype has two purposes: to distinguish char-tables meant for different uses, and to control the number of extra slots. For example, display tables are char-tables with display-table as the subtype, and syntax tables are char-tables with syntax-table as the subtype. A valid subtype must have a char-table-extra-slots property which is an integer between 0 and 10. This integer specifies the number of extra slots in the char-table.

A char-table can have a parent. which is another char-table. If it does, then whenever the char-table specifies nil for a particular character c, it inherits the value specified in the parent. In other words, (aref char-table c) returns the value from the parent of char-table if char-table itself specifies nil.

A char-table can also have a default value. If so, then (aref char-table c) returns the default value whenever the char-table does not specify any other non-nil value.

Function: make-char-table subtype &optional init
Return a newly created char-table, with subtype subtype. Each element is initialized to init, which defaults to nil. You cannot alter the subtype of a char-table after the char-table is created.

There is no argument to specify the length of the char-table, because all char-tables have room for any valid character code as an index.

Function: char-table-p object
This function returns t if object is a char-table, otherwise nil.

Function: char-table-subtype char-table
This function returns the subtype symbol of char-table.

Function: set-char-table-default char-table new-default
This function sets the default value of char-table to new-default.

There is no special function to access the default value of a char-table. To do that, use (char-table-range char-table nil).

Function: char-table-parent char-table
This function returns the parent of char-table. The parent is always either nil or another char-table.

Function: set-char-table-parent char-table new-parent
This function sets the parent of char-table to new-parent.

Function: char-table-extra-slot char-table n
This function returns the contents of extra slot n of char-table. The number of extra slots in a char-table is determined by its subtype.

Function: set-char-table-extra-slot char-table n value
This function stores value in extra slot n of char-table.

A char-table can specify an element value for a single character code; it can also specify a value for an entire character set.

Function: char-table-range char-table range
This returns the value specified in char-table for a range of characters range. Here are the possibilities for range:

nil
Refers to the default value.
char
Refers to the element for character char (supposing char is a valid character code).
charset
Refers to the value specified for the whole character set charset (see section Character Sets).
generic-char
A generic character stands for a character set; specifying the generic character as argument is equivalent to specifying the character set name. See section Splitting Characters, for a description of generic characters.

Function: set-char-table-range char-table range value
This function sets the value in char-table for a range of characters range. Here are the possibilities for range:

nil
Refers to the default value.
t
Refers to the whole range of character codes.
char
Refers to the element for character char (supposing char is a valid character code).
charset
Refers to the value specified for the whole character set charset (see section Character Sets).
generic-char
A generic character stands for a character set; specifying the generic character as argument is equivalent to specifying the character set name. See section Splitting Characters, for a description of generic characters.

Function: map-char-table function char-table
This function calls function for each element of char-table. function is called with two arguments, a key and a value. The key is a possible range argument for char-table-range---either a valid character or a generic character--and the value is (char-table-range char-table key).

Overall, the key-value pairs passed to function describe all the values stored in char-table.

The return value is always nil; to make this function useful, function should have side effects. For example, here is how to examine each element of the syntax table:

(let (accumulator)
  (map-char-table
   #'(lambda (key value)
       (setq accumulator
             (cons (list key value) accumulator)))
   (syntax-table))
  accumulator)
=>
((475008 nil) (474880 nil) (474752 nil) (474624 nil)
 ... (5 (3)) (4 (3)) (3 (3)) (2 (3)) (1 (3)) (0 (3)))

Bool-vectors

A bool-vector is much like a vector, except that it stores only the values t and nil. If you try to store any non-nil value into an element of the bool-vector, the effect is to store t there. As with all arrays, bool-vector indices start from 0, and the length cannot be changed once the bool-vector is created. Bool-vectors are constants when evaluated.

There are two special functions for working with bool-vectors; aside from that, you manipulate them with same functions used for other kinds of arrays.

Function: make-bool-vector length initial
Return a new book-vector of length elements, each one initialized to initial.

Function: bool-vector-p object
This returns t if object is a bool-vector, and nil otherwise.

Symbols

A symbol is an object with a unique name. This chapter describes symbols, their components, their property lists, and how they are created and interned. Separate chapters describe the use of symbols as variables and as function names; see section Variables, and section Functions. For the precise read syntax for symbols, see section Symbol Type.

You can test whether an arbitrary Lisp object is a symbol with symbolp:

Function: symbolp object
This function returns t if object is a symbol, nil otherwise.

Symbol Components

Each symbol has four components (or "cells"), each of which references another object:

Print name
The print name cell holds a string that names the symbol for reading and printing. See symbol-name in section Creating and Interning Symbols.
Value
The value cell holds the current value of the symbol as a variable. When a symbol is used as a form, the value of the form is the contents of the symbol's value cell. See symbol-value in section Accessing Variable Values.
Function
The function cell holds the function definition of the symbol. When a symbol is used as a function, its function definition is used in its place. This cell is also used to make a symbol stand for a keymap or a keyboard macro, for editor command execution. Because each symbol has separate value and function cells, variables and function names do not conflict. See symbol-function in section Accessing Function Cell Contents.
Property list
The property list cell holds the property list of the symbol. See symbol-plist in section Property Lists.

The print name cell always holds a string, and cannot be changed. The other three cells can be set individually to any specified Lisp object.

The print name cell holds the string that is the name of the symbol. Since symbols are represented textually by their names, it is important not to have two symbols with the same name. The Lisp reader ensures this: every time it reads a symbol, it looks for an existing symbol with the specified name before it creates a new one. (In GNU Emacs Lisp, this lookup uses a hashing algorithm and an obarray; see section Creating and Interning Symbols.)

In normal usage, the function cell usually contains a function (see section Functions) or a macro (see section Macros), as that is what the Lisp interpreter expects to see there (see section Evaluation). Keyboard macros (see section Keyboard Macros), keymaps (see section Keymaps) and autoload objects (see section Autoloading) are also sometimes stored in the function cells of symbols. We often refer to "the function foo" when we really mean the function stored in the function cell of the symbol foo. We make the distinction only when necessary.

The property list cell normally should hold a correctly formatted property list (see section Property Lists), as a number of functions expect to see a property list there.

The function cell or the value cell may be void, which means that the cell does not reference any object. (This is not the same thing as holding the symbol void, nor the same as holding the symbol nil.) Examining a function or value cell that is void results in an error, such as `Symbol's value as variable is void'.

The four functions symbol-name, symbol-value, symbol-plist, and symbol-function return the contents of the four cells of a symbol. Here as an example we show the contents of the four cells of the symbol buffer-file-name:

(symbol-name 'buffer-file-name)
     => "buffer-file-name"
(symbol-value 'buffer-file-name)
     => "/gnu/elisp/symbols.texi"
(symbol-plist 'buffer-file-name)
     => (variable-documentation 29529)
(symbol-function 'buffer-file-name)
     => #<subr buffer-file-name>

Because this symbol is the variable which holds the name of the file being visited in the current buffer, the value cell contents we see are the name of the source file of this chapter of the Emacs Lisp Manual. The property list cell contains the list (variable-documentation 29529) which tells the documentation functions where to find the documentation string for the variable buffer-file-name in the `DOC-version' file. (29529 is the offset from the beginning of the `DOC-version' file to where that documentation string begins--see section Documentation Basics.) The function cell contains the function for returning the name of the file. buffer-file-name names a primitive function, which has no read syntax and prints in hash notation (see section Primitive Function Type). A symbol naming a function written in Lisp would have a lambda expression (or a byte-code object) in this cell.

Defining Symbols

A definition in Lisp is a special form that announces your intention to use a certain symbol in a particular way. In Emacs Lisp, you can define a symbol as a variable, or define it as a function (or macro), or both independently.

A definition construct typically specifies a value or meaning for the symbol for one kind of use, plus documentation for its meaning when used in this way. Thus, when you define a symbol as a variable, you can supply an initial value for the variable, plus documentation for the variable.

defvar and defconst are special forms that define a symbol as a global variable. They are documented in detail in section Defining Global Variables. For defining user option variables that can be customized, use defcustom (see section Writing Customization Definitions).

defun defines a symbol as a function, creating a lambda expression and storing it in the function cell of the symbol. This lambda expression thus becomes the function definition of the symbol. (The term "function definition", meaning the contents of the function cell, is derived from the idea that defun gives the symbol its definition as a function.) defsubst and defalias are two other ways of defining a function. See section Functions.

defmacro defines a symbol as a macro. It creates a macro object and stores it in the function cell of the symbol. Note that a given symbol can be a macro or a function, but not both at once, because both macro and function definitions are kept in the function cell, and that cell can hold only one Lisp object at any given time. See section Macros.

In Emacs Lisp, a definition is not required in order to use a symbol as a variable or function. Thus, you can make a symbol a global variable with setq, whether you define it first or not. The real purpose of definitions is to guide programmers and programming tools. They inform programmers who read the code that certain symbols are intended to be used as variables, or as functions. In addition, utilities such as `etags' and `make-docfile' recognize definitions, and add appropriate information to tag tables and the `DOC-version' file. See section Access to Documentation Strings.

Creating and Interning Symbols

To understand how symbols are created in GNU Emacs Lisp, you must know how Lisp reads them. Lisp must ensure that it finds the same symbol every time it reads the same set of characters. Failure to do so would cause complete confusion.

When the Lisp reader encounters a symbol, it reads all the characters of the name. Then it "hashes" those characters to find an index in a table called an obarray. Hashing is an efficient method of looking something up. For example, instead of searching a telephone book cover to cover when looking up Jan Jones, you start with the J's and go from there. That is a simple version of hashing. Each element of the obarray is a bucket which holds all the symbols with a given hash code; to look for a given name, it is sufficient to look through all the symbols in the bucket for that name's hash code.

If a symbol with the desired name is found, the reader uses that symbol. If the obarray does not contain a symbol with that name, the reader makes a new symbol and adds it to the obarray. Finding or adding a symbol with a certain name is called interning it, and the symbol is then called an interned symbol.

Interning ensures that each obarray has just one symbol with any particular name. Other like-named symbols may exist, but not in the same obarray. Thus, the reader gets the same symbols for the same names, as long as you keep reading with the same obarray.

No obarray contains all symbols; in fact, some symbols are not in any obarray. They are called uninterned symbols. An uninterned symbol has the same four cells as other symbols; however, the only way to gain access to it is by finding it in some other object or as the value of a variable.

In Emacs Lisp, an obarray is actually a vector. Each element of the vector is a bucket; its value is either an interned symbol whose name hashes to that bucket, or 0 if the bucket is empty. Each interned symbol has an internal link (invisible to the user) to the next symbol in the bucket. Because these links are invisible, there is no way to find all the symbols in an obarray except using mapatoms (below). The order of symbols in a bucket is not significant.

In an empty obarray, every element is 0, and you can create an obarray with (make-vector length 0). This is the only valid way to create an obarray. Prime numbers as lengths tend to result in good hashing; lengths one less than a power of two are also good.

Do not try to put symbols in an obarray yourself. This does not work--only intern can enter a symbol in an obarray properly.

Common Lisp note: In Common Lisp, a single symbol may be interned in several obarrays.

Most of the functions below take a name and sometimes an obarray as arguments. A wrong-type-argument error is signaled if the name is not a string, or if the obarray is not a vector.

Function: symbol-name symbol
This function returns the string that is symbol's name. For example:

(symbol-name 'foo)
     => "foo"

Warning: Changing the string by substituting characters does change the name of the symbol, but fails to update the obarray, so don't do it!

Function: make-symbol name
This function returns a newly-allocated, uninterned symbol whose name is name (which must be a string). Its value and function definition are void, and its property list is nil. In the example below, the value of sym is not eq to foo because it is a distinct uninterned symbol whose name is also `foo'.

(setq sym (make-symbol "foo"))
     => foo
(eq sym 'foo)
     => nil

Function: intern name &optional obarray
This function returns the interned symbol whose name is name. If there is no such symbol in the obarray obarray, intern creates a new one, adds it to the obarray, and returns it. If obarray is omitted, the value of the global variable obarray is used.

(setq sym (intern "foo"))
     => foo
(eq sym 'foo)
     => t

(setq sym1 (intern "foo" other-obarray))
     => foo
(eq sym 'foo)
     => nil

Common Lisp note: In Common Lisp, you can intern an existing symbol in an obarray. In Emacs Lisp, you cannot do this, because the argument to intern must be a string, not a symbol.

Function: intern-soft name &optional obarray
This function returns the symbol in obarray whose name is name, or nil if obarray has no symbol with that name. Therefore, you can use intern-soft to test whether a symbol with a given name is already interned. If obarray is omitted, the value of the global variable obarray is used.

(intern-soft "frazzle")        ; No such symbol exists.
     => nil
(make-symbol "frazzle")        ; Create an uninterned one.
     => frazzle
(intern-soft "frazzle")        ; That one cannot be found.
     => nil
(setq sym (intern "frazzle"))  ; Create an interned one.
     => frazzle
(intern-soft "frazzle")        ; That one can be found!
     => frazzle
(eq sym 'frazzle)              ; And it is the same one.
     => t

Variable: obarray
This variable is the standard obarray for use by intern and read.

Function: mapatoms function &optional obarray
This function calls function once with each symbol in the obarray obarray. Then it returns nil. If obarray is omitted, it defaults to the value of obarray, the standard obarray for ordinary symbols.

(setq count 0)
     => 0
(defun count-syms (s)
  (setq count (1+ count)))
     => count-syms
(mapatoms 'count-syms)
     => nil
count
     => 1871

See documentation in section Access to Documentation Strings, for another example using mapatoms.

Function: unintern symbol &optional obarray
This function deletes symbol from the obarray obarray. If symbol is not actually in the obarray, unintern does nothing. If obarray is nil, the current obarray is used.

If you provide a string instead of a symbol as symbol, it stands for a symbol name. Then unintern deletes the symbol (if any) in the obarray which has that name. If there is no such symbol, unintern does nothing.

If unintern does delete a symbol, it returns t. Otherwise it returns nil.

Property Lists

A property list (plist for short) is a list of paired elements stored in the property list cell of a symbol. Each of the pairs associates a property name (usually a symbol) with a property or value. Property lists are generally used to record information about a symbol, such as its documentation as a variable, the name of the file where it was defined, or perhaps even the grammatical class of the symbol (representing a word) in a language-understanding system.

Character positions in a string or buffer can also have property lists. See section Text Properties.

The property names and values in a property list can be any Lisp objects, but the names are usually symbols. Property list functions compare the property names using eq. Here is an example of a property list, found on the symbol progn when the compiler is loaded:

(lisp-indent-function 0 byte-compile byte-compile-progn)

Here lisp-indent-function and byte-compile are property names, and the other two elements are the corresponding values.

Property Lists and Association Lists

Association lists (see section Association Lists) are very similar to property lists. In contrast to association lists, the order of the pairs in the property list is not significant since the property names must be distinct.

Property lists are better than association lists for attaching information to various Lisp function names or variables. If your program keeps all of its associations in one association list, it will typically need to search that entire list each time it checks for an association. This could be slow. By contrast, if you keep the same information in the property lists of the function names or variables themselves, each search will scan only the length of one property list, which is usually short. This is why the documentation for a variable is recorded in a property named variable-documentation. The byte compiler likewise uses properties to record those functions needing special treatment.

However, association lists have their own advantages. Depending on your application, it may be faster to add an association to the front of an association list than to update a property. All properties for a symbol are stored in the same property list, so there is a possibility of a conflict between different uses of a property name. (For this reason, it is a good idea to choose property names that are probably unique, such as by beginning the property name with the program's usual name-prefix for variables and functions.) An association list may be used like a stack where associations are pushed on the front of the list and later discarded; this is not possible with a property list.

Property List Functions for Symbols

Function: symbol-plist symbol
This function returns the property list of symbol.

Function: setplist symbol plist
This function sets symbol's property list to plist. Normally, plist should be a well-formed property list, but this is not enforced.

(setplist 'foo '(a 1 b (2 3) c nil))
     => (a 1 b (2 3) c nil)
(symbol-plist 'foo)
     => (a 1 b (2 3) c nil)

For symbols in special obarrays, which are not used for ordinary purposes, it may make sense to use the property list cell in a nonstandard fashion; in fact, the abbrev mechanism does so (see section Abbrevs And Abbrev Expansion).

Function: get symbol property
This function finds the value of the property named property in symbol's property list. If there is no such property, nil is returned. Thus, there is no distinction between a value of nil and the absence of the property.

The name property is compared with the existing property names using eq, so any object is a legitimate property.

See put for an example.

Function: put symbol property value
This function puts value onto symbol's property list under the property name property, replacing any previous property value. The put function returns value.

(put 'fly 'verb 'transitive)
     =>'transitive
(put 'fly 'noun '(a buzzing little bug))
     => (a buzzing little bug)
(get 'fly 'verb)
     => transitive
(symbol-plist 'fly)
     => (verb transitive noun (a buzzing little bug))

Property Lists Outside Symbols

These two functions are useful for manipulating property lists that are stored in places other than symbols:

Function: plist-get plist property
This returns the value of the property property stored in the property list plist. For example,

(plist-get '(foo 4) 'foo)
     => 4

Function: plist-put plist property value
This stores value as the value of the property property in the property list plist. It may modify plist destructively, or it may construct a new list structure without altering the old. The function returns the modified property list, so you can store that back in the place where you got plist. For example,

(setq my-plist '(bar t foo 4))
     => (bar t foo 4)
(setq my-plist (plist-put my-plist 'foo 69))
     => (bar t foo 69)
(setq my-plist (plist-put my-plist 'quux '(a)))
     => (bar t foo 69 quux (a))

You could define put in terms of plist-put as follows:

(defun put (symbol prop value)
  (setplist symbol
            (plist-put (symbol-plist symbol) prop value)))

Evaluation

The evaluation of expressions in Emacs Lisp is performed by the Lisp interpreter---a program that receives a Lisp object as input and computes its value as an expression. How it does this depends on the data type of the object, according to rules described in this chapter. The interpreter runs automatically to evaluate portions of your program, but can also be called explicitly via the Lisp primitive function eval.

A Lisp object that is intended for evaluation is called an expression or a form. The fact that expressions are data objects and not merely text is one of the fundamental differences between Lisp-like languages and typical programming languages. Any object can be evaluated, but in practice only numbers, symbols, lists and strings are evaluated very often.

It is very common to read a Lisp expression and then evaluate the expression, but reading and evaluation are separate activities, and either can be performed alone. Reading per se does not evaluate anything; it converts the printed representation of a Lisp object to the object itself. It is up to the caller of read whether this object is a form to be evaluated, or serves some entirely different purpose. See section Input Functions.

Do not confuse evaluation with command key interpretation. The editor command loop translates keyboard input into a command (an interactively callable function) using the active keymaps, and then uses call-interactively to invoke the command. The execution of the command itself involves evaluation if the command is written in Lisp, but that is not a part of command key interpretation itself. See section Command Loop.

Evaluation is a recursive process. That is, evaluation of a form may call eval to evaluate parts of the form. For example, evaluation of a function call first evaluates each argument of the function call, and then evaluates each form in the function body. Consider evaluation of the form (car x): the subform x must first be evaluated recursively, so that its value can be passed as an argument to the function car.

Evaluation of a function call ultimately calls the function specified in it. See section Functions. The execution of the function may itself work by evaluating the function definition; or the function may be a Lisp primitive implemented in C, or it may be a byte-compiled function (see section Byte Compilation).

The evaluation of forms takes place in a context called the environment, which consists of the current values and bindings of all Lisp variables.(2) Whenever a form refers to a variable without creating a new binding for it, the value of the variable's binding in the current environment is used. See section Variables.

Evaluation of a form may create new environments for recursive evaluation by binding variables (see section Local Variables). These environments are temporary and vanish by the time evaluation of the form is complete. The form may also make changes that persist; these changes are called side effects. An example of a form that produces side effects is (setq foo 1).

The details of what evaluation means for each kind of form are described below (see section Kinds of Forms).

Kinds of Forms

A Lisp object that is intended to be evaluated is called a form. How Emacs evaluates a form depends on its data type. Emacs has three different kinds of form that are evaluated differently: symbols, lists, and "all other types". This section describes all three kinds, one by one, starting with the "all other types" which are self-evaluating forms.

Self-Evaluating Forms

A self-evaluating form is any form that is not a list or symbol. Self-evaluating forms evaluate to themselves: the result of evaluation is the same object that was evaluated. Thus, the number 25 evaluates to 25, and the string "foo" evaluates to the string "foo". Likewise, evaluation of a vector does not cause evaluation of the elements of the vector--it returns the same vector with its contents unchanged.

'123               ; A number, shown without evaluation.
     => 123
123                ; Evaluated as usual---result is the same.
     => 123
(eval '123)        ; Evaluated ``by hand''---result is the same.
     => 123
(eval (eval '123)) ; Evaluating twice changes nothing.
     => 123

It is common to write numbers, characters, strings, and even vectors in Lisp code, taking advantage of the fact that they self-evaluate. However, it is quite unusual to do this for types that lack a read syntax, because there's no way to write them textually. It is possible to construct Lisp expressions containing these types by means of a Lisp program. Here is an example:

;; Build an expression containing a buffer object.
(setq print-exp (list 'print (current-buffer)))
     => (print #<buffer eval.texi>)
;; Evaluate it.
(eval print-exp)
     -| #<buffer eval.texi>
     => #<buffer eval.texi>

Symbol Forms

When a symbol is evaluated, it is treated as a variable. The result is the variable's value, if it has one. If it has none (if its value cell is void), an error is signaled. For more information on the use of variables, see section Variables.

In the following example, we set the value of a symbol with setq. Then we evaluate the symbol, and get back the value that setq stored.

(setq a 123)
     => 123
(eval 'a)
     => 123
a
     => 123

The symbols nil and t are treated specially, so that the value of nil is always nil, and the value of t is always t; you cannot set or bind them to any other values. Thus, these two symbols act like self-evaluating forms, even though eval treats them like any other symbol. A symbol whose name starts with `:' also self-evaluates in the same way; likewise, its value ordinarily cannot be changed. See section Variables That Never Change.

Classification of List Forms

A form that is a nonempty list is either a function call, a macro call, or a special form, according to its first element. These three kinds of forms are evaluated in different ways, described below. The remaining list elements constitute the arguments for the function, macro, or special form.

The first step in evaluating a nonempty list is to examine its first element. This element alone determines what kind of form the list is and how the rest of the list is to be processed. The first element is not evaluated, as it would be in some Lisp dialects such as Scheme.

Symbol Function Indirection

If the first element of the list is a symbol then evaluation examines the symbol's function cell, and uses its contents instead of the original symbol. If the contents are another symbol, this process, called symbol function indirection, is repeated until it obtains a non-symbol. See section Naming a Function, for more information about using a symbol as a name for a function stored in the function cell of the symbol.

One possible consequence of this process is an infinite loop, in the event that a symbol's function cell refers to the same symbol. Or a symbol may have a void function cell, in which case the subroutine symbol-function signals a void-function error. But if neither of these things happens, we eventually obtain a non-symbol, which ought to be a function or other suitable object.

More precisely, we should now have a Lisp function (a lambda expression), a byte-code function, a primitive function, a Lisp macro, a special form, or an autoload object. Each of these types is a case described in one of the following sections. If the object is not one of these types, the error invalid-function is signaled.

The following example illustrates the symbol indirection process. We use fset to set the function cell of a symbol and symbol-function to get the function cell contents (see section Accessing Function Cell Contents). Specifically, we store the symbol car into the function cell of first, and the symbol first into the function cell of erste.

;; Build this function cell linkage:
;;   -------------       -----        -------        -------
;;  | #<subr car> | <-- | car |  <-- | first |  <-- | erste |
;;   -------------       -----        -------        -------
(symbol-function 'car)
     => #<subr car>
(fset 'first 'car)
     => car
(fset 'erste 'first)
     => first
(erste '(1 2 3))   ; Call the function referenced by erste.
     => 1

By contrast, the following example calls a function without any symbol function indirection, because the first element is an anonymous Lisp function, not a symbol.

((lambda (arg) (erste arg))
 '(1 2 3)) 
     => 1

Executing the function itself evaluates its body; this does involve symbol function indirection when calling erste.

The built-in function indirect-function provides an easy way to perform symbol function indirection explicitly.

Function: indirect-function function
This function returns the meaning of function as a function. If function is a symbol, then it finds function's function definition and starts over with that value. If function is not a symbol, then it returns function itself.

Here is how you could define indirect-function in Lisp:

(defun indirect-function (function)
  (if (symbolp function)
      (indirect-function (symbol-function function))
    function))

Evaluation of Function Forms

If the first element of a list being evaluated is a Lisp function object, byte-code object or primitive function object, then that list is a function call. For example, here is a call to the function +:

(+ 1 x)

The first step in evaluating a function call is to evaluate the remaining elements of the list from left to right. The results are the actual argument values, one value for each list element. The next step is to call the function with this list of arguments, effectively using the function apply (see section Calling Functions). If the function is written in Lisp, the arguments are used to bind the argument variables of the function (see section Lambda Expressions); then the forms in the function body are evaluated in order, and the value of the last body form becomes the value of the function call.

Lisp Macro Evaluation

If the first element of a list being evaluated is a macro object, then the list is a macro call. When a macro call is evaluated, the elements of the rest of the list are not initially evaluated. Instead, these elements themselves are used as the arguments of the macro. The macro definition computes a replacement form, called the expansion of the macro, to be evaluated in place of the original form. The expansion may be any sort of form: a self-evaluating constant, a symbol, or a list. If the expansion is itself a macro call, this process of expansion repeats until some other sort of form results.

Ordinary evaluation of a macro call finishes by evaluating the expansion. However, the macro expansion is not necessarily evaluated right away, or at all, because other programs also expand macro calls, and they may or may not evaluate the expansions.

Normally, the argument expressions are not evaluated as part of computing the macro expansion, but instead appear as part of the expansion, so they are computed when the expansion is evaluated.

For example, given a macro defined as follows:

(defmacro cadr (x)
  (list 'car (list 'cdr x)))

an expression such as (cadr (assq 'handler list)) is a macro call, and its expansion is:

(car (cdr (assq 'handler list)))

Note that the argument (assq 'handler list) appears in the expansion.

See section Macros, for a complete description of Emacs Lisp macros.

Special Forms

A special form is a primitive function specially marked so that its arguments are not all evaluated. Most special forms define control structures or perform variable bindings--things which functions cannot do.

Each special form has its own rules for which arguments are evaluated and which are used without evaluation. Whether a particular argument is evaluated may depend on the results of evaluating other arguments.

Here is a list, in alphabetical order, of all of the special forms in Emacs Lisp with a reference to where each is described.

and
see section Constructs for Combining Conditions
catch
see section Explicit Nonlocal Exits: catch and throw
cond
see section Conditionals
condition-case
see section Writing Code to Handle Errors
defconst
see section Defining Global Variables
defmacro
see section Defining Macros
defun
see section Defining Functions
defvar
see section Defining Global Variables
function
see section Anonymous Functions
if
see section Conditionals
interactive
see section Interactive Call
let
let*
see section Local Variables
or
see section Constructs for Combining Conditions
prog1
prog2
progn
see section Sequencing
quote
see section Quoting
save-current-buffer
see section The Current Buffer
save-excursion
see section Excursions
save-restriction
see section Narrowing
save-window-excursion
see section Window Configurations
setq
see section How to Alter a Variable Value
setq-default
see section Creating and Deleting Buffer-Local Bindings
track-mouse
see section Mouse Tracking
unwind-protect
see section Nonlocal Exits
while
see section Iteration
with-output-to-temp-buffer
see section Temporary Displays

Common Lisp note: Here are some comparisons of special forms in GNU Emacs Lisp and Common Lisp. setq, if, and catch are special forms in both Emacs Lisp and Common Lisp. defun is a special form in Emacs Lisp, but a macro in Common Lisp. save-excursion is a special form in Emacs Lisp, but doesn't exist in Common Lisp. throw is a special form in Common Lisp (because it must be able to throw multiple values), but it is a function in Emacs Lisp (which doesn't have multiple values).

Autoloading

The autoload feature allows you to call a function or macro whose function definition has not yet been loaded into Emacs. It specifies which file contains the definition. When an autoload object appears as a symbol's function definition, calling that symbol as a function automatically loads the specified file; then it calls the real definition loaded from that file. See section Autoload.

Quoting

The special form quote returns its single argument, as written, without evaluating it. This provides a way to include constant symbols and lists, which are not self-evaluating objects, in a program. (It is not necessary to quote self-evaluating objects such as numbers, strings, and vectors.)

Special Form: quote object
This special form returns object, without evaluating it.

Because quote is used so often in programs, Lisp provides a convenient read syntax for it. An apostrophe character (`'') followed by a Lisp object (in read syntax) expands to a list whose first element is quote, and whose second element is the object. Thus, the read syntax 'x is an abbreviation for (quote x).

Here are some examples of expressions that use quote:

(quote (+ 1 2))
     => (+ 1 2)
(quote foo)
     => foo
'foo
     => foo
''foo
     => (quote foo)
'(quote foo)
     => (quote foo)
['foo]
     => [(quote foo)]

Other quoting constructs include function (see section Anonymous Functions), which causes an anonymous lambda expression written in Lisp to be compiled, and ``' (see section Backquote), which is used to quote only part of a list, while computing and substituting other parts.

Eval

Most often, forms are evaluated automatically, by virtue of their occurrence in a program being run. On rare occasions, you may need to write code that evaluates a form that is computed at run time, such as after reading a form from text being edited or getting one from a property list. On these occasions, use the eval function.

The functions and variables described in this section evaluate forms, specify limits to the evaluation process, or record recently returned values. Loading a file also does evaluation (see section Loading).

Note: it is generally cleaner and more flexible to store a function in a data structure, and call it with funcall or apply, than to store an expression in the data structure and evaluate it. Using functions provides the ability to pass information to them as arguments.

Function: eval form
This is the basic function evaluating an expression. It evaluates form in the current environment and returns the result. How the evaluation proceeds depends on the type of the object (see section Kinds of Forms).

Since eval is a function, the argument expression that appears in a call to eval is evaluated twice: once as preparation before eval is called, and again by the eval function itself. Here is an example:

(setq foo 'bar)
     => bar
(setq bar 'baz)
     => baz
;; Here eval receives argument foo
(eval 'foo)
     => bar
;; Here eval receives argument bar, which is the value of foo
(eval foo)
     => baz

The number of currently active calls to eval is limited to max-lisp-eval-depth (see below).

Command: eval-region start end &optional stream read-function
This function evaluates the forms in the current buffer in the region defined by the positions start and end. It reads forms from the region and calls eval on them until the end of the region is reached, or until an error is signaled and not handled.

If stream is non-nil, the values that result from evaluating the expressions in the region are printed using stream. See section Output Streams.

If read-function is non-nil, it should be a function, which is used instead of read to read expressions one by one. This function is called with one argument, the stream for reading input. You can also use the variable load-read-function (see section How Programs Do Loading) to specify this function, but it is more robust to use the read-function argument.

eval-region always returns nil.

Command: eval-current-buffer &optional stream
This is like eval-region except that it operates on the whole buffer.

Variable: max-lisp-eval-depth
This variable defines the maximum depth allowed in calls to eval, apply, and funcall before an error is signaled (with error message "Lisp nesting exceeds max-lisp-eval-depth"). This limit, with the associated error when it is exceeded, is one way that Lisp avoids infinite recursion on an ill-defined function.

The depth limit counts internal uses of eval, apply, and funcall, such as for calling the functions mentioned in Lisp expressions, and recursive evaluation of function call arguments and function body forms, as well as explicit calls in Lisp code.

The default value of this variable is 300. If you set it to a value less than 100, Lisp will reset it to 100 if the given value is reached. Entry to the Lisp debugger increases the value, if there is little room left, to make sure the debugger itself has room to execute.

max-specpdl-size provides another limit on nesting. See section Local Variables.

Variable: values
The value of this variable is a list of the values returned by all the expressions that were read, evaluated, and printed from buffers (including the minibuffer) by the standard Emacs commands which do this. The elements are ordered most recent first.

(setq x 1)
     => 1
(list 'A (1+ 2) auto-save-default)
     => (A 3 t)
values
     => ((A 3 t) 1 ...)

This variable is useful for referring back to values of forms recently evaluated. It is generally a bad idea to print the value of values itself, since this may be very long. Instead, examine particular elements, like this:

;; Refer to the most recent evaluation result.
(nth 0 values)
     => (A 3 t)
;; That put a new element on,
;;   so all elements move back one.
(nth 1 values)
     => (A 3 t)
;; This gets the element that was next-to-most-recent
;;   before this example.
(nth 3 values)
     => 1

Control Structures

A Lisp program consists of expressions or forms (see section Kinds of Forms). We control the order of execution of the forms by enclosing them in control structures. Control structures are special forms which control when, whether, or how many times to execute the forms they contain.

The simplest order of execution is sequential execution: first form a, then form b, and so on. This is what happens when you write several forms in succession in the body of a function, or at top level in a file of Lisp code--the forms are executed in the order written. We call this textual order. For example, if a function body consists of two forms a and b, evaluation of the function evaluates first a and then b, and the function's value is the value of b.

Explicit control structures make possible an order of execution other than sequential.

Emacs Lisp provides several kinds of control structure, including other varieties of sequencing, conditionals, iteration, and (controlled) jumps--all discussed below. The built-in control structures are special forms since their subforms are not necessarily evaluated or not evaluated sequentially. You can use macros to define your own control structure constructs (see section Macros).

Sequencing

Evaluating forms in the order they appear is the most common way control passes from one form to another. In some contexts, such as in a function body, this happens automatically. Elsewhere you must use a control structure construct to do this: progn, the simplest control construct of Lisp.

A progn special form looks like this:

(progn a b c ...)

and it says to execute the forms a, b, c and so on, in that order. These forms are called the body of the progn form. The value of the last form in the body becomes the value of the entire progn.

In the early days of Lisp, progn was the only way to execute two or more forms in succession and use the value of the last of them. But programmers found they often needed to use a progn in the body of a function, where (at that time) only one form was allowed. So the body of a function was made into an "implicit progn": several forms are allowed just as in the body of an actual progn. Many other control structures likewise contain an implicit progn. As a result, progn is not used as often as it used to be. It is needed now most often inside an unwind-protect, and, or, or in the then-part of an if.

Special Form: progn forms...
This special form evaluates all of the forms, in textual order, returning the result of the final form.

(progn (print "The first form")
       (print "The second form")
       (print "The third form"))
     -| "The first form"
     -| "The second form"
     -| "The third form"
=> "The third form"

Two other control constructs likewise evaluate a series of forms but return a different value:

Special Form: prog1 form1 forms...
This special form evaluates form1 and all of the forms, in textual order, returning the result of form1.

(prog1 (print "The first form")
       (print "The second form")
       (print "The third form"))
     -| "The first form"
     -| "The second form"
     -| "The third form"
=> "The first form"

Here is a way to remove the first element from a list in the variable x, then return the value of that former element:

(prog1 (car x) (setq x (cdr x)))

Special Form: prog2 form1 form2 forms...
This special form evaluates form1, form2, and all of the following forms, in textual order, returning the result of form2.

(prog2 (print "The first form")
       (print "The second form")
       (print "The third form"))
     -| "The first form"
     -| "The second form"
     -| "The third form"
=> "The second form"

Conditionals

Conditional control structures choose among alternatives. Emacs Lisp has four conditional forms: if, which is much the same as in other languages; when and unless, which are variants of if; and cond, which is a generalized case statement.

Special Form: if condition then-form else-forms...
if chooses between the then-form and the else-forms based on the value of condition. If the evaluated condition is non-nil, then-form is evaluated and the result returned. Otherwise, the else-forms are evaluated in textual order, and the value of the last one is returned. (The else part of if is an example of an implicit progn. See section Sequencing.)

If condition has the value nil, and no else-forms are given, if returns nil.

if is a special form because the branch that is not selected is never evaluated--it is ignored. Thus, in the example below, true is not printed because print is never called.

(if nil 
    (print 'true) 
  'very-false)
=> very-false

Macro: when condition then-forms...
This is a variant of if where there are no else-forms, and possibly several then-forms. In particular,

(when condition a b c)

is entirely equivalent to

(if condition (progn a b c) nil)

Macro: unless condition forms...
This is a variant of if where there is no then-form:

(unless condition a b c)

is entirely equivalent to

(if condition nil
   a b c)

Special Form: cond clause...
cond chooses among an arbitrary number of alternatives. Each clause in the cond must be a list. The CAR of this list is the condition; the remaining elements, if any, the body-forms. Thus, a clause looks like this:

(condition body-forms...)

cond tries the clauses in textual order, by evaluating the condition of each clause. If the value of condition is non-nil, the clause "succeeds"; then cond evaluates its body-forms, and the value of the last of body-forms becomes the value of the cond. The remaining clauses are ignored.

If the value of condition is nil, the clause "fails", so the cond moves on to the following clause, trying its condition.

If every condition evaluates to nil, so that every clause fails, cond returns nil.

A clause may also look like this:

(condition)

Then, if condition is non-nil when tested, the value of condition becomes the value of the cond form.

The following example has four clauses, which test for the cases where the value of x is a number, string, buffer and symbol, respectively:

(cond ((numberp x) x)
      ((stringp x) x)
      ((bufferp x)
       (setq temporary-hack x) ; multiple body-forms
       (buffer-name x))        ; in one clause
      ((symbolp x) (symbol-value x)))

Often we want to execute the last clause whenever none of the previous clauses was successful. To do this, we use t as the condition of the last clause, like this: (t body-forms). The form t evaluates to t, which is never nil, so this clause never fails, provided the cond gets to it at all.

For example,

(cond ((eq a 'hack) 'foo)
      (t "default"))
=> "default"

This expression is a cond which returns foo if the value of a is hack, and returns the string "default" otherwise.

Any conditional construct can be expressed with cond or with if. Therefore, the choice between them is a matter of style. For example:

(if a b c)
==
(cond (a b) (t c))

Constructs for Combining Conditions

This section describes three constructs that are often used together with if and cond to express complicated conditions. The constructs and and or can also be used individually as kinds of multiple conditional constructs.

Function: not condition
This function tests for the falsehood of condition. It returns t if condition is nil, and nil otherwise. The function not is identical to null, and we recommend using the name null if you are testing for an empty list.

Special Form: and conditions...
The and special form tests whether all the conditions are true. It works by evaluating the conditions one by one in the order written.

If any of the conditions evaluates to nil, then the result of the and must be nil regardless of the remaining conditions; so and returns right away, ignoring the remaining conditions.

If all the conditions turn out non-nil, then the value of the last of them becomes the value of the and form.

Here is an example. The first condition returns the integer 1, which is not nil. Similarly, the second condition returns the integer 2, which is not nil. The third condition is nil, so the remaining condition is never evaluated.

(and (print 1) (print 2) nil (print 3))
     -| 1
     -| 2
=> nil

Here is a more realistic example of using and:

(if (and (consp foo) (eq (car foo) 'x))
    (message "foo is a list starting with x"))

Note that (car foo) is not executed if (consp foo) returns nil, thus avoiding an error.

and can be expressed in terms of either if or cond. For example:

(and arg1 arg2 arg3)
==
(if arg1 (if arg2 arg3))
==
(cond (arg1 (cond (arg2 arg3))))

Special Form: or conditions...
The or special form tests whether at least one of the conditions is true. It works by evaluating all the conditions one by one in the order written.

If any of the conditions evaluates to a non-nil value, then the result of the or must be non-nil; so or returns right away, ignoring the remaining conditions. The value it returns is the non-nil value of the condition just evaluated.

If all the conditions turn out nil, then the or expression returns nil.

For example, this expression tests whether x is either 0 or nil:

(or (eq x nil) (eq x 0))

Like the and construct, or can be written in terms of cond. For example:

(or arg1 arg2 arg3)
==
(cond (arg1)
      (arg2)
      (arg3))

You could almost write or in terms of if, but not quite:

(if arg1 arg1
  (if arg2 arg2 
    arg3))

This is not completely equivalent because it can evaluate arg1 or arg2 twice. By contrast, (or arg1 arg2 arg3) never evaluates any argument more than once.

Iteration

Iteration means executing part of a program repetitively. For example, you might want to repeat some computation once for each element of a list, or once for each integer from 0 to n. You can do this in Emacs Lisp with the special form while:

Special Form: while condition forms...
while first evaluates condition. If the result is non-nil, it evaluates forms in textual order. Then it reevaluates condition, and if the result is non-nil, it evaluates forms again. This process repeats until condition evaluates to nil.

There is no limit on the number of iterations that may occur. The loop will continue until either condition evaluates to nil or until an error or throw jumps out of it (see section Nonlocal Exits).

The value of a while form is always nil.

(setq num 0)
     => 0
(while (< num 4)
  (princ (format "Iteration %d." num))
  (setq num (1+ num)))
     -| Iteration 0.
     -| Iteration 1.
     -| Iteration 2.
     -| Iteration 3.
     => nil

If you would like to execute something on each iteration before the end-test, put it together with the end-test in a progn as the first argument of while, as shown here:

(while (progn
         (forward-line 1)
         (not (looking-at "^$"))))

This moves forward one line and continues moving by lines until it reaches an empty line. It is peculiar in that the while has no body, just the end test (which also does the real work of moving point).

Nonlocal Exits

A nonlocal exit is a transfer of control from one point in a program to another remote point. Nonlocal exits can occur in Emacs Lisp as a result of errors; you can also use them under explicit control. Nonlocal exits unbind all variable bindings made by the constructs being exited.

Explicit Nonlocal Exits: catch and throw

Most control constructs affect only the flow of control within the construct itself. The function throw is the exception to this rule of normal program execution: it performs a nonlocal exit on request. (There are other exceptions, but they are for error handling only.) throw is used inside a catch, and jumps back to that catch. For example:

(defun foo-outer ()
  (catch 'foo
    (foo-inner)))

(defun foo-inner ()
  ...
  (if x
      (throw 'foo t))
  ...)

The throw form, if executed, transfers control straight back to the corresponding catch, which returns immediately. The code following the throw is not executed. The second argument of throw is used as the return value of the catch.

The function throw finds the matching catch based on the first argument: it searches for a catch whose first argument is eq to the one specified in the throw. If there is more than one applicable catch, the innermost one takes precedence. Thus, in the above example, the throw specifies foo, and the catch in foo-outer specifies the same symbol, so that catch is the applicable one (assuming there is no other matching catch in between).

Executing throw exits all Lisp constructs up to the matching catch, including function calls. When binding constructs such as let or function calls are exited in this way, the bindings are unbound, just as they are when these constructs exit normally (see section Local Variables). Likewise, throw restores the buffer and position saved by save-excursion (see section Excursions), and the narrowing status saved by save-restriction and the window selection saved by save-window-excursion (see section Window Configurations). It also runs any cleanups established with the unwind-protect special form when it exits that form (see section Cleaning Up from Nonlocal Exits).

The throw need not appear lexically within the catch that it jumps to. It can equally well be called from another function called within the catch. As long as the throw takes place chronologically after entry to the catch, and chronologically before exit from it, it has access to that catch. This is why throw can be used in commands such as exit-recursive-edit that throw back to the editor command loop (see section Recursive Editing).

Common Lisp note: Most other versions of Lisp, including Common Lisp, have several ways of transferring control nonsequentially: return, return-from, and go, for example. Emacs Lisp has only throw.

Special Form: catch tag body...
catch establishes a return point for the throw function. The return point is distinguished from other such return points by tag, which may be any Lisp object except nil. The argument tag is evaluated normally before the return point is established.

With the return point in effect, catch evaluates the forms of the body in textual order. If the forms execute normally, without error or nonlocal exit, the value of the last body form is returned from the catch.

If a throw is done within body specifying the same value tag, the catch exits immediately; the value it returns is whatever was specified as the second argument of throw.

Function: throw tag value
The purpose of throw is to return from a return point previously established with catch. The argument tag is used to choose among the various existing return points; it must be eq to the value specified in the catch. If multiple return points match tag, the innermost one is used.

The argument value is used as the value to return from that catch.

If no return point is in effect with tag tag, then a no-catch error is signaled with data (tag value).

Examples of catch and throw

One way to use catch and throw is to exit from a doubly nested loop. (In most languages, this would be done with a "go to".) Here we compute (foo i j) for i and j varying from 0 to 9:

(defun search-foo ()
  (catch 'loop
    (let ((i 0))
      (while (< i 10)
        (let ((j 0))
          (while (< j 10)
            (if (foo i j)
                (throw 'loop (list i j)))
            (setq j (1+ j))))
        (setq i (1+ i))))))

If foo ever returns non-nil, we stop immediately and return a list of i and j. If foo always returns nil, the catch returns normally, and the value is nil, since that is the result of the while.

Here are two tricky examples, slightly different, showing two return points at once. First, two return points with the same tag, hack:

(defun catch2 (tag)
  (catch tag
    (throw 'hack 'yes)))
=> catch2

(catch 'hack 
  (print (catch2 'hack))
  'no)
-| yes
=> no

Since both return points have tags that match the throw, it goes to the inner one, the one established in catch2. Therefore, catch2 returns normally with value yes, and this value is printed. Finally the second body form in the outer catch, which is 'no, is evaluated and returned from the outer catch.

Now let's change the argument given to catch2:

(defun catch2 (tag)
  (catch tag
    (throw 'hack 'yes)))
=> catch2

(catch 'hack
  (print (catch2 'quux))
  'no)
=> yes

We still have two return points, but this time only the outer one has the tag hack; the inner one has the tag quux instead. Therefore, throw makes the outer catch return the value yes. The function print is never called, and the body-form 'no is never evaluated.

Errors

When Emacs Lisp attempts to evaluate a form that, for some reason, cannot be evaluated, it signals an error.

When an error is signaled, Emacs's default reaction is to print an error message and terminate execution of the current command. This is the right thing to do in most cases, such as if you type C-f at the end of the buffer.

In complicated programs, simple termination may not be what you want. For example, the program may have made temporary changes in data structures, or created temporary buffers that should be deleted before the program is finished. In such cases, you would use unwind-protect to establish cleanup expressions to be evaluated in case of error. (See section Cleaning Up from Nonlocal Exits.) Occasionally, you may wish the program to continue execution despite an error in a subroutine. In these cases, you would use condition-case to establish error handlers to recover control in case of error.

Resist the temptation to use error handling to transfer control from one part of the program to another; use catch and throw instead. See section Explicit Nonlocal Exits: catch and throw.

How to Signal an Error

Most errors are signaled "automatically" within Lisp primitives which you call for other purposes, such as if you try to take the CAR of an integer or move forward a character at the end of the buffer; you can also signal errors explicitly with the functions error and signal.

Quitting, which happens when the user types C-g, is not considered an error, but it is handled almost like an error. See section Quitting.

Function: error format-string &rest args
This function signals an error with an error message constructed by applying format (see section Conversion of Characters and Strings) to format-string and args.

These examples show typical uses of error:

(error "That is an error -- try something else")
     error--> That is an error -- try something else

(error "You have committed %d errors" 10)
     error--> You have committed 10 errors

error works by calling signal with two arguments: the error symbol error, and a list containing the string returned by format.

Warning: If you want to use your own string as an error message verbatim, don't just write (error string). If string contains `%', it will be interpreted as a format specifier, with undesirable results. Instead, use (error "%s" string).

Function: signal error-symbol data
This function signals an error named by error-symbol. The argument data is a list of additional Lisp objects relevant to the circumstances of the error.

The argument error-symbol must be an error symbol---a symbol bearing a property error-conditions whose value is a list of condition names. This is how Emacs Lisp classifies different sorts of errors.

The number and significance of the objects in data depends on error-symbol. For example, with a wrong-type-arg error, there should be two objects in the list: a predicate that describes the type that was expected, and the object that failed to fit that type. See section Error Symbols and Condition Names, for a description of error symbols.

Both error-symbol and data are available to any error handlers that handle the error: condition-case binds a local variable to a list of the form (error-symbol . data) (see section Writing Code to Handle Errors). If the error is not handled, these two values are used in printing the error message.

The function signal never returns (though in older Emacs versions it could sometimes return).

(signal 'wrong-number-of-arguments '(x y))
     error--> Wrong number of arguments: x, y

(signal 'no-such-error '("My unknown error condition"))
     error--> peculiar error: "My unknown error condition"

Common Lisp note: Emacs Lisp has nothing like the Common Lisp concept of continuable errors.

How Emacs Processes Errors

When an error is signaled, signal searches for an active handler for the error. A handler is a sequence of Lisp expressions designated to be executed if an error happens in part of the Lisp program. If the error has an applicable handler, the handler is executed, and control resumes following the handler. The handler executes in the environment of the condition-case that established it; all functions called within that condition-case have already been exited, and the handler cannot return to them.

If there is no applicable handler for the error, the current command is terminated and control returns to the editor command loop, because the command loop has an implicit handler for all kinds of errors. The command loop's handler uses the error symbol and associated data to print an error message.

An error that has no explicit handler may call the Lisp debugger. The debugger is enabled if the variable debug-on-error (see section Entering the Debugger on an Error) is non-nil. Unlike error handlers, the debugger runs in the environment of the error, so that you can examine values of variables precisely as they were at the time of the error.

Writing Code to Handle Errors

The usual effect of signaling an error is to terminate the command that is running and return immediately to the Emacs editor command loop. You can arrange to trap errors occurring in a part of your program by establishing an error handler, with the special form condition-case. A simple example looks like this:

(condition-case nil
    (delete-file filename)
  (error nil))

This deletes the file named filename, catching any error and returning nil if an error occurs.

The second argument of condition-case is called the protected form. (In the example above, the protected form is a call to delete-file.) The error handlers go into effect when this form begins execution and are deactivated when this form returns. They remain in effect for all the intervening time. In particular, they are in effect during the execution of functions called by this form, in their subroutines, and so on. This is a good thing, since, strictly speaking, errors can be signaled only by Lisp primitives (including signal and error) called by the protected form, not by the protected form itself.

The arguments after the protected form are handlers. Each handler lists one or more condition names (which are symbols) to specify which errors it will handle. The error symbol specified when an error is signaled also defines a list of condition names. A handler applies to an error if they have any condition names in common. In the example above, there is one handler, and it specifies one condition name, error, which covers all errors.

The search for an applicable handler checks all the established handlers starting with the most recently established one. Thus, if two nested condition-case forms offer to handle the same error, the inner of the two will actually handle it.

If an error is handled by some condition-case form, this ordinarily prevents the debugger from being run, even if debug-on-error says this error should invoke the debugger. See section Entering the Debugger on an Error. If you want to be able to debug errors that are caught by a condition-case, set the variable debug-on-signal to a non-nil value.

When an error is handled, control returns to the handler. Before this happens, Emacs unbinds all variable bindings made by binding constructs that are being exited and executes the cleanups of all unwind-protect forms that are exited. Once control arrives at the handler, the body of the handler is executed.

After execution of the handler body, execution returns from the condition-case form. Because the protected form is exited completely before execution of the handler, the handler cannot resume execution at the point of the error, nor can it examine variable bindings that were made within the protected form. All it can do is clean up and proceed.

The condition-case construct is often used to trap errors that are predictable, such as failure to open a file in a call to insert-file-contents. It is also used to trap errors that are totally unpredictable, such as when the program evaluates an expression read from the user.

Error signaling and handling have some resemblance to throw and catch, but they are entirely separate facilities. An error cannot be caught by a catch, and a throw cannot be handled by an error handler (though using throw when there is no suitable catch signals an error that can be handled).

Special Form: condition-case var protected-form handlers...
This special form establishes the error handlers handlers around the execution of protected-form. If protected-form executes without error, the value it returns becomes the value of the condition-case form; in this case, the condition-case has no effect. The condition-case form makes a difference when an error occurs during protected-form.

Each of the handlers is a list of the form (conditions body...). Here conditions is an error condition name to be handled, or a list of condition names; body is one or more Lisp expressions to be executed when this handler handles an error. Here are examples of handlers:

(error nil)

(arith-error (message "Division by zero"))

((arith-error file-error)
 (message
  "Either division by zero or failure to open a file"))

Each error that occurs has an error symbol that describes what kind of error it is. The error-conditions property of this symbol is a list of condition names (see section Error Symbols and Condition Names). Emacs searches all the active condition-case forms for a handler that specifies one or more of these condition names; the innermost matching condition-case handles the error. Within this condition-case, the first applicable handler handles the error.

After executing the body of the handler, the condition-case returns normally, using the value of the last form in the handler body as the overall value.

The argument var is a variable. condition-case does not bind this variable when executing the protected-form, only when it handles an error. At that time, it binds var locally to an error description, which is a list giving the particulars of the error. The error description has the form (error-symbol . data). The handler can refer to this list to decide what to do. For example, if the error is for failure opening a file, the file name is the second element of data---the third element of the error description.

If var is nil, that means no variable is bound. Then the error symbol and associated data are not available to the handler.

Function: error-message-string error-description
This function returns the error message string for a given error descriptor. It is useful if you want to handle an error by printing the usual error message for that error.

Here is an example of using condition-case to handle the error that results from dividing by zero. The handler displays the error message (but without a beep), then returns a very large number.

(defun safe-divide (dividend divisor)
  (condition-case err                
      ;; Protected form.
      (/ dividend divisor)              
    ;; The handler.
    (arith-error                        ; Condition.
     ;; Display the usual message for this error.
     (message "%s" (error-message-string err))
     1000000)))
=> safe-divide

(safe-divide 5 0)
     -| Arithmetic error: (arith-error)
=> 1000000

The handler specifies condition name arith-error so that it will handle only division-by-zero errors. Other kinds of errors will not be handled, at least not by this condition-case. Thus,

(safe-divide nil 3)
     error--> Wrong type argument: number-or-marker-p, nil

Here is a condition-case that catches all kinds of errors, including those signaled with error:

(setq baz 34)
     => 34

(condition-case err
    (if (eq baz 35)
        t
      ;; This is a call to the function error.
      (error "Rats!  The variable %s was %s, not 35" 'baz baz))
  ;; This is the handler; it is not a form.
  (error (princ (format "The error was: %s" err)) 
         2))
-| The error was: (error "Rats!  The variable baz was 34, not 35")
=> 2

Error Symbols and Condition Names

When you signal an error, you specify an error symbol to specify the kind of error you have in mind. Each error has one and only one error symbol to categorize it. This is the finest classification of errors defined by the Emacs Lisp language.

These narrow classifications are grouped into a hierarchy of wider classes called error conditions, identified by condition names. The narrowest such classes belong to the error symbols themselves: each error symbol is also a condition name. There are also condition names for more extensive classes, up to the condition name error which takes in all kinds of errors. Thus, each error has one or more condition names: error, the error symbol if that is distinct from error, and perhaps some intermediate classifications.

In order for a symbol to be an error symbol, it must have an error-conditions property which gives a list of condition names. This list defines the conditions that this kind of error belongs to. (The error symbol itself, and the symbol error, should always be members of this list.) Thus, the hierarchy of condition names is defined by the error-conditions properties of the error symbols.

In addition to the error-conditions list, the error symbol should have an error-message property whose value is a string to be printed when that error is signaled but not handled. If the error-message property exists, but is not a string, the error message `peculiar error' is used.

Here is how we define a new error symbol, new-error:

(put 'new-error
     'error-conditions
     '(error my-own-errors new-error))       
=> (error my-own-errors new-error)
(put 'new-error 'error-message "A new error")
=> "A new error"

This error has three condition names: new-error, the narrowest classification; my-own-errors, which we imagine is a wider classification; and error, which is the widest of all.

The error string should start with a capital letter but it should not end with a period. This is for consistency with the rest of Emacs. Naturally, Emacs will never signal new-error on its own; only an explicit call to signal (see section How to Signal an Error) in your code can do this:

(signal 'new-error '(x y))
     error--> A new error: x, y

This error can be handled through any of the three condition names. This example handles new-error and any other errors in the class my-own-errors:

(condition-case foo
    (bar nil t)
  (my-own-errors nil))

The significant way that errors are classified is by their condition names--the names used to match errors with handlers. An error symbol serves only as a convenient way to specify the intended error message and list of condition names. It would be cumbersome to give signal a list of condition names rather than one error symbol.

By contrast, using only error symbols without condition names would seriously decrease the power of condition-case. Condition names make it possible to categorize errors at various levels of generality when you write an error handler. Using error symbols alone would eliminate all but the narrowest level of classification.

See section Standard Errors, for a list of all the standard error symbols and their conditions.

Cleaning Up from Nonlocal Exits

The unwind-protect construct is essential whenever you temporarily put a data structure in an inconsistent state; it permits you to make the data consistent again in the event of an error or throw.

Special Form: unwind-protect body cleanup-forms...
unwind-protect executes the body with a guarantee that the cleanup-forms will be evaluated if control leaves body, no matter how that happens. The body may complete normally, or execute a throw out of the unwind-protect, or cause an error; in all cases, the cleanup-forms will be evaluated.

If the body forms finish normally, unwind-protect returns the value of the last body form, after it evaluates the cleanup-forms. If the body forms do not finish, unwind-protect does not return any value in the normal sense.

Only the body is actually protected by the unwind-protect. If any of the cleanup-forms themselves exits nonlocally (e.g., via a throw or an error), unwind-protect is not guaranteed to evaluate the rest of them. If the failure of one of the cleanup-forms has the potential to cause trouble, then protect it with another unwind-protect around that form.

The number of currently active unwind-protect forms counts, together with the number of local variable bindings, against the limit max-specpdl-size (see section Local Variables).

For example, here we make an invisible buffer for temporary use, and make sure to kill it before finishing:

(save-excursion
  (let ((buffer (get-buffer-create " *temp*")))
    (set-buffer buffer)
    (unwind-protect
        body
      (kill-buffer buffer))))

You might think that we could just as well write (kill-buffer (current-buffer)) and dispense with the variable buffer. However, the way shown above is safer, if body happens to get an error after switching to a different buffer! (Alternatively, you could write another save-excursion around the body, to ensure that the temporary buffer becomes current again in time to kill it.)

Emacs includes a standard macro called with-temp-buffer which expands into more or less the code shown above (see section The Current Buffer). Several of the macros defined in this manual use unwind-protect in this way.

Here is an actual example taken from the file `ftp.el'. It creates a process (see section Processes) to try to establish a connection to a remote machine. As the function ftp-login is highly susceptible to numerous problems that the writer of the function cannot anticipate, it is protected with a form that guarantees deletion of the process in the event of failure. Otherwise, Emacs might fill up with useless subprocesses.

(let ((win nil))
  (unwind-protect
      (progn
        (setq process (ftp-setup-buffer host file))
        (if (setq win (ftp-login process host user password))
            (message "Logged in")
          (error "Ftp login failed")))
    (or win (and process (delete-process process)))))

This example actually has a small bug: if the user types C-g to quit, and the quit happens immediately after the function ftp-setup-buffer returns but before the variable process is set, the process will not be killed. There is no easy way to fix this bug, but at least it is very unlikely.

Variables

A variable is a name used in a program to stand for a value. Nearly all programming languages have variables of some sort. In the text of a Lisp program, variables are written using the syntax for symbols.

In Lisp, unlike most programming languages, programs are represented primarily as Lisp objects and only secondarily as text. The Lisp objects used for variables are symbols: the symbol name is the variable name, and the variable's value is stored in the value cell of the symbol. The use of a symbol as a variable is independent of its use as a function name. See section Symbol Components.

The Lisp objects that constitute a Lisp program determine the textual form of the program--it is simply the read syntax for those Lisp objects. This is why, for example, a variable in a textual Lisp program is written using the read syntax for the symbol that represents the variable.

Global Variables

The simplest way to use a variable is globally. This means that the variable has just one value at a time, and this value is in effect (at least for the moment) throughout the Lisp system. The value remains in effect until you specify a new one. When a new value replaces the old one, no trace of the old value remains in the variable.

You specify a value for a symbol with setq. For example,

(setq x '(a b))

gives the variable x the value (a b). Note that setq does not evaluate its first argument, the name of the variable, but it does evaluate the second argument, the new value.

Once the variable has a value, you can refer to it by using the symbol by itself as an expression. Thus,

x => (a b)

assuming the setq form shown above has already been executed.

If you do set the same variable again, the new value replaces the old one:

x
     => (a b)
(setq x 4)
     => 4
x
     => 4

Variables That Never Change

In Emacs Lisp, certain symbols normally evaluate to themselves. These include nil and t, as well as any symbol whose name starts with `:'. These symbols cannot be rebound, nor can their values be changed. Any attempt to set or bind nil or t signals a setting-constant error. The same is true for a symbol whose name starts with `:', except that you are allowed to set such a symbol to itself.

nil == 'nil
     => nil
(setq nil 500)
error--> Attempt to set constant symbol: nil

Variable: keyword-symbols-constant-flag
If this variable is nil, you are allowed to set and bind symbols whose names start with `:' as you wish. This is to make it possible to run old Lisp programs which do that.

Local Variables

Global variables have values that last until explicitly superseded with new values. Sometimes it is useful to create variable values that exist temporarily--only until a certain part of the program finishes. These values are called local, and the variables so used are called local variables.

For example, when a function is called, its argument variables receive new local values that last until the function exits. The let special form explicitly establishes new local values for specified variables; these last until exit from the let form.

Establishing a local value saves away the previous value (or lack of one) of the variable. When the life span of the local value is over, the previous value is restored. In the mean time, we say that the previous value is shadowed and not visible. Both global and local values may be shadowed (see section Scope).

If you set a variable (such as with setq) while it is local, this replaces the local value; it does not alter the global value, or previous local values, that are shadowed. To model this behavior, we speak of a local binding of the variable as well as a local value.

The local binding is a conceptual place that holds a local value. Entry to a function, or a special form such as let, creates the local binding; exit from the function or from the let removes the local binding. As long as the local binding lasts, the variable's value is stored within it. Use of setq or set while there is a local binding stores a different value into the local binding; it does not create a new binding.

We also speak of the global binding, which is where (conceptually) the global value is kept.

A variable can have more than one local binding at a time (for example, if there are nested let forms that bind it). In such a case, the most recently created local binding that still exists is the current binding of the variable. (This rule is called dynamic scoping; see section Scoping Rules for Variable Bindings.) If there are no local bindings, the variable's global binding is its current binding. We sometimes call the current binding the most-local existing binding, for emphasis. Ordinary evaluation of a symbol always returns the value of its current binding.

The special forms let and let* exist to create local bindings.

Special Form: let (bindings...) forms...
This special form binds variables according to bindings and then evaluates all of the forms in textual order. The let-form returns the value of the last form in forms.

Each of the bindings is either (i) a symbol, in which case that symbol is bound to nil; or (ii) a list of the form (symbol value-form), in which case symbol is bound to the result of evaluating value-form. If value-form is omitted, nil is used.

All of the value-forms in bindings are evaluated in the order they appear and before binding any of the symbols to them. Here is an example of this: Z is bound to the old value of Y, which is 2, not the new value of Y, which is 1.

(setq Y 2)
     => 2
(let ((Y 1) 
      (Z Y))
  (list Y Z))
     => (1 2)

Special Form: let* (bindings...) forms...
This special form is like let, but it binds each variable right after computing its local value, before computing the local value for the next variable. Therefore, an expression in bindings can reasonably refer to the preceding symbols bound in this let* form. Compare the following example with the example above for let.

(setq Y 2)
     => 2
(let* ((Y 1)
       (Z Y))    ; Use the just-established value of Y.
  (list Y Z))
     => (1 1)

Here is a complete list of the other facilities that create local bindings:

Variables can also have buffer-local bindings (see section Buffer-Local Variables) and frame-local bindings (see section Frame-Local Variables); a few variables have terminal-local bindings (see section Multiple Displays). These kinds of bindings work somewhat like ordinary local bindings, but they are localized depending on "where" you are in Emacs, rather than localized in time.

Variable: max-specpdl-size
This variable defines the limit on the total number of local variable bindings and unwind-protect cleanups (see section Nonlocal Exits) that are allowed before signaling an error (with data "Variable binding depth exceeds max-specpdl-size").

This limit, with the associated error when it is exceeded, is one way that Lisp avoids infinite recursion on an ill-defined function. max-lisp-eval-depth provides another limit on depth of nesting. See section Eval.

The default value is 600. Entry to the Lisp debugger increases the value, if there is little room left, to make sure the debugger itself has room to execute.

When a Variable is "Void"

If you have never given a symbol any value as a global variable, we say that that symbol's global value is void. In other words, the symbol's value cell does not have any Lisp object in it. If you try to evaluate the symbol, you get a void-variable error rather than a value.

Note that a value of nil is not the same as void. The symbol nil is a Lisp object and can be the value of a variable just as any other object can be; but it is a value. A void variable does not have any value.

After you have given a variable a value, you can make it void once more using makunbound.

Function: makunbound symbol
This function makes the current variable binding of symbol void. Subsequent attempts to use this symbol's value as a variable will signal the error void-variable, unless and until you set it again.

makunbound returns symbol.

(makunbound 'x)      ; Make the global value of x void.
     => x
x
error--> Symbol's value as variable is void: x

If symbol is locally bound, makunbound affects the most local existing binding. This is the only way a symbol can have a void local binding, since all the constructs that create local bindings create them with values. In this case, the voidness lasts at most as long as the binding does; when the binding is removed due to exit from the construct that made it, the previous local or global binding is reexposed as usual, and the variable is no longer void unless the newly reexposed binding was void all along.

(setq x 1)               ; Put a value in the global binding.
     => 1
(let ((x 2))             ; Locally bind it.
  (makunbound 'x)        ; Void the local binding.
  x)
error--> Symbol's value as variable is void: x
x                        ; The global binding is unchanged.
     => 1

(let ((x 2))             ; Locally bind it.
  (let ((x 3))           ; And again.
    (makunbound 'x)      ; Void the innermost-local binding.
    x))                  ; And refer: it's void.
error--> Symbol's value as variable is void: x

(let ((x 2))
  (let ((x 3))
    (makunbound 'x))     ; Void inner binding, then remove it.
  x)                     ; Now outer let binding is visible.
     => 2

A variable that has been made void with makunbound is indistinguishable from one that has never received a value and has always been void.

You can use the function boundp to test whether a variable is currently void.

Function: boundp variable
boundp returns t if variable (a symbol) is not void; more precisely, if its current binding is not void. It returns nil otherwise.

(boundp 'abracadabra)          ; Starts out void.
     => nil
(let ((abracadabra 5))         ; Locally bind it.
  (boundp 'abracadabra))
     => t
(boundp 'abracadabra)          ; Still globally void.
     => nil
(setq abracadabra 5)           ; Make it globally nonvoid.
     => 5
(boundp 'abracadabra)
     => t

Defining Global Variables

You may announce your intention to use a symbol as a global variable with a variable definition: a special form, either defconst or defvar.

In Emacs Lisp, definitions serve three purposes. First, they inform people who read the code that certain symbols are intended to be used a certain way (as variables). Second, they inform the Lisp system of these things, supplying a value and documentation. Third, they provide information to utilities such as etags and make-docfile, which create data bases of the functions and variables in a program.

The difference between defconst and defvar is primarily a matter of intent, serving to inform human readers of whether the value should ever change. Emacs Lisp does not restrict the ways in which a variable can be used based on defconst or defvar declarations. However, it does make a difference for initialization: defconst unconditionally initializes the variable, while defvar initializes it only if it is void.

Special Form: defvar symbol [value [doc-string]]
This special form defines symbol as a variable and can also initialize and document it. The definition informs a person reading your code that symbol is used as a variable that might be set or changed. Note that symbol is not evaluated; the symbol to be defined must appear explicitly in the defvar.

If symbol is void and value is specified, defvar evaluates it and sets symbol to the result. But if symbol already has a value (i.e., it is not void), value is not even evaluated, and symbol's value remains unchanged. If value is omitted, the value of symbol is not changed in any case.

If symbol has a buffer-local binding in the current buffer, defvar operates on the default value, which is buffer-independent, not the current (buffer-local) binding. It sets the default value if the default value is void. See section Buffer-Local Variables.

When you evaluate a top-level defvar form with C-M-x in Emacs Lisp mode (eval-defun), a special feature of eval-defun arranges to set the variable unconditionally, without testing whether its value is void.

If the doc-string argument appears, it specifies the documentation for the variable. (This opportunity to specify documentation is one of the main benefits of defining the variable.) The documentation is stored in the symbol's variable-documentation property. The Emacs help functions (see section Documentation) look for this property.

If the first character of doc-string is `*', it means that this variable is considered a user option. This lets users set the variable conveniently using the commands set-variable and edit-options. However, it is better to use defcustom instead of defvar for user option variables, so you can specify customization information. See section Writing Customization Definitions.

Here are some examples. This form defines foo but does not initialize it:

(defvar foo)
     => foo

This example initializes the value of bar to 23, and gives it a documentation string:

(defvar bar 23
  "The normal weight of a bar.")
     => bar

The following form changes the documentation string for bar, making it a user option, but does not change the value, since bar already has a value. (The addition (1+ nil) would get an error if it were evaluated, but since it is not evaluated, there is no error.)

(defvar bar (1+ nil)
  "*The normal weight of a bar.")
     => bar
bar
     => 23

Here is an equivalent expression for the defvar special form:

(defvar symbol value doc-string)
==
(progn
  (if (not (boundp 'symbol))
      (setq symbol value))
  (if 'doc-string
    (put 'symbol 'variable-documentation 'doc-string))
  'symbol)

The defvar form returns symbol, but it is normally used at top level in a file where its value does not matter.

Special Form: defconst symbol [value [doc-string]]
This special form defines symbol as a value and initializes it. It informs a person reading your code that symbol has a standard global value, established here, that should not be changed by the user or by other programs. Note that symbol is not evaluated; the symbol to be defined must appear explicitly in the defconst.

defconst always evaluates value, and sets the value of symbol to the result if value is given. If symbol does have a buffer-local binding in the current buffer, defconst sets the default value, not the buffer-local value. (But you should not be making buffer-local bindings for a symbol that is defined with defconst.)

Here, pi is a constant that presumably ought not to be changed by anyone (attempts by the Indiana State Legislature notwithstanding). As the second form illustrates, however, this is only advisory.

(defconst pi 3.1415 "Pi to five places.")
     => pi
(setq pi 3)
     => pi
pi
     => 3

Function: user-variable-p variable
This function returns t if variable is a user option--a variable intended to be set by the user for customization--and nil otherwise. (Variables other than user options exist for the internal purposes of Lisp programs, and users need not know about them.)

User option variables are distinguished from other variables by the first character of the variable-documentation property. If the property exists and is a string, and its first character is `*', then the variable is a user option.

If a user option variable has a variable-interactive property, the set-variable command uses that value to control reading the new value for the variable. The property's value is used as if it were to interactive (see section Using interactive). However, this feature is largely obsoleted by defcustom (see section Writing Customization Definitions).

Warning: If the defconst and defvar special forms are used while the variable has a local binding, they set the local binding's value; the global binding is not changed. This is not what we really want. To prevent it, use these special forms at top level in a file, where normally no local binding is in effect, and make sure to load the file before making a local binding for the variable.

Tips for Defining Variables Robustly

When defining and initializing a variable that holds a complicated value (such as a keymap with bindings in it), it's best to put the entire computation of the value into the defvar, like this:

(defvar my-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\C-c\C-a" 'my-command)
    ...
    map)
  docstring)

This method has several benefits. First, if the user quits while loading the file, the variable is either still uninitialized or initialized properly, never in-between. If it is still uninitialized, reloading the file will initialize it properly. Second, reloading the file once the variable is initialized will not alter it; that is important if the user has run hooks to alter part of the contents (such as, to rebind keys). Third, evaluating the defvar form with C-M-x will reinitialize the map completely.

Putting so much code in the defvar form has one disadvantage: it puts the documentation string far away from the line which names the variable. Here's a safe way to avoid that:

(defvar my-mode-map nil
  docstring)
(if my-mode-map
    nil
  (let ((map (make-sparse-keymap)))
    (define-key my-mode-map "\C-c\C-a" 'my-command)
    ...
    (setq my-mode-map map)))

This has all the same advantages as putting the initialization inside the defvar, except that you must type C-M-x twice, once on each form, if you do want to reinitialize the variable.

But be careful not to write the code like this:

(defvar my-mode-map nil
  docstring)
(if my-mode-map
    nil
  (setq my-mode-map (make-sparse-keymap))
  (define-key my-mode-map "\C-c\C-a" 'my-command)
  ...)

This code sets the variable, then alters it, but it does so in more than one step. If the user quits just after the setq, that leaves the variable neither correctly initialized nor void nor nil. Once that happens, reloading the file will not initialize the variable; it will remain incomplete.

Accessing Variable Values

The usual way to reference a variable is to write the symbol which names it (see section Symbol Forms). This requires you to specify the variable name when you write the program. Usually that is exactly what you want to do. Occasionally you need to choose at run time which variable to reference; then you can use symbol-value.

Function: symbol-value symbol
This function returns the value of symbol. This is the value in the innermost local binding of the symbol, or its global value if it has no local bindings.

(setq abracadabra 5)
     => 5
(setq foo 9)
     => 9

;; Here the symbol abracadabra
;;   is the symbol whose value is examined.
(let ((abracadabra 'foo))
  (symbol-value 'abracadabra))
     => foo

;; Here the value of abracadabra,
;;   which is foo,
;;   is the symbol whose value is examined.
(let ((abracadabra 'foo))
  (symbol-value abracadabra))
     => 9

(symbol-value 'abracadabra)
     => 5

A void-variable error is signaled if the current binding of symbol is void.

How to Alter a Variable Value

The usual way to change the value of a variable is with the special form setq. When you need to compute the choice of variable at run time, use the function set.

Special Form: setq [symbol form]...
This special form is the most common method of changing a variable's value. Each symbol is given a new value, which is the result of evaluating the corresponding form. The most-local existing binding of the symbol is changed.

setq does not evaluate symbol; it sets the symbol that you write. We say that this argument is automatically quoted. The `q' in setq stands for "quoted."

The value of the setq form is the value of the last form.

(setq x (1+ 2))
     => 3
x                   ; x now has a global value.
     => 3
(let ((x 5)) 
  (setq x 6)        ; The local binding of x is set.
  x)
     => 6
x                   ; The global value is unchanged.
     => 3

Note that the first form is evaluated, then the first symbol is set, then the second form is evaluated, then the second symbol is set, and so on:

(setq x 10          ; Notice that x is set before
      y (1+ x))     ;   the value of y is computed.
     => 11             

Function: set symbol value
This function sets symbol's value to value, then returns value. Since set is a function, the expression written for symbol is evaluated to obtain the symbol to set.

The most-local existing binding of the variable is the binding that is set; shadowed bindings are not affected.

(set one 1)
error--> Symbol's value as variable is void: one
(set 'one 1)
     => 1
(set 'two 'one)
     => one
(set two 2)         ; two evaluates to symbol one.
     => 2
one                 ; So it is one that was set.
     => 2
(let ((one 1))      ; This binding of one is set,
  (set 'one 3)      ;   not the global value.
  one)
     => 3
one
     => 2

If symbol is not actually a symbol, a wrong-type-argument error is signaled.

(set '(x y) 'z)
error--> Wrong type argument: symbolp, (x y)

Logically speaking, set is a more fundamental primitive than setq. Any use of setq can be trivially rewritten to use set; setq could even be defined as a macro, given the availability of set. However, set itself is rarely used; beginners hardly need to know about it. It is useful only for choosing at run time which variable to set. For example, the command set-variable, which reads a variable name from the user and then sets the variable, needs to use set.

Common Lisp note: In Common Lisp, set always changes the symbol's "special" or dynamic value, ignoring any lexical bindings. In Emacs Lisp, all variables and all bindings are dynamic, so set always affects the most local existing binding.

One other function for setting a variable is designed to add an element to a list if it is not already present in the list.

Function: add-to-list symbol element
This function sets the variable symbol by consing element onto the old value, if element is not already a member of that value. It returns the resulting list, whether updated or not. The value of symbol had better be a list already before the call.

The argument symbol is not implicitly quoted; add-to-list is an ordinary function, like set and unlike setq. Quote the argument yourself if that is what you want.

Here's a scenario showing how to use add-to-list:

(setq foo '(a b))
     => (a b)

(add-to-list 'foo 'c)     ;; Add c.
     => (c a b)

(add-to-list 'foo 'b)     ;; No effect.
     => (c a b)

foo                       ;; foo was changed.
     => (c a b)

An equivalent expression for (add-to-list 'var value) is this:

(or (member value var)
    (setq var (cons value var)))

Scoping Rules for Variable Bindings

A given symbol foo can have several local variable bindings, established at different places in the Lisp program, as well as a global binding. The most recently established binding takes precedence over the others.

Local bindings in Emacs Lisp have indefinite scope and dynamic extent. Scope refers to where textually in the source code the binding can be accessed. Indefinite scope means that any part of the program can potentially access the variable binding. Extent refers to when, as the program is executing, the binding exists. Dynamic extent means that the binding lasts as long as the activation of the construct that established it.

The combination of dynamic extent and indefinite scope is called dynamic scoping. By contrast, most programming languages use lexical scoping, in which references to a local variable must be located textually within the function or block that binds the variable.

Common Lisp note: Variables declared "special" in Common Lisp are dynamically scoped, like all variables in Emacs Lisp.

Scope

Emacs Lisp uses indefinite scope for local variable bindings. This means that any function anywhere in the program text might access a given binding of a variable. Consider the following function definitions:

(defun binder (x)   ; x is bound in binder.
   (foo 5))         ; foo is some other function.

(defun user ()      ; x is used ``free'' in user.
  (list x))

In a lexically scoped language, the binding of x in binder would never be accessible in user, because user is not textually contained within the function binder. However, in dynamically scoped Emacs Lisp, user may or may not refer to the binding of x established in binder, depending on circumstances:

Emacs Lisp uses dynamic scoping because simple implementations of lexical scoping are slow. In addition, every Lisp system needs to offer dynamic scoping at least as an option; if lexical scoping is the norm, there must be a way to specify dynamic scoping instead for a particular variable. It might not be a bad thing for Emacs to offer both, but implementing it with dynamic scoping only was much easier.

Extent

Extent refers to the time during program execution that a variable name is valid. In Emacs Lisp, a variable is valid only while the form that bound it is executing. This is called dynamic extent. "Local" or "automatic" variables in most languages, including C and Pascal, have dynamic extent.

One alternative to dynamic extent is indefinite extent. This means that a variable binding can live on past the exit from the form that made the binding. Common Lisp and Scheme, for example, support this, but Emacs Lisp does not.

To illustrate this, the function below, make-add, returns a function that purports to add n to its own argument m. This would work in Common Lisp, but it does not do the job in Emacs Lisp, because after the call to make-add exits, the variable n is no longer bound to the actual argument 2.

(defun make-add (n)
    (function (lambda (m) (+ n m))))  ; Return a function.
     => make-add
(fset 'add2 (make-add 2))  ; Define function add2
                           ;   with (make-add 2).
     => (lambda (m) (+ n m))
(add2 4)                   ; Try to add 2 to 4.
error--> Symbol's value as variable is void: n

Some Lisp dialects have "closures", objects that are like functions but record additional variable bindings. Emacs Lisp does not have closures.

Implementation of Dynamic Scoping

A simple sample implementation (which is not how Emacs Lisp actually works) may help you understand dynamic binding. This technique is called deep binding and was used in early Lisp systems.

Suppose there is a stack of bindings, which are variable-value pairs. At entry to a function or to a let form, we can push bindings onto the stack for the arguments or local variables created there. We can pop those bindings from the stack at exit from the binding construct.

We can find the value of a variable by searching the stack from top to bottom for a binding for that variable; the value from that binding is the value of the variable. To set the variable, we search for the current binding, then store the new value into that binding.

As you can see, a function's bindings remain in effect as long as it continues execution, even during its calls to other functions. That is why we say the extent of the binding is dynamic. And any other function can refer to the bindings, if it uses the same variables while the bindings are in effect. That is why we say the scope is indefinite.

The actual implementation of variable scoping in GNU Emacs Lisp uses a technique called shallow binding. Each variable has a standard place in which its current value is always found--the value cell of the symbol.

In shallow binding, setting the variable works by storing a value in the value cell. Creating a new binding works by pushing the old value (belonging to a previous binding) onto a stack, and storing the new local value in the value cell. Eliminating a binding works by popping the old value off the stack, into the value cell.

We use shallow binding because it has the same results as deep binding, but runs faster, since there is never a need to search for a binding.

Proper Use of Dynamic Scoping

Binding a variable in one function and using it in another is a powerful technique, but if used without restraint, it can make programs hard to understand. There are two clean ways to use this technique:

In either case, you should define the variable with defvar. This helps other people understand your program by telling them to look for inter-function usage. It also avoids a warning from the byte compiler. Choose the variable's name to avoid name conflicts--don't use short names like x.

Buffer-Local Variables

Global and local variable bindings are found in most programming languages in one form or another. Emacs also supports additional, unusual kinds of variable binding: buffer-local bindings, which apply only in one buffer, and frame-local bindings, which apply only in one frame. Having different values for a variable in different buffers and/or frames is an important customization method.

This section describes buffer-local bindings; for frame-local bindings, see the following section, section Frame-Local Variables. (A few variables have bindings that are local to each terminal; see section Multiple Displays.)

Introduction to Buffer-Local Variables

A buffer-local variable has a buffer-local binding associated with a particular buffer. The binding is in effect when that buffer is current; otherwise, it is not in effect. If you set the variable while a buffer-local binding is in effect, the new value goes in that binding, so its other bindings are unchanged. This means that the change is visible only in the buffer where you made it.

The variable's ordinary binding, which is not associated with any specific buffer, is called the default binding. In most cases, this is the global binding.

A variable can have buffer-local bindings in some buffers but not in other buffers. The default binding is shared by all the buffers that don't have their own bindings for the variable. (This includes all newly created buffers.) If you set the variable in a buffer that does not have a buffer-local binding for it, this sets the default binding (assuming there are no frame-local bindings to complicate the matter), so the new value is visible in all the buffers that see the default binding.

The most common use of buffer-local bindings is for major modes to change variables that control the behavior of commands. For example, C mode and Lisp mode both set the variable paragraph-start to specify that only blank lines separate paragraphs. They do this by making the variable buffer-local in the buffer that is being put into C mode or Lisp mode, and then setting it to the new value for that mode. See section Major Modes.

The usual way to make a buffer-local binding is with make-local-variable, which is what major mode commands typically use. This affects just the current buffer; all other buffers (including those yet to be created) will continue to share the default value unless they are explicitly given their own buffer-local bindings.

A more powerful operation is to mark the variable as automatically buffer-local by calling make-variable-buffer-local. You can think of this as making the variable local in all buffers, even those yet to be created. More precisely, the effect is that setting the variable automatically makes the variable local to the current buffer if it is not already so. All buffers start out by sharing the default value of the variable as usual, but setting the variable creates a buffer-local binding for the current buffer. The new value is stored in the buffer-local binding, leaving the default binding untouched. This means that the default value cannot be changed with setq in any buffer; the only way to change it is with setq-default.

Warning: When a variable has buffer-local values in one or more buffers, you can get Emacs very confused by binding the variable with let, changing to a different current buffer in which a different binding is in effect, and then exiting the let. This can scramble the values of the buffer-local and default bindings.

To preserve your sanity, avoid using a variable in that way. If you use save-excursion around each piece of code that changes to a different current buffer, you will not have this problem (see section Excursions). Here is an example of what to avoid:

(setq foo 'b)
(set-buffer "a")
(make-local-variable 'foo)
(setq foo 'a)
(let ((foo 'temp))
  (set-buffer "b")
  body...)
foo => 'a      ; The old buffer-local value from buffer `a'
               ;   is now the default value.
(set-buffer "a")
foo => 'temp   ; The local let value that should be gone
               ;   is now the buffer-local value in buffer `a'.

But save-excursion as shown here avoids the problem:

(let ((foo 'temp))
  (save-excursion
    (set-buffer "b")
    body...))

Note that references to foo in body access the buffer-local binding of buffer `b'.

When a file specifies local variable values, these become buffer-local values when you visit the file. See section `File Variables' in The GNU Emacs Manual.

Creating and Deleting Buffer-Local Bindings

Command: make-local-variable variable
This function creates a buffer-local binding in the current buffer for variable (a symbol). Other buffers are not affected. The value returned is variable.

The buffer-local value of variable starts out as the same value variable previously had. If variable was void, it remains void.

;; In buffer `b1':
(setq foo 5)                ; Affects all buffers.
     => 5
(make-local-variable 'foo)  ; Now it is local in `b1'.
     => foo
foo                         ; That did not change
     => 5                   ;   the value.
(setq foo 6)                ; Change the value
     => 6                   ;   in `b1'.
foo
     => 6

;; In buffer `b2', the value hasn't changed.
(save-excursion
  (set-buffer "b2")
  foo)
     => 5

Making a variable buffer-local within a let-binding for that variable does not work reliably, unless the buffer in which you do this is not current either on entry to or exit from the let. This is because let does not distinguish between different kinds of bindings; it knows only which variable the binding was made for.

If the variable is terminal-local, this function signals an error. Such variables cannot have buffer-local bindings as well. See section Multiple Displays.

Note: do not use make-local-variable for a hook variable. Instead, use make-local-hook. See section Hooks.

Command: make-variable-buffer-local variable
This function marks variable (a symbol) automatically buffer-local, so that any subsequent attempt to set it will make it local to the current buffer at the time.

A peculiar wrinkle of this feature is that binding the variable (with let or other binding constructs) does not create a buffer-local binding for it. Only setting the variable (with set or setq) does so.

The value returned is variable.

Warning: Don't assume that you should use make-variable-buffer-local for user-option variables, simply because users might want to customize them differently in different buffers. Users can make any variable local, when they wish to. It is better to leave the choice to them.

The time to use make-variable-buffer-local is when it is crucial that no two buffers ever share the same binding. For example, when a variable is used for internal purposes in a Lisp program which depends on having separate values in separate buffers, then using make-variable-buffer-local can be the best solution.

Function: local-variable-p variable &optional buffer
This returns t if variable is buffer-local in buffer buffer (which defaults to the current buffer); otherwise, nil.

Function: buffer-local-variables &optional buffer
This function returns a list describing the buffer-local variables in buffer buffer. (If buffer is omitted, the current buffer is used.) It returns an association list (see section Association Lists) in which each element contains one buffer-local variable and its value. However, when a variable's buffer-local binding in buffer is void, then the variable appears directly in the resulting list.

(make-local-variable 'foobar)
(makunbound 'foobar)
(make-local-variable 'bind-me)
(setq bind-me 69)
(setq lcl (buffer-local-variables))
    ;; First, built-in variables local in all buffers:
=> ((mark-active . nil)
    (buffer-undo-list . nil)
    (mode-name . "Fundamental")
    ...
    ;; Next, non-built-in buffer-local variables. 
    ;; This one is buffer-local and void:
    foobar
    ;; This one is buffer-local and nonvoid:
    (bind-me . 69))

Note that storing new values into the CDRs of cons cells in this list does not change the buffer-local values of the variables.

Command: kill-local-variable variable
This function deletes the buffer-local binding (if any) for variable (a symbol) in the current buffer. As a result, the default binding of variable becomes visible in this buffer. This typically results in a change in the value of variable, since the default value is usually different from the buffer-local value just eliminated.

If you kill the buffer-local binding of a variable that automatically becomes buffer-local when set, this makes the default value visible in the current buffer. However, if you set the variable again, that will once again create a buffer-local binding for it.

kill-local-variable returns variable.

This function is a command because it is sometimes useful to kill one buffer-local variable interactively, just as it is useful to create buffer-local variables interactively.

Function: kill-all-local-variables
This function eliminates all the buffer-local variable bindings of the current buffer except for variables marked as "permanent". As a result, the buffer will see the default values of most variables.

This function also resets certain other information pertaining to the buffer: it sets the local keymap to nil, the syntax table to the value of (standard-syntax-table), the case table to (standard-case-table), and the abbrev table to the value of fundamental-mode-abbrev-table.

The very first thing this function does is run the normal hook change-major-mode-hook (see below).

Every major mode command begins by calling this function, which has the effect of switching to Fundamental mode and erasing most of the effects of the previous major mode. To ensure that this does its job, the variables that major modes set should not be marked permanent.

kill-all-local-variables returns nil.

Variable: change-major-mode-hook
The function kill-all-local-variables runs this normal hook before it does anything else. This gives major modes a way to arrange for something special to be done if the user switches to a different major mode. For best results, make this variable buffer-local, so that it will disappear after doing its job and will not interfere with the subsequent major mode. See section Hooks.

A buffer-local variable is permanent if the variable name (a symbol) has a permanent-local property that is non-nil. Permanent locals are appropriate for data pertaining to where the file came from or how to save it, rather than with how to edit the contents.

The Default Value of a Buffer-Local Variable

The global value of a variable with buffer-local bindings is also called the default value, because it is the value that is in effect whenever neither the current buffer nor the selected frame has its own binding for the variable.

The functions default-value and setq-default access and change a variable's default value regardless of whether the current buffer has a buffer-local binding. For example, you could use setq-default to change the default setting of paragraph-start for most buffers; and this would work even when you are in a C or Lisp mode buffer that has a buffer-local value for this variable.

The special forms defvar and defconst also set the default value (if they set the variable at all), rather than any buffer-local or frame-local value.

Function: default-value symbol
This function returns symbol's default value. This is the value that is seen in buffers and frames that do not have their own values for this variable. If symbol is not buffer-local, this is equivalent to symbol-value (see section Accessing Variable Values).

Function: default-boundp symbol
The function default-boundp tells you whether symbol's default value is nonvoid. If (default-boundp 'foo) returns nil, then (default-value 'foo) would get an error.

default-boundp is to default-value as boundp is to symbol-value.

Special Form: setq-default [symbol form]...
This special form gives each symbol a new default value, which is the result of evaluating the corresponding form. It does not evaluate symbol, but does evaluate form. The value of the setq-default form is the value of the last form.

If a symbol is not buffer-local for the current buffer, and is not marked automatically buffer-local, setq-default has the same effect as setq. If symbol is buffer-local for the current buffer, then this changes the value that other buffers will see (as long as they don't have a buffer-local value), but not the value that the current buffer sees.

;; In buffer `foo':
(make-local-variable 'buffer-local)
     => buffer-local
(setq buffer-local 'value-in-foo)
     => value-in-foo
(setq-default buffer-local 'new-default)
     => new-default
buffer-local
     => value-in-foo
(default-value 'buffer-local)
     => new-default

;; In (the new) buffer `bar':
buffer-local
     => new-default
(default-value 'buffer-local)
     => new-default
(setq buffer-local 'another-default)
     => another-default
(default-value 'buffer-local)
     => another-default

;; Back in buffer `foo':
buffer-local
     => value-in-foo
(default-value 'buffer-local)
     => another-default

Function: set-default symbol value
This function is like setq-default, except that symbol is an ordinary evaluated argument.

(set-default (car '(a b c)) 23)
     => 23
(default-value 'a)
     => 23

Frame-Local Variables

Just as variables can have buffer-local bindings, they can also have frame-local bindings. These bindings belong to one frame, and are in effect when that frame is selected. Frame-local bindings are actually frame parameters: you create a frame-local binding in a specific frame by calling modify-frame-parameters and specifying the variable name as the parameter name.

To enable frame-local bindings for a certain variable, call the function make-variable-frame-local.

Command: make-variable-frame-local variable
Enable the use of frame-local bindings for variable. This does not in itself create any frame-local bindings for the variable; however, if some frame already has a value for variable as a frame parameter, that value automatically becomes a frame-local binding.

If the variable is terminal-local, this function signals an error, because such variables cannot have frame-local bindings as well. See section Multiple Displays. A few variables that are implemented specially in Emacs can be (and usually are) buffer-local, but can never be frame-local.

Buffer-local bindings take precedence over frame-local bindings. Thus, consider a variable foo: if the current buffer has a buffer-local binding for foo, that binding is active; otherwise, if the selected frame has a frame-local binding for foo, that binding is active; otherwise, the default binding of foo is active.

Here is an example. First we prepare a few bindings for foo:

(setq f1 (selected-frame))
(make-variable-frame-local 'foo)

;; Make a buffer-local binding for foo in `b1'.
(set-buffer (get-buffer-create "b1"))
(make-local-variable 'foo)
(setq foo '(b 1))

;; Make a frame-local binding for foo in a new frame.
;; Store that frame in f2.
(setq f2 (make-frame))
(modify-frame-parameters f2 '((foo . (f 2))))

Now we examine foo in various contexts. Whenever the buffer `b1' is current, its buffer-local binding is in effect, regardless of the selected frame:

(select-frame f1)
(set-buffer (get-buffer-create "b1"))
foo
     => (b 1)

(select-frame f2)
(set-buffer (get-buffer-create "b1"))
foo
     => (b 1)

Otherwise, the frame gets a chance to provide the binding; when frame f2 is selected, its frame-local binding is in effect:

(select-frame f2)
(set-buffer (get-buffer "*scratch*"))
foo
     => (f 2)

When neither the current buffer nor the selected frame provides a binding, the default binding is used:

(select-frame f1)
(set-buffer (get-buffer "*scratch*"))
foo
     => nil

When the active binding of a variable is a frame-local binding, setting the variable changes that binding. You can observe the result with frame-parameters:

(select-frame f2)
(set-buffer (get-buffer "*scratch*"))
(setq foo 'nobody)
(assq 'foo (frame-parameters f2))
     => (foo . nobody)

Possible Future Local Variables

We have considered the idea of bindings that are local to a category of frames--for example, all color frames, or all frames with dark backgrounds. We have not implemented them because it is not clear that this feature is really useful. You can get more or less the same results by adding a function to after-make-frame-hook, set up to define a particular frame parameter according to the appropriate conditions for each frame.

It would also be possible to implement window-local bindings. We don't know of many situations where they would be useful, and it seems that indirect buffers (see section Indirect Buffers) with buffer-local bindings offer a way to handle these situations more robustly.

If sufficient application is found for either of these two kinds of local bindings, we will provide it in a subsequent Emacs version.

Functions

A Lisp program is composed mainly of Lisp functions. This chapter explains what functions are, how they accept arguments, and how to define them.

What Is a Function?

In a general sense, a function is a rule for carrying on a computation given several values called arguments. The result of the computation is called the value of the function. The computation can also have side effects: lasting changes in the values of variables or the contents of data structures.

Here are important terms for functions in Emacs Lisp and for other function-like objects.

function
In Emacs Lisp, a function is anything that can be applied to arguments in a Lisp program. In some cases, we use it more specifically to mean a function written in Lisp. Special forms and macros are not functions.
primitive
A primitive is a function callable from Lisp that is written in C, such as car or append. These functions are also called built-in functions or subrs. (Special forms are also considered primitives.) Usually the reason we implement a function as a primitive is either because it is fundamental, because it provides a low-level interface to operating system services, or because it needs to run fast. Primitives can be modified or added only by changing the C sources and recompiling the editor. See section Writing Emacs Primitives.
lambda expression
A lambda expression is a function written in Lisp. These are described in the following section.
special form
A special form is a primitive that is like a function but does not evaluate all of its arguments in the usual way. It may evaluate only some of the arguments, or may evaluate them in an unusual order, or several times. Many special forms are described in section Control Structures.
macro
A macro is a construct defined in Lisp by the programmer. It differs from a function in that it translates a Lisp expression that you write into an equivalent expression to be evaluated instead of the original expression. Macros enable Lisp programmers to do the sorts of things that special forms can do. See section Macros, for how to define and use macros.
command
A command is an object that command-execute can invoke; it is a possible definition for a key sequence. Some functions are commands; a function written in Lisp is a command if it contains an interactive declaration (see section Defining Commands). Such a function can be called from Lisp expressions like other functions; in this case, the fact that the function is a command makes no difference. Keyboard macros (strings and vectors) are commands also, even though they are not functions. A symbol is a command if its function definition is a command; such symbols can be invoked with M-x. The symbol is a function as well if the definition is a function. See section Command Loop Overview.
keystroke command
A keystroke command is a command that is bound to a key sequence (typically one to three keystrokes). The distinction is made here merely to avoid confusion with the meaning of "command" in non-Emacs editors; for Lisp programs, the distinction is normally unimportant.
byte-code function
A byte-code function is a function that has been compiled by the byte compiler. See section Byte-Code Function Type.

Function: functionp object
This function returns t if object is any kind of function, or a special form or macro.

Function: subrp object
This function returns t if object is a built-in function (i.e., a Lisp primitive).

(subrp 'message)            ; message is a symbol,
     => nil                 ;   not a subr object.
(subrp (symbol-function 'message))
     => t

Function: byte-code-function-p object
This function returns t if object is a byte-code function. For example:

(byte-code-function-p (symbol-function 'next-line))
     => t

Lambda Expressions

A function written in Lisp is a list that looks like this:

(lambda (arg-variables...)
  [documentation-string]
  [interactive-declaration]
  body-forms...)

Such a list is called a lambda expression. In Emacs Lisp, it actually is valid as an expression--it evaluates to itself. In some other Lisp dialects, a lambda expression is not a valid expression at all. In either case, its main use is not to be evaluated as an expression, but to be called as a function.

Components of a Lambda Expression

The first element of a lambda expression is always the symbol lambda. This indicates that the list represents a function. The reason functions are defined to start with lambda is so that other lists, intended for other uses, will not accidentally be valid as functions.

The second element is a list of symbols--the argument variable names. This is called the lambda list. When a Lisp function is called, the argument values are matched up against the variables in the lambda list, which are given local bindings with the values provided. See section Local Variables.

The documentation string is a Lisp string object placed within the function definition to describe the function for the Emacs help facilities. See section Documentation Strings of Functions.

The interactive declaration is a list of the form (interactive code-string). This declares how to provide arguments if the function is used interactively. Functions with this declaration are called commands; they can be called using M-x or bound to a key. Functions not intended to be called in this way should not have interactive declarations. See section Defining Commands, for how to write an interactive declaration.

The rest of the elements are the body of the function: the Lisp code to do the work of the function (or, as a Lisp programmer would say, "a list of Lisp forms to evaluate"). The value returned by the function is the value returned by the last element of the body.

A Simple Lambda-Expression Example

Consider for example the following function:

(lambda (a b c) (+ a b c))

We can call this function by writing it as the CAR of an expression, like this:

((lambda (a b c) (+ a b c))
 1 2 3)

This call evaluates the body of the lambda expression with the variable a bound to 1, b bound to 2, and c bound to 3. Evaluation of the body adds these three numbers, producing the result 6; therefore, this call to the function returns the value 6.

Note that the arguments can be the results of other function calls, as in this example:

((lambda (a b c) (+ a b c))
 1 (* 2 3) (- 5 4))

This evaluates the arguments 1, (* 2 3), and (- 5 4) from left to right. Then it applies the lambda expression to the argument values 1, 6 and 1 to produce the value 8.

It is not often useful to write a lambda expression as the CAR of a form in this way. You can get the same result, of making local variables and giving them values, using the special form let (see section Local Variables). And let is clearer and easier to use. In practice, lambda expressions are either stored as the function definitions of symbols, to produce named functions, or passed as arguments to other functions (see section Anonymous Functions).

However, calls to explicit lambda expressions were very useful in the old days of Lisp, before the special form let was invented. At that time, they were the only way to bind and initialize local variables.

Other Features of Argument Lists

Our simple sample function, (lambda (a b c) (+ a b c)), specifies three argument variables, so it must be called with three arguments: if you try to call it with only two arguments or four arguments, you get a wrong-number-of-arguments error.

It is often convenient to write a function that allows certain arguments to be omitted. For example, the function substring accepts three arguments--a string, the start index and the end index--but the third argument defaults to the length of the string if you omit it. It is also convenient for certain functions to accept an indefinite number of arguments, as the functions list and + do.

To specify optional arguments that may be omitted when a function is called, simply include the keyword &optional before the optional arguments. To specify a list of zero or more extra arguments, include the keyword &rest before one final argument.

Thus, the complete syntax for an argument list is as follows:

(required-vars...
 [&optional optional-vars...]
 [&rest rest-var])

The square brackets indicate that the &optional and &rest clauses, and the variables that follow them, are optional.

A call to the function requires one actual argument for each of the required-vars. There may be actual arguments for zero or more of the optional-vars, and there cannot be any actual arguments beyond that unless the lambda list uses &rest. In that case, there may be any number of extra actual arguments.

If actual arguments for the optional and rest variables are omitted, then they always default to nil. There is no way for the function to distinguish between an explicit argument of nil and an omitted argument. However, the body of the function is free to consider nil an abbreviation for some other meaningful value. This is what substring does; nil as the third argument to substring means to use the length of the string supplied.

Common Lisp note: Common Lisp allows the function to specify what default value to use when an optional argument is omitted; Emacs Lisp always uses nil. Emacs Lisp does not support "supplied-p" variables that tell you whether an argument was explicitly passed.

For example, an argument list that looks like this:

(a b &optional c d &rest e)

binds a and b to the first two actual arguments, which are required. If one or two more arguments are provided, c and d are bound to them respectively; any arguments after the first four are collected into a list and e is bound to that list. If there are only two arguments, c is nil; if two or three arguments, d is nil; if four arguments or fewer, e is nil.

There is no way to have required arguments following optional ones--it would not make sense. To see why this must be so, suppose that c in the example were optional and d were required. Suppose three actual arguments are given; which variable would the third argument be for? Similarly, it makes no sense to have any more arguments (either required or optional) after a &rest argument.

Here are some examples of argument lists and proper calls:

((lambda (n) (1+ n))                ; One required:
 1)                                 ; requires exactly one argument.
     => 2
((lambda (n &optional n1)           ; One required and one optional:
         (if n1 (+ n n1) (1+ n)))   ; 1 or 2 arguments.
 1 2)
     => 3
((lambda (n &rest ns)               ; One required and one rest:
         (+ n (apply '+ ns)))       ; 1 or more arguments.
 1 2 3 4 5)
     => 15

Documentation Strings of Functions

A lambda expression may optionally have a documentation string just after the lambda list. This string does not affect execution of the function; it is a kind of comment, but a systematized comment which actually appears inside the Lisp world and can be used by the Emacs help facilities. See section Documentation, for how the documentation-string is accessed.

It is a good idea to provide documentation strings for all the functions in your program, even those that are called only from within your program. Documentation strings are like comments, except that they are easier to access.

The first line of the documentation string should stand on its own, because apropos displays just this first line. It should consist of one or two complete sentences that summarize the function's purpose.

The start of the documentation string is usually indented in the source file, but since these spaces come before the starting double-quote, they are not part of the string. Some people make a practice of indenting any additional lines of the string so that the text lines up in the program source. This is a mistake. The indentation of the following lines is inside the string; what looks nice in the source code will look ugly when displayed by the help commands.

You may wonder how the documentation string could be optional, since there are required components of the function that follow it (the body). Since evaluation of a string returns that string, without any side effects, it has no effect if it is not the last form in the body. Thus, in practice, there is no confusion between the first form of the body and the documentation string; if the only body form is a string then it serves both as the return value and as the documentation.

Naming a Function

In most computer languages, every function has a name; the idea of a function without a name is nonsensical. In Lisp, a function in the strictest sense has no name. It is simply a list whose first element is lambda, a byte-code function object, or a primitive subr-object.

However, a symbol can serve as the name of a function. This happens when you put the function in the symbol's function cell (see section Symbol Components). Then the symbol itself becomes a valid, callable function, equivalent to the list or subr-object that its function cell refers to. The contents of the function cell are also called the symbol's function definition. The procedure of using a symbol's function definition in place of the symbol is called symbol function indirection; see section Symbol Function Indirection.

In practice, nearly all functions are given names in this way and referred to through their names. For example, the symbol car works as a function and does what it does because the primitive subr-object #<subr car> is stored in its function cell.

We give functions names because it is convenient to refer to them by their names in Lisp expressions. For primitive subr-objects such as #<subr car>, names are the only way you can refer to them: there is no read syntax for such objects. For functions written in Lisp, the name is more convenient to use in a call than an explicit lambda expression. Also, a function with a name can refer to itself--it can be recursive. Writing the function's name in its own definition is much more convenient than making the function definition point to itself (something that is not impossible but that has various disadvantages in practice).

We often identify functions with the symbols used to name them. For example, we often speak of "the function car", not distinguishing between the symbol car and the primitive subr-object that is its function definition. For most purposes, there is no need to distinguish.

Even so, keep in mind that a function need not have a unique name. While a given function object usually appears in the function cell of only one symbol, this is just a matter of convenience. It is easy to store it in several symbols using fset; then each of the symbols is equally well a name for the same function.

A symbol used as a function name may also be used as a variable; these two uses of a symbol are independent and do not conflict. (Some Lisp dialects, such as Scheme, do not distinguish between a symbol's value and its function definition; a symbol's value as a variable is also its function definition.) If you have not given a symbol a function definition, you cannot use it as a function; whether the symbol has a value as a variable makes no difference to this.

Defining Functions

We usually give a name to a function when it is first created. This is called defining a function, and it is done with the defun special form.

Special Form: defun name argument-list body-forms
defun is the usual way to define new Lisp functions. It defines the symbol name as a function that looks like this:

(lambda argument-list . body-forms)

defun stores this lambda expression in the function cell of name. It returns the value name, but usually we ignore this value.

As described previously (see section Lambda Expressions), argument-list is a list of argument names and may include the keywords &optional and &rest. Also, the first two of the body-forms may be a documentation string and an interactive declaration.

There is no conflict if the same symbol name is also used as a variable, since the symbol's value cell is independent of the function cell. See section Symbol Components.

Here are some examples:

(defun foo () 5)
     => foo
(foo)
     => 5

(defun bar (a &optional b &rest c)
    (list a b c))
     => bar
(bar 1 2 3 4 5)
     => (1 2 (3 4 5))
(bar 1)
     => (1 nil nil)
(bar)
error--> Wrong number of arguments.

(defun capitalize-backwards ()
  "Upcase the last letter of a word."
  (interactive)
  (backward-word 1)
  (forward-word 1)
  (backward-char 1)
  (capitalize-word 1))
     => capitalize-backwards

Be careful not to redefine existing functions unintentionally. defun redefines even primitive functions such as car without any hesitation or notification. Redefining a function already defined is often done deliberately, and there is no way to distinguish deliberate redefinition from unintentional redefinition.

Function: defalias name definition
This special form defines the symbol name as a function, with definition definition (which can be any valid Lisp function).

The proper place to use defalias is where a specific function name is being defined--especially where that name appears explicitly in the source file being loaded. This is because defalias records which file defined the function, just like defun (see section Unloading).

By contrast, in programs that manipulate function definitions for other purposes, it is better to use fset, which does not keep such records.

See also defsubst, which defines a function like defun and tells the Lisp compiler to open-code it. See section Inline Functions.

Calling Functions

Defining functions is only half the battle. Functions don't do anything until you call them, i.e., tell them to run. Calling a function is also known as invocation.

The most common way of invoking a function is by evaluating a list. For example, evaluating the list (concat "a" "b") calls the function concat with arguments "a" and "b". See section Evaluation, for a description of evaluation.

When you write a list as an expression in your program, the function name it calls is written in your program. This means that you choose which function to call, and how many arguments to give it, when you write the program. Usually that's just what you want. Occasionally you need to compute at run time which function to call. To do that, use the function funcall. When you also need to determine at run time how many arguments to pass, use apply.

Function: funcall function &rest arguments
funcall calls function with arguments, and returns whatever function returns.

Since funcall is a function, all of its arguments, including function, are evaluated before funcall is called. This means that you can use any expression to obtain the function to be called. It also means that funcall does not see the expressions you write for the arguments, only their values. These values are not evaluated a second time in the act of calling function; funcall enters the normal procedure for calling a function at the place where the arguments have already been evaluated.

The argument function must be either a Lisp function or a primitive function. Special forms and macros are not allowed, because they make sense only when given the "unevaluated" argument expressions. funcall cannot provide these because, as we saw above, it never knows them in the first place.

(setq f 'list)
     => list
(funcall f 'x 'y 'z)
     => (x y z)
(funcall f 'x 'y '(z))
     => (x y (z))
(funcall 'and t nil)
error--> Invalid function: #<subr and>

Compare these example with the examples of apply.

Function: apply function &rest arguments
apply calls function with arguments, just like funcall but with one difference: the last of arguments is a list of objects, which are passed to function as separate arguments, rather than a single list. We say that apply spreads this list so that each individual element becomes an argument.

apply returns the result of calling function. As with funcall, function must either be a Lisp function or a primitive function; special forms and macros do not make sense in apply.

(setq f 'list)
     => list
(apply f 'x 'y 'z)
error--> Wrong type argument: listp, z
(apply '+ 1 2 '(3 4))
     => 10
(apply '+ '(1 2 3 4))
     => 10

(apply 'append '((a b c) nil (x y z) nil))
     => (a b c x y z)

For an interesting example of using apply, see the description of mapcar, in section Mapping Functions.

It is common for Lisp functions to accept functions as arguments or find them in data structures (especially in hook variables and property lists) and call them using funcall or apply. Functions that accept function arguments are often called functionals.

Sometimes, when you call a functional, it is useful to supply a no-op function as the argument. Here are two different kinds of no-op function:

Function: identity arg
This function returns arg and has no side effects.

Function: ignore &rest args
This function ignores any arguments and returns nil.

Mapping Functions

A mapping function applies a given function to each element of a list or other collection. Emacs Lisp has several such functions; mapcar and mapconcat, which scan a list, are described here. See section Creating and Interning Symbols, for the function mapatoms which maps over the symbols in an obarray.

These mapping functions do not allow char-tables because a char-table is a sparse array whose nominal range of indices is very large. To map over a char-table in a way that deals properly with its sparse nature, use the function map-char-table (see section Char-Tables).

Function: mapcar function sequence
mapcar applies function to each element of sequence in turn, and returns a list of the results.

The argument sequence can be any kind of sequence except a char-table; that is, a list, a vector, a bool-vector, or a string. The result is always a list. The length of the result is the same as the length of sequence.

For example:

(mapcar 'car '((a b) (c d) (e f)))
     => (a c e)
(mapcar '1+ [1 2 3])
     => (2 3 4)
(mapcar 'char-to-string "abc")
     => ("a" "b" "c")

;; Call each function in my-hooks.
(mapcar 'funcall my-hooks)

(defun mapcar* (function &rest args)
  "Apply FUNCTION to successive cars of all ARGS.
Return the list of results."
  ;; If no list is exhausted,
  (if (not (memq 'nil args))              
      ;; apply function to CARs.
      (cons (apply function (mapcar 'car args))  
            (apply 'mapcar* function             
                   ;; Recurse for rest of elements.
                   (mapcar 'cdr args)))))

(mapcar* 'cons '(a b c) '(1 2 3 4))
     => ((a . 1) (b . 2) (c . 3))

Function: mapconcat function sequence separator
mapconcat applies function to each element of sequence: the results, which must be strings, are concatenated. Between each pair of result strings, mapconcat inserts the string separator. Usually separator contains a space or comma or other suitable punctuation.

The argument function must be a function that can take one argument and return a string. The argument sequence can be any kind of sequence except a char-table; that is, a list, a vector, a bool-vector, or a string.

(mapconcat 'symbol-name
           '(The cat in the hat)
           " ")
     => "The cat in the hat"

(mapconcat (function (lambda (x) (format "%c" (1+ x))))
           "HAL-8000"
           "")
     => "IBM.9111"

Anonymous Functions

In Lisp, a function is a list that starts with lambda, a byte-code function compiled from such a list, or alternatively a primitive subr-object; names are "extra". Although usually functions are defined with defun and given names at the same time, it is occasionally more concise to use an explicit lambda expression--an anonymous function. Such a list is valid wherever a function name is.

Any method of creating such a list makes a valid function. Even this:

(setq silly (append '(lambda (x)) (list (list '+ (* 3 4) 'x))))
=> (lambda (x) (+ 12 x))

This computes a list that looks like (lambda (x) (+ 12 x)) and makes it the value (not the function definition!) of silly.

Here is how we might call this function:

(funcall silly 1)
=> 13

(It does not work to write (silly 1), because this function is not the function definition of silly. We have not given silly any function definition, just a value as a variable.)

Most of the time, anonymous functions are constants that appear in your program. For example, you might want to pass one as an argument to the function mapcar, which applies any given function to each element of a list.

Here we define a function change-property which uses a function as its third argument:

(defun change-property (symbol prop function)
  (let ((value (get symbol prop)))
    (put symbol prop (funcall function value))))

Here we define a function that uses change-property, passing it a function to double a number:

(defun double-property (symbol prop)
  (change-property symbol prop '(lambda (x) (* 2 x))))

In such cases, we usually use the special form function instead of simple quotation to quote the anonymous function, like this:

(defun double-property (symbol prop)
  (change-property symbol prop
                   (function (lambda (x) (* 2 x)))))

Using function instead of quote makes a difference if you compile the function double-property. For example, if you compile the second definition of double-property, the anonymous function is compiled as well. By contrast, if you compile the first definition which uses ordinary quote, the argument passed to change-property is the precise list shown:

(lambda (x) (* x 2))

The Lisp compiler cannot assume this list is a function, even though it looks like one, since it does not know what change-property will do with the list. Perhaps it will check whether the CAR of the third element is the symbol *! Using function tells the compiler it is safe to go ahead and compile the constant function.

We sometimes write function instead of quote when quoting the name of a function, but this usage is just a sort of comment:

(function symbol) == (quote symbol) == 'symbol

The read syntax #' is a short-hand for using function. For example,

#'(lambda (x) (* x x))

is equivalent to

(function (lambda (x) (* x x)))

Special Form: function function-object
This special form returns function-object without evaluating it. In this, it is equivalent to quote. However, it serves as a note to the Emacs Lisp compiler that function-object is intended to be used only as a function, and therefore can safely be compiled. Contrast this with quote, in section Quoting.

See documentation in section Access to Documentation Strings, for a realistic example using function and an anonymous function.

Accessing Function Cell Contents

The function definition of a symbol is the object stored in the function cell of the symbol. The functions described here access, test, and set the function cell of symbols.

See also the function indirect-function in section Symbol Function Indirection.

Function: symbol-function symbol
This returns the object in the function cell of symbol. If the symbol's function cell is void, a void-function error is signaled.

This function does not check that the returned object is a legitimate function.

(defun bar (n) (+ n 2))
     => bar
(symbol-function 'bar)
     => (lambda (n) (+ n 2))
(fset 'baz 'bar)
     => bar
(symbol-function 'baz)
     => bar

If you have never given a symbol any function definition, we say that that symbol's function cell is void. In other words, the function cell does not have any Lisp object in it. If you try to call such a symbol as a function, it signals a void-function error.

Note that void is not the same as nil or the symbol void. The symbols nil and void are Lisp objects, and can be stored into a function cell just as any other object can be (and they can be valid functions if you define them in turn with defun). A void function cell contains no object whatsoever.

You can test the voidness of a symbol's function definition with fboundp. After you have given a symbol a function definition, you can make it void once more using fmakunbound.

Function: fboundp symbol
This function returns t if the symbol has an object in its function cell, nil otherwise. It does not check that the object is a legitimate function.

Function: fmakunbound symbol
This function makes symbol's function cell void, so that a subsequent attempt to access this cell will cause a void-function error. (See also makunbound, in section When a Variable is "Void".)

(defun foo (x) x)
     => foo
(foo 1)
     =>1
(fmakunbound 'foo)
     => foo
(foo 1)
error--> Symbol's function definition is void: foo

Function: fset symbol definition
This function stores definition in the function cell of symbol. The result is definition. Normally definition should be a function or the name of a function, but this is not checked. The argument symbol is an ordinary evaluated argument.

There are three normal uses of this function:

Here are examples of these uses:

;; Save foo's definition in old-foo.
(fset 'old-foo (symbol-function 'foo))

;; Make the symbol car the function definition of xfirst.
;; (Most likely, defalias would be better than fset here.)
(fset 'xfirst 'car)
     => car
(xfirst '(1 2 3))
     => 1
(symbol-function 'xfirst)
     => car
(symbol-function (symbol-function 'xfirst))
     => #<subr car>

;; Define a named keyboard macro.
(fset 'kill-two-lines "\^u2\^k")
     => "\^u2\^k"

;; Here is a function that alters other functions.
(defun copy-function-definition (new old)
  "Define NEW with the same function definition as OLD."
  (fset new (symbol-function old)))

When writing a function that extends a previously defined function, the following idiom is sometimes used:

(fset 'old-foo (symbol-function 'foo))
(defun foo ()
  "Just like old-foo, except more so."
  (old-foo)
  (more-so))

This does not work properly if foo has been defined to autoload. In such a case, when foo calls old-foo, Lisp attempts to define old-foo by loading a file. Since this presumably defines foo rather than old-foo, it does not produce the proper results. The only way to avoid this problem is to make sure the file is loaded before moving aside the old definition of foo.

But it is unmodular and unclean, in any case, for a Lisp file to redefine a function defined elsewhere. It is cleaner to use the advice facility (see section Advising Emacs Lisp Functions).

Inline Functions

You can define an inline function by using defsubst instead of defun. An inline function works just like an ordinary function except for one thing: when you compile a call to the function, the function's definition is open-coded into the caller.

Making a function inline makes explicit calls run faster. But it also has disadvantages. For one thing, it reduces flexibility; if you change the definition of the function, calls already inlined still use the old definition until you recompile them. Since the flexibility of redefining functions is an important feature of Emacs, you should not make a function inline unless its speed is really crucial.

Another disadvantage is that making a large function inline can increase the size of compiled code both in files and in memory. Since the speed advantage of inline functions is greatest for small functions, you generally should not make large functions inline.

It's possible to define a macro to expand into the same code that an inline function would execute. (See section Macros.) But the macro would be limited to direct use in expressions--a macro cannot be called with apply, mapcar and so on. Also, it takes some work to convert an ordinary function into a macro. To convert it into an inline function is very easy; simply replace defun with defsubst. Since each argument of an inline function is evaluated exactly once, you needn't worry about how many times the body uses the arguments, as you do for macros. (See section Evaluating Macro Arguments Repeatedly.)

Inline functions can be used and open-coded later on in the same file, following the definition, just like macros.

Other Topics Related to Functions

Here is a table of several functions that do things related to function calling and function definitions. They are documented elsewhere, but we provide cross references here.

apply
See section Calling Functions.
autoload
See section Autoload.
call-interactively
See section Interactive Call.
commandp
See section Interactive Call.
documentation
See section Access to Documentation Strings.
eval
See section Eval.
funcall
See section Calling Functions.
function
See section Anonymous Functions.
ignore
See section Calling Functions.
indirect-function
See section Symbol Function Indirection.
interactive
See section Using interactive.
interactive-p
See section Interactive Call.
mapatoms
See section Creating and Interning Symbols.
mapcar
See section Mapping Functions.
map-char-table
See section Char-Tables.
mapconcat
See section Mapping Functions.
undefined
See section Key Lookup.

Macros

Macros enable you to define new control constructs and other language features. A macro is defined much like a function, but instead of telling how to compute a value, it tells how to compute another Lisp expression which will in turn compute the value. We call this expression the expansion of the macro.

Macros can do this because they operate on the unevaluated expressions for the arguments, not on the argument values as functions do. They can therefore construct an expansion containing these argument expressions or parts of them.

If you are using a macro to do something an ordinary function could do, just for the sake of speed, consider using an inline function instead. See section Inline Functions.

A Simple Example of a Macro

Suppose we would like to define a Lisp construct to increment a variable value, much like the ++ operator in C. We would like to write (inc x) and have the effect of (setq x (1+ x)). Here's a macro definition that does the job:

(defmacro inc (var)
   (list 'setq var (list '1+ var)))

When this is called with (inc x), the argument var is the symbol x---not the value of x, as it would be in a function. The body of the macro uses this to construct the expansion, which is (setq x (1+ x)). Once the macro definition returns this expansion, Lisp proceeds to evaluate it, thus incrementing x.

Expansion of a Macro Call

A macro call looks just like a function call in that it is a list which starts with the name of the macro. The rest of the elements of the list are the arguments of the macro.

Evaluation of the macro call begins like evaluation of a function call except for one crucial difference: the macro arguments are the actual expressions appearing in the macro call. They are not evaluated before they are given to the macro definition. By contrast, the arguments of a function are results of evaluating the elements of the function call list.

Having obtained the arguments, Lisp invokes the macro definition just as a function is invoked. The argument variables of the macro are bound to the argument values from the macro call, or to a list of them in the case of a &rest argument. And the macro body executes and returns its value just as a function body does.

The second crucial difference between macros and functions is that the value returned by the macro body is not the value of the macro call. Instead, it is an alternate expression for computing that value, also known as the expansion of the macro. The Lisp interpreter proceeds to evaluate the expansion as soon as it comes back from the macro.

Since the expansion is evaluated in the normal manner, it may contain calls to other macros. It may even be a call to the same macro, though this is unusual.

You can see the expansion of a given macro call by calling macroexpand.

Function: macroexpand form &optional environment
This function expands form, if it is a macro call. If the result is another macro call, it is expanded in turn, until something which is not a macro call results. That is the value returned by macroexpand. If form is not a macro call to begin with, it is returned as given.

Note that macroexpand does not look at the subexpressions of form (although some macro definitions may do so). Even if they are macro calls themselves, macroexpand does not expand them.

The function macroexpand does not expand calls to inline functions. Normally there is no need for that, since a call to an inline function is no harder to understand than a call to an ordinary function.

If environment is provided, it specifies an alist of macro definitions that shadow the currently defined macros. Byte compilation uses this feature.

(defmacro inc (var)
    (list 'setq var (list '1+ var)))
     => inc

(macroexpand '(inc r))
     => (setq r (1+ r))

(defmacro inc2 (var1 var2)
    (list 'progn (list 'inc var1) (list 'inc var2)))
     => inc2

(macroexpand '(inc2 r s))
     => (progn (inc r) (inc s))  ; inc not expanded here.

Macros and Byte Compilation

You might ask why we take the trouble to compute an expansion for a macro and then evaluate the expansion. Why not have the macro body produce the desired results directly? The reason has to do with compilation.

When a macro call appears in a Lisp program being compiled, the Lisp compiler calls the macro definition just as the interpreter would, and receives an expansion. But instead of evaluating this expansion, it compiles the expansion as if it had appeared directly in the program. As a result, the compiled code produces the value and side effects intended for the macro, but executes at full compiled speed. This would not work if the macro body computed the value and side effects itself--they would be computed at compile time, which is not useful.

In order for compilation of macro calls to work, the macros must already be defined in Lisp when the calls to them are compiled. The compiler has a special feature to help you do this: if a file being compiled contains a defmacro form, the macro is defined temporarily for the rest of the compilation of that file. To make this feature work, you must put the defmacro in the same file where it is used, and before its first use.

Byte-compiling a file executes any require calls at top-level in the file. This is in case the file needs the required packages for proper compilation. One way to ensure that necessary macro definitions are available during compilation is to require the files that define them (see section Features). To avoid loading the macro definition files when someone runs the compiled program, write eval-when-compile around the require calls (see section Evaluation During Compilation).

Defining Macros

A Lisp macro is a list whose CAR is macro. Its CDR should be a function; expansion of the macro works by applying the function (with apply) to the list of unevaluated argument-expressions from the macro call.

It is possible to use an anonymous Lisp macro just like an anonymous function, but this is never done, because it does not make sense to pass an anonymous macro to functionals such as mapcar. In practice, all Lisp macros have names, and they are usually defined with the special form defmacro.

Special Form: defmacro name argument-list body-forms...
defmacro defines the symbol name as a macro that looks like this:

(macro lambda argument-list . body-forms)

(Note that the CDR of this list is a function--a lambda expression.) This macro object is stored in the function cell of name. The value returned by evaluating the defmacro form is name, but usually we ignore this value.

The shape and meaning of argument-list is the same as in a function, and the keywords &rest and &optional may be used (see section Other Features of Argument Lists). Macros may have a documentation string, but any interactive declaration is ignored since macros cannot be called interactively.

Backquote

Macros often need to construct large list structures from a mixture of constants and nonconstant parts. To make this easier, use the ``' syntax (usually called backquote).

Backquote allows you to quote a list, but selectively evaluate elements of that list. In the simplest case, it is identical to the special form quote (see section Quoting). For example, these two forms yield identical results:

`(a list of (+ 2 3) elements)
     => (a list of (+ 2 3) elements)
'(a list of (+ 2 3) elements)
     => (a list of (+ 2 3) elements)

The special marker `,' inside of the argument to backquote indicates a value that isn't constant. Backquote evaluates the argument of `,' and puts the value in the list structure:

(list 'a 'list 'of (+ 2 3) 'elements)
     => (a list of 5 elements)
`(a list of ,(+ 2 3) elements)
     => (a list of 5 elements)

Substitution with `,' is allowed at deeper levels of the list structure also. For example:

(defmacro t-becomes-nil (variable)
  `(if (eq ,variable t)
       (setq ,variable nil)))

(t-becomes-nil foo)
     == (if (eq foo t) (setq foo nil))

You can also splice an evaluated value into the resulting list, using the special marker `,@'. The elements of the spliced list become elements at the same level as the other elements of the resulting list. The equivalent code without using ``' is often unreadable. Here are some examples:

(setq some-list '(2 3))
     => (2 3)
(cons 1 (append some-list '(4) some-list))
     => (1 2 3 4 2 3)
`(1 ,@some-list 4 ,@some-list)
     => (1 2 3 4 2 3)

(setq list '(hack foo bar))
     => (hack foo bar)
(cons 'use
  (cons 'the
    (cons 'words (append (cdr list) '(as elements)))))
     => (use the words foo bar as elements)
`(use the words ,@(cdr list) as elements)
     => (use the words foo bar as elements)

In old Emacs versions, before version 19.29, ``' used a different syntax which required an extra level of parentheses around the entire backquote construct. Likewise, each `,' or `,@' substitution required an extra level of parentheses surrounding both the `,' or `,@' and the following expression. The old syntax required whitespace between the ``', `,' or `,@' and the following expression.

This syntax is still accepted, for compatibility with old Emacs versions, but we recommend not using it in new programs.

Common Problems Using Macros

The basic facts of macro expansion have counterintuitive consequences. This section describes some important consequences that can lead to trouble, and rules to follow to avoid trouble.

Evaluating Macro Arguments Repeatedly

When defining a macro you must pay attention to the number of times the arguments will be evaluated when the expansion is executed. The following macro (used to facilitate iteration) illustrates the problem. This macro allows us to write a simple "for" loop such as one might find in Pascal.

(defmacro for (var from init to final do &rest body)
  "Execute a simple \"for\" loop.
For example, (for i from 1 to 10 do (print i))."
  (list 'let (list (list var init))
        (cons 'while (cons (list '<= var final)
                           (append body (list (list 'inc var)))))))
=> for

(for i from 1 to 3 do
   (setq square (* i i))
   (princ (format "\n%d %d" i square)))
==>
(let ((i 1))
  (while (<= i 3)
    (setq square (* i i))
    (princ (format "%d      %d" i square))
    (inc i)))

     -|1       1
     -|2       4
     -|3       9
=> nil

The arguments from, to, and do in this macro are "syntactic sugar"; they are entirely ignored. The idea is that you will write noise words (such as from, to, and do) in those positions in the macro call.

Here's an equivalent definition simplified through use of backquote:

(defmacro for (var from init to final do &rest body)
  "Execute a simple \"for\" loop.
For example, (for i from 1 to 10 do (print i))."
  `(let ((,var ,init))
     (while (<= ,var ,final)
       ,@body
       (inc ,var))))

Both forms of this definition (with backquote and without) suffer from the defect that final is evaluated on every iteration. If final is a constant, this is not a problem. If it is a more complex form, say (long-complex-calculation x), this can slow down the execution significantly. If final has side effects, executing it more than once is probably incorrect.

A well-designed macro definition takes steps to avoid this problem by producing an expansion that evaluates the argument expressions exactly once unless repeated evaluation is part of the intended purpose of the macro. Here is a correct expansion for the for macro:

(let ((i 1)
      (max 3))
  (while (<= i max)
    (setq square (* i i))
    (princ (format "%d      %d" i square))
    (inc i)))

Here is a macro definition that creates this expansion:

(defmacro for (var from init to final do &rest body)
  "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  `(let ((,var ,init)
         (max ,final))
     (while (<= ,var max)
       ,@body
       (inc ,var))))

Unfortunately, this fix introduces another problem, described in the following section.

Local Variables in Macro Expansions

The new definition of for has a new problem: it introduces a local variable named max which the user does not expect. This causes trouble in examples such as the following:

(let ((max 0))
  (for x from 0 to 10 do
    (let ((this (frob x)))
      (if (< max this)
          (setq max this)))))

The references to max inside the body of the for, which are supposed to refer to the user's binding of max, really access the binding made by for.

The way to correct this is to use an uninterned symbol instead of max (see section Creating and Interning Symbols). The uninterned symbol can be bound and referred to just like any other symbol, but since it is created by for, we know that it cannot already appear in the user's program. Since it is not interned, there is no way the user can put it into the program later. It will never appear anywhere except where put by for. Here is a definition of for that works this way:

(defmacro for (var from init to final do &rest body)
  "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  (let ((tempvar (make-symbol "max")))
    `(let ((,var ,init)
           (,tempvar ,final))
       (while (<= ,var ,tempvar)
         ,@body
         (inc ,var)))))

This creates an uninterned symbol named max and puts it in the expansion instead of the usual interned symbol max that appears in expressions ordinarily.

Evaluating Macro Arguments in Expansion

Another problem can happen if the macro definition itself evaluates any of the macro argument expressions, such as by calling eval (see section Eval). If the argument is supposed to refer to the user's variables, you may have trouble if the user happens to use a variable with the same name as one of the macro arguments. Inside the macro body, the macro argument binding is the most local binding of this variable, so any references inside the form being evaluated do refer to it. Here is an example:

(defmacro foo (a)
  (list 'setq (eval a) t))
     => foo
(setq x 'b)
(foo x) ==> (setq b t)
     => t                  ; and b has been set.
;; but
(setq a 'c)
(foo a) ==> (setq a t)
     => t                  ; but this set a, not c.

It makes a difference whether the user's variable is named a or x, because a conflicts with the macro argument variable a.

Another problem with calling eval in a macro definition is that it probably won't do what you intend in a compiled program. The byte-compiler runs macro definitions while compiling the program, when the program's own computations (which you might have wished to access with eval) don't occur and its local variable bindings don't exist.

To avoid these problems, don't evaluate an argument expression while computing the macro expansion. Instead, substitute the expression into the macro expansion, so that its value will be computed as part of executing the expansion. This is how the other examples in this chapter work.

How Many Times is the Macro Expanded?

Occasionally problems result from the fact that a macro call is expanded each time it is evaluated in an interpreted function, but is expanded only once (during compilation) for a compiled function. If the macro definition has side effects, they will work differently depending on how many times the macro is expanded.

Therefore, you should avoid side effects in computation of the macro expansion, unless you really know what you are doing.

One special kind of side effect can't be avoided: constructing Lisp objects. Almost all macro expansions include constructed lists; that is the whole point of most macros. This is usually safe; there is just one case where you must be careful: when the object you construct is part of a quoted constant in the macro expansion.

If the macro is expanded just once, in compilation, then the object is constructed just once, during compilation. But in interpreted execution, the macro is expanded each time the macro call runs, and this means a new object is constructed each time.

In most clean Lisp code, this difference won't matter. It can matter only if you perform side-effects on the objects constructed by the macro definition. Thus, to avoid trouble, avoid side effects on objects constructed by macro definitions. Here is an example of how such side effects can get you into trouble:

(defmacro empty-object ()
  (list 'quote (cons nil nil)))

(defun initialize (condition)
  (let ((object (empty-object)))
    (if condition
        (setcar object condition))
    object))

If initialize is interpreted, a new list (nil) is constructed each time initialize is called. Thus, no side effect survives between calls. If initialize is compiled, then the macro empty-object is expanded during compilation, producing a single "constant" (nil) that is reused and altered each time initialize is called.

One way to avoid pathological cases like this is to think of empty-object as a funny kind of constant, not as a memory allocation construct. You wouldn't use setcar on a constant such as '(nil), so naturally you won't use it on (empty-object) either.

Writing Customization Definitions

This chapter describes how to declare user options for customization, and also customization groups for classifying them. We use the term customization item to include both kinds of customization definitions--as well as face definitions (see section Defining Faces).

Common Keywords for All Kinds of Items

All kinds of customization declarations (for variables and groups, and for faces) accept keyword arguments for specifying various information. This section describes some keywords that apply to all kinds.

All of these keywords, except :tag, can be used more than once in a given item. Each use of the keyword has an independent effect. The keyword :tag is an exception because any given item can only display one name.

:tag name
Use name, a string, instead of the item's name, to label the item in customization menus and buffers.
:group group
Put this customization item in group group. When you use :group in a defgroup, it makes the new group a subgroup of group. If you use this keyword more than once, you can put a single item into more than one group. Displaying any of those groups will show this item. Be careful not to overdo this!
:link link-data
Include an external link after the documentation string for this item. This is a sentence containing an active field which references some other documentation. There are three alternatives you can use for link-data:
(custom-manual info-node)
Link to an Info node; info-node is a string which specifies the node name, as in "(emacs)Top". The link appears as `[manual]' in the customization buffer.
(info-link info-node)
Like custom-manual except that the link appears in the customization buffer with the Info node name.
(url-link url)
Link to a web page; url is a string which specifies the URL. The link appears in the customization buffer as url.
You can specify the text to use in the customization buffer by adding :tag name after the first element of the link-data; for example, (info-link :tag "foo" "(emacs)Top") makes a link to the Emacs manual which appears in the buffer as `foo'. An item can have more than one external link; however, most items have none at all.
:load file
Load file file (a string) before displaying this customization item. Loading is done with load-library, and only if the file is not already loaded.
:require feature
Require feature feature (a symbol) when installing a value for this item (an option or a face) that was saved using the customization feature. This is done by calling require. The most common reason to use :require is when a variable enables a feature such as a minor mode, and just setting the variable won't have any effect unless the code which implements the mode is loaded.

Defining Custom Groups

Each Emacs Lisp package should have one main customization group which contains all the options, faces and other groups in the package. If the package has a small number of options and faces, use just one group and put everything in it. When there are more than twelve or so options and faces, then you should structure them into subgroups, and put the subgroups under the package's main customization group. It is OK to put some of the options and faces in the package's main group alongside the subgroups.

The package's main or only group should be a member of one or more of the standard customization groups. (To display the full list of them, use M-x customize.) Choose one or more of them (but not too many), and add your group to each of them using the :group keyword.

The way to declare new customization groups is with defgroup.

Macro: defgroup group members doc [keyword value]...
Declare group as a customization group containing members. Do not quote the symbol group. The argument doc specifies the documentation string for the group.

The argument members is a list specifying an initial set of customization items to be members of the group. However, most often members is nil, and you specify the group's members by using the :group keyword when defining those members.

If you want to specify group members through members, each element should have the form (name widget). Here name is a symbol, and widget is a widget type for editing that symbol. Useful widgets are custom-variable for a variable, custom-face for a face, and custom-group for a group.

In addition to the common keywords (see section Common Keywords for All Kinds of Items), you can use this keyword in defgroup:

:prefix prefix
If the name of an item in the group starts with prefix, then the tag for that item is constructed (by default) by omitting prefix. One group can have any number of prefixes.

The prefix-discarding feature is currently turned off, which means that :prefix currently has no effect. We did this because we found that discarding the specified prefixes often led to confusing names for options. This happened because the people who wrote the defgroup definitions for various groups added :prefix keywords whenever they make logical sense--that is, whenever the variables in the library have a common prefix.

In order to obtain good results with :prefix, it would be necessary to check the specific effects of discarding a particular prefix, given the specific items in a group and their names and documentation. If the resulting text is not clear, then :prefix should not be used in that case.

It should be possible to recheck all the customization groups, delete the :prefix specifications which give unclear results, and then turn this feature back on, if someone would like to do the work.

Defining Customization Variables

Use defcustom to declare user-editable variables.

Macro: defcustom option default doc [keyword value]...
Declare option as a customizable user option variable. Do not quote option. The argument doc specifies the documentation string for the variable.

If option is void, defcustom initializes it to default. default should be an expression to compute the value; be careful in writing it, because it can be evaluated on more than one occasion.

defcustom accepts the following additional keywords:

:type type
Use type as the data type for this option. It specifies which values are legitimate, and how to display the value. See section Customization Types, for more information.
:options list
Specify list as the list of reasonable values for use in this option. Currently this is meaningful only when the type is hook. In that case, the elements of list should be functions that are useful as elements of the hook value. The user is not restricted to using only these functions, but they are offered as convenient alternatives.
:version version
This option specifies that the variable was first introduced, or its default value was changed, in Emacs version version. The value version must be a string. For example,
(defcustom foo-max 34
  "*Maximum number of foo's allowed."
  :type 'integer
  :group 'foo
  :version "20.3")
:set setfunction
Specify setfunction as the way to change the value of this option. The function setfunction should take two arguments, a symbol and the new value, and should do whatever is necessary to update the value properly for this option (which may not mean simply setting the option as a Lisp variable). The default for setfunction is set-default.
:get getfunction
Specify getfunction as the way to extract the value of this option. The function getfunction should take one argument, a symbol, and should return the "current value" for that symbol (which need not be the symbol's Lisp value). The default is default-value.
:initialize function
function should be a function used to initialize the variable when the defcustom is evaluated. It should take two arguments, the symbol and value. Here are some predefined functions meant for use in this way:
custom-initialize-set
Use the variable's :set function to initialize the variable, but do not reinitialize it if it is already non-void. This is the default :initialize function.
custom-initialize-default
Like custom-initialize-set, but use the function set-default to set the variable, instead of the variable's :set function. This is the usual choice for a variable whose :set function enables or disables a minor mode; with this choice, defining the variable will not call the minor mode function, but customizing the variable will do so.
custom-initialize-reset
Always use the :set function to initialize the variable. If the variable is already non-void, reset it by calling the :set function using the current value (returned by the :get method).
custom-initialize-changed
Use the :set function to initialize the variable, if it is already set or has been customized; otherwise, just use set-default.

The :require option is useful for an option that turns on the operation of a certain feature. Assuming that the package is coded to check the value of the option, you still need to arrange for the package to be loaded. You can do that with :require. See section Common Keywords for All Kinds of Items. Here is an example, from the library `paren.el':

(defcustom show-paren-mode nil
  "Toggle Show Paren [email protected]{}"
  :set (lambda (symbol value)
         (show-paren-mode (or value 0)))
  :initialize 'custom-initialize-default
  :type 'boolean
  :group 'paren-showing
  :require 'paren)

Internally, defcustom uses the symbol property standard-value to record the expression for the default value, and saved-value to record the value saved by the user with the customization buffer. The saved-value property is actually a list whose car is an expression which evaluates to the value.

Customization Types

When you define a user option with defcustom, you must specify its customization type. That is a Lisp object which describes (1) which values are legitimate and (2) how to display the value in the customization buffer for editing.

You specify the customization type in defcustom with the :type keyword. The argument of :type is evaluated; since types that vary at run time are rarely useful, normally you use a quoted constant. For example:

(defcustom diff-command "diff"
  "*The command to use to run diff."
  :type '(string)
  :group 'diff)

In general, a customization type is a list whose first element is a symbol, one of the customization type names defined in the following sections. After this symbol come a number of arguments, depending on the symbol. Between the type symbol and its arguments, you can optionally write keyword-value pairs (see section Type Keywords).

Some of the type symbols do not use any arguments; those are called simple types. For a simple type, if you do not use any keyword-value pairs, you can omit the parentheses around the type symbol. For example just string as a customization type is equivalent to (string).

Simple Types

This section describes all the simple customization types.

sexp
The value may be any Lisp object that can be printed and read back. You can use sexp as a fall-back for any option, if you don't want to take the time to work out a more specific type to use.
integer
The value must be an integer, and is represented textually in the customization buffer.
number
The value must be a number, and is represented textually in the customization buffer.
string
The value must be a string, and the customization buffer shows just the contents, with no delimiting `"' characters and no quoting with `\'.
regexp
Like string except that the string must be a valid regular expression.
character
The value must be a character code. A character code is actually an integer, but this type shows the value by inserting the character in the buffer, rather than by showing the number.
file
The value must be a file name, and you can do completion with M-TAB.
(file :must-match t)
The value must be a file name for an existing file, and you can do completion with M-TAB.
directory
The value must be a directory name, and you can do completion with M-TAB.
hook
The value must be a list of functions (or a single function, but that is obsolete usage). This customization type is used for hook variables. You can use the :options keyword in a hook variable's defcustom to specify a list of functions recommended for use in the hook; see section Defining Customization Variables.
symbol
The value must be a symbol. It appears in the customization buffer as the name of the symbol.
function
The value must be either a lambda expression or a function name. When it is a function name, you can do completion with M-TAB.
variable
The value must be a variable name, and you can do completion with M-TAB.
face
The value must be a symbol which is a face name, and you can do completion with M-TAB.
boolean
The value is boolean--either nil or t. Note that by using choice and const together (see the next section), you can specify that the value must be nil or t, but also specify the text to describe each value in a way that fits the specific meaning of the alternative.

Composite Types

When none of the simple types is appropriate, you can use composite types, which build new types from other types. Here are several ways of doing that:

(restricted-sexp :match-alternatives criteria)
The value may be any Lisp object that satisfies one of criteria. criteria should be a list, and each element should be one of these possibilities: For example,
(restricted-sexp :match-alternatives
                 (integerp 't 'nil))
allows integers, t and nil as legitimate values. The customization buffer shows all legitimate values using their read syntax, and the user edits them textually.
(cons car-type cdr-type)
The value must be a cons cell, its CAR must fit car-type, and its CDR must fit cdr-type. For example, (cons string symbol) is a customization type which matches values such as ("foo" . foo). In the customization buffer, the CAR and the CDR are displayed and edited separately, each according to the type that you specify for it.
(list element-types...)
The value must be a list with exactly as many elements as the element-types you have specified; and each element must fit the corresponding element-type. For example, (list integer string function) describes a list of three elements; the first element must be an integer, the second a string, and the third a function. In the customization buffer, each element is displayed and edited separately, according to the type specified for it.
(vector element-types...)
Like list except that the value must be a vector instead of a list. The elements work the same as in list.
(choice alternative-types...)
The value must fit at least one of alternative-types. For example, (choice integer string) allows either an integer or a string. In the customization buffer, the user selects one of the alternatives using a menu, and can then edit the value in the usual way for that alternative. Normally the strings in this menu are determined automatically from the choices; however, you can specify different strings for the menu by including the :tag keyword in the alternatives. For example, if an integer stands for a number of spaces, while a string is text to use verbatim, you might write the customization type this way,
(choice (integer :tag "Number of spaces")
        (string :tag "Literal text"))
so that the menu offers `Number of spaces' and `Literal Text'. In any alternative for which nil is not a valid value, other than a const, you should specify a valid default for that alternative using the :value keyword. See section Type Keywords.
(const value)
The value must be value---nothing else is allowed. The main use of const is inside of choice. For example, (choice integer (const nil)) allows either an integer or nil. :tag is often used with const, inside of choice. For example,
(choice (const :tag "Yes" t)
        (const :tag "No" nil)
        (const :tag "Ask" foo))
describes a variable for which t means yes, nil means no, and foo means "ask."
(other value)
This alternative can match any Lisp value, but if the user chooses this alternative, that selects the value value. The main use of other is as the last element of choice. For example,
(choice (const :tag "Yes" t)
        (const :tag "No" nil)
        (other :tag "Ask" foo))
describes a variable for which t means yes, nil means no, and anything else means "ask." If the user chooses `Ask' from the menu of alternatives, that specifies the value foo; but any other value (not t, nil or foo) displays as `Ask', just like foo.
(function-item function)
Like const, but used for values which are functions. This displays the documentation string as well as the function name. The documentation string is either the one you specify with :doc, or function's own documentation string.
(variable-item variable)
Like const, but used for values which are variable names. This displays the documentation string as well as the variable name. The documentation string is either the one you specify with :doc, or variable's own documentation string.
(set elements...)
The value must be a list and each element of the list must be one of the elements specified. This appears in the customization buffer as a checklist.
(repeat element-type)
The value must be a list and each element of the list must fit the type element-type. This appears in the customization buffer as a list of elements, with `[INS]' and `[DEL]' buttons for adding more elements or removing elements.

Splicing into Lists

The :inline feature lets you splice a variable number of elements into the middle of a list or vector. You use it in a set, choice or repeat type which appears among the element-types of a list or vector.

Normally, each of the element-types in a list or vector describes one and only one element of the list or vector. Thus, if an element-type is a repeat, that specifies a list of unspecified length which appears as one element.

But when the element-type uses :inline, the value it matches is merged directly into the containing sequence. For example, if it matches a list with three elements, those become three elements of the overall sequence. This is analogous to using `,@' in the backquote construct.

For example, to specify a list whose first element must be t and whose remaining arguments should be zero or more of foo and bar, use this customization type:

(list (const t) (set :inline t foo bar))

This matches values such as (t), (t foo), (t bar) and (t foo bar).

When the element-type is a choice, you use :inline not in the choice itself, but in (some of) the alternatives of the choice. For example, to match a list which must start with a file name, followed either by the symbol t or two strings, use this customization type:

(list file
      (choice (const t)
              (list :inline t string string)))

If the user chooses the first alternative in the choice, then the overall list has two elements and the second element is t. If the user chooses the second alternative, then the overall list has three elements and the second and third must be strings.

Type Keywords

You can specify keyword-argument pairs in a customization type after the type name symbol. Here are the keywords you can use, and their meanings:

:value default
This is used for a type that appears as an alternative inside of choice; it specifies the default value to use, at first, if and when the user selects this alternative with the menu in the customization buffer. Of course, if the actual value of the option fits this alternative, it will appear showing the actual value, not default. If nil is not a valid value for the alternative, then it is essential to specify a valid default with :value.
:format format-string
This string will be inserted in the buffer to represent the value corresponding to the type. The following `%' escapes are available for use in format-string:
`%[button%]'
Display the text button marked as a button. The :action attribute specifies what the button will do if the user invokes it; its value is a function which takes two arguments--the widget which the button appears in, and the event. There is no way to specify two different buttons with different actions.
`%{sample%}'
Show sample in a special face specified by :sample-face.
`%v'
Substitute the item's value. How the value is represented depends on the kind of item, and (for variables) on the customization type.
`%d'
Substitute the item's documentation string.
`%h'
Like `%d', but if the documentation string is more than one line, add an active field to control whether to show all of it or just the first line.
`%t'
Substitute the tag here. You specify the tag with the :tag keyword.
`%%'
Display a literal `%'.
:action action
Perform action if the user clicks on a button.
:button-face face
Use the face face (a face name or a list of face names) for button text displayed with `%[...%]'.
:button-prefix prefix
:button-suffix suffix
These specify the text to display before and after a button. Each can be:
nil
No text is inserted.
a string
The string is inserted literally.
a symbol
The symbol's value is used.
:tag tag
Use tag (a string) as the tag for the value (or part of the value) that corresponds to this type.
:doc doc
Use doc as the documentation string for this value (or part of the value) that corresponds to this type. In order for this to work, you must specify a value for :format, and use `%d' or `%h' in that value. The usual reason to specify a documentation string for a type is to provide more information about the meanings of alternatives inside a :choice type or the parts of some other composite type.
:help-echo motion-doc
When you move to this item with widget-forward or widget-backward, it will display the string motion-doc in the echo area.
:match function
Specify how to decide whether a value matches the type. The corresponding value, function, should be a function that accepts two arguments, a widget and a value; it should return non-nil if the value is acceptable.

Loading

Loading a file of Lisp code means bringing its contents into the Lisp environment in the form of Lisp objects. Emacs finds and opens the file, reads the text, evaluates each form, and then closes the file.

The load functions evaluate all the expressions in a file just as the eval-current-buffer function evaluates all the expressions in a buffer. The difference is that the load functions read and evaluate the text in the file as found on disk, not the text in an Emacs buffer.

The loaded file must contain Lisp expressions, either as source code or as byte-compiled code. Each form in the file is called a top-level form. There is no special format for the forms in a loadable file; any form in a file may equally well be typed directly into a buffer and evaluated there. (Indeed, most code is tested this way.) Most often, the forms are function definitions and variable definitions.

A file containing Lisp code is often called a library. Thus, the "Rmail library" is a file containing code for Rmail mode. Similarly, a "Lisp library directory" is a directory of files containing Lisp code.

How Programs Do Loading

Emacs Lisp has several interfaces for loading. For example, autoload creates a placeholder object for a function defined in a file; trying to call the autoloading function loads the file to get the function's real definition (see section Autoload). require loads a file if it isn't already loaded (see section Features). Ultimately, all these facilities call the load function to do the work.

Function: load filename &optional missing-ok nomessage nosuffix must-suffix
This function finds and opens a file of Lisp code, evaluates all the forms in it, and closes the file.

To find the file, load first looks for a file named `filename.elc', that is, for a file whose name is filename with `.elc' appended. If such a file exists, it is loaded. If there is no file by that name, then load looks for a file named `filename.el'. If that file exists, it is loaded. Finally, if neither of those names is found, load looks for a file named filename with nothing appended, and loads it if it exists. (The load function is not clever about looking at filename. In the perverse case of a file named `foo.el.el', evaluation of (load "foo.el") will indeed find it.)

If the optional argument nosuffix is non-nil, then the suffixes `.elc' and `.el' are not tried. In this case, you must specify the precise file name you want. By specifying the precise file name and using t for nosuffix, you can prevent perverse file names such as `foo.el.el' from being tried.

If the optional argument must-suffix is non-nil, then load insists that the file name used must end in either `.el' or `.elc', unless it contains an explicit directory name. If filename does not contain an explicit directory name, and does not end in a suffix, then load insists on adding one.

If filename is a relative file name, such as `foo' or `baz/foo.bar', load searches for the file using the variable load-path. It appends filename to each of the directories listed in load-path, and loads the first file it finds whose name matches. The current default directory is tried only if it is specified in load-path, where nil stands for the default directory. load tries all three possible suffixes in the first directory in load-path, then all three suffixes in the second directory, and so on. See section Library Search.

If you get a warning that `foo.elc' is older than `foo.el', it means you should consider recompiling `foo.el'. See section Byte Compilation.

When loading a source file (not compiled), load performs character set translation just as Emacs would do when visiting the file. See section Coding Systems.

Messages like `Loading foo...' and `Loading foo...done' appear in the echo area during loading unless nomessage is non-nil.

Any unhandled errors while loading a file terminate loading. If the load was done for the sake of autoload, any function definitions made during the loading are undone.

If load can't find the file to load, then normally it signals the error file-error (with `Cannot open load file filename'). But if missing-ok is non-nil, then load just returns nil.

You can use the variable load-read-function to specify a function for load to use instead of read for reading expressions. See below.

load returns t if the file loads successfully.

Command: load-file filename
This command loads the file filename. If filename is a relative file name, then the current default directory is assumed. load-path is not used, and suffixes are not appended. Use this command if you wish to specify precisely the file name to load.

Command: load-library library
This command loads the library named library. It is equivalent to load, except in how it reads its argument interactively.

Variable: load-in-progress
This variable is non-nil if Emacs is in the process of loading a file, and it is nil otherwise.

Variable: load-read-function
This variable specifies an alternate expression-reading function for load and eval-region to use instead of read. The function should accept one argument, just as read does.

Normally, the variable's value is nil, which means those functions should use read.

Note: Instead of using this variable, it is cleaner to use another, newer feature: to pass the function as the read-function argument to eval-region. See section Eval.

For information about how load is used in building Emacs, see section Building Emacs.

Library Search

When Emacs loads a Lisp library, it searches for the library in a list of directories specified by the variable load-path.

User Option: load-path
The value of this variable is a list of directories to search when loading files with load. Each element is a string (which must be a directory name) or nil (which stands for the current working directory).

The value of load-path is initialized from the environment variable EMACSLOADPATH, if that exists; otherwise its default value is specified in `emacs/src/paths.h' when Emacs is built. Then the list is expanded by adding subdirectories of the directories in the list.

The syntax of EMACSLOADPATH is the same as used for PATH; `:' (or `;', according to the operating system) separates directory names, and `.' is used for the current default directory. Here is an example of how to set your EMACSLOADPATH variable from a csh `.login' file:

setenv EMACSLOADPATH .:/user/bil/emacs:/usr/local/share/emacs/20.3/lisp

Here is how to set it using sh:

export EMACSLOADPATH
EMACSLOADPATH=.:/user/bil/emacs:/usr/local/share/emacs/20.3/lisp

Here is an example of code you can place in a `.emacs' file to add several directories to the front of your default load-path:

(setq load-path
      (append (list nil "/user/bil/emacs"
                    "/usr/local/lisplib"
                    "~/emacs")
              load-path))

In this example, the path searches the current working directory first, followed then by the `/user/bil/emacs' directory, the `/usr/local/lisplib' directory, and the `~/emacs' directory, which are then followed by the standard directories for Lisp code.

Dumping Emacs uses a special value of load-path. If the value of load-path at the end of dumping is unchanged (that is, still the same special value), the dumped Emacs switches to the ordinary load-path value when it starts up, as described above. But if load-path has any other value at the end of dumping, that value is used for execution of the dumped Emacs also.

Therefore, if you want to change load-path temporarily for loading a few libraries in `site-init.el' or `site-load.el', you should bind load-path locally with let around the calls to load.

The default value of load-path, when running an Emacs which has been installed on the system, includes two special directories (and their subdirectories as well):

"/usr/local/share/emacs/version/site-lisp"

and

"/usr/local/share/emacs/site-lisp"

The first one is for locally installed packages for a particular Emacs version; the second is for locally installed packages meant for use with all installed Emacs versions.

There are several reasons why a Lisp package that works well in one Emacs version can cause trouble in another. Sometimes packages need updating for incompatible changes in Emacs; sometimes they depend on undocumented internal Emacs data that can change without notice; sometimes a newer Emacs version incorporates a version of the package, and should be used only with that version.

Emacs finds these directories' subdirectories and adds them to load-path when it starts up. Both immediate subdirectories and subdirectories multiple levels down are added to load-path.

Not all subdirectories are included, though. Subdirectories whose names do not start with a letter or digit are excluded. Subdirectories named `RCS' are excluded. Also, a subdirectory which contains a file named `.nosearch' is excluded. You can use these methods to prevent certain subdirectories of the `site-lisp' directories from being searched.

If you run Emacs from the directory where it was built--that is, an executable that has not been formally installed--then load-path normally contains two additional directories. These are the lisp and site-lisp subdirectories of the main build directory. (Both are represented as absolute file names.)

Command: locate-library library &optional nosuffix path interactive-call
This command finds the precise file name for library library. It searches for the library in the same way load does, and the argument nosuffix has the same meaning as in load: don't add suffixes `.elc' or `.el' to the specified name library.

If the path is non-nil, that list of directories is used instead of load-path.

When locate-library is called from a program, it returns the file name as a string. When the user runs locate-library interactively, the argument interactive-call is t, and this tells locate-library to display the file name in the echo area.

Loading Non-ASCII Characters

When Emacs Lisp programs contain string constants with non-ASCII characters, these can be represented within Emacs either as unibyte strings or as multibyte strings (see section Text Representations). Which representation is used depends on how the file is read into Emacs. If it is read with decoding into multibyte representation, the text of the Lisp program will be multibyte text, and its string constants will be multibyte strings. If a file containing Latin-1 characters (for example) is read without decoding, the text of the program will be unibyte text, and its string constants will be unibyte strings. See section Coding Systems.

To make the results more predictable, Emacs always performs decoding into the multibyte representation when loading Lisp files, even if it was started with the `--unibyte' option. This means that string constants with non-ASCII characters translate into multibyte strings. The only exception is when a particular file specifies no decoding.

The reason Emacs is designed this way is so that Lisp programs give predictable results, regardless of how Emacs was started. In addition, this enables programs that depend on using multibyte text to work even in a unibyte Emacs. Of course, such programs should be designed to notice whether the user prefers unibyte or multibyte text, by checking default-enable-multibyte-characters, and convert representations appropriately.

In most Emacs Lisp programs, the fact that non-ASCII strings are multibyte strings should not be noticeable, since inserting them in unibyte buffers converts them to unibyte automatically. However, if this does make a difference, you can force a particular Lisp file to be interpreted as unibyte by writing `-*-unibyte: t;-*-' in a comment on the file's first line. With that designator, the file will be unconditionally be interpreted as unibyte, even in an ordinary multibyte Emacs session.

Autoload

The autoload facility allows you to make a function or macro known in Lisp, but put off loading the file that defines it. The first call to the function automatically reads the proper file to install the real definition and other associated code, then runs the real definition as if it had been loaded all along.

There are two ways to set up an autoloaded function: by calling autoload, and by writing a special "magic" comment in the source before the real definition. autoload is the low-level primitive for autoloading; any Lisp program can call autoload at any time. Magic comments are the most convenient way to make a function autoload, for packages installed along with Emacs. These comments do nothing on their own, but they serve as a guide for the command update-file-autoloads, which constructs calls to autoload and arranges to execute them when Emacs is built.

Function: autoload function filename &optional docstring interactive type
This function defines the function (or macro) named function so as to load automatically from filename. The string filename specifies the file to load to get the real definition of function.

If filename does not contain either a directory name, or the suffix .el or .elc, then autoload insists on adding one of these suffixes, and it will not load from a file whose name is just filename with no added suffix.

The argument docstring is the documentation string for the function. Normally, this should be identical to the documentation string in the function definition itself. Specifying the documentation string in the call to autoload makes it possible to look at the documentation without loading the function's real definition.

If interactive is non-nil, that says function can be called interactively. This lets completion in M-x work without loading function's real definition. The complete interactive specification is not given here; it's not needed unless the user actually calls function, and when that happens, it's time to load the real definition.

You can autoload macros and keymaps as well as ordinary functions. Specify type as macro if function is really a macro. Specify type as keymap if function is really a keymap. Various parts of Emacs need to know this information without loading the real definition.

An autoloaded keymap loads automatically during key lookup when a prefix key's binding is the symbol function. Autoloading does not occur for other kinds of access to the keymap. In particular, it does not happen when a Lisp program gets the keymap from the value of a variable and calls define-key; not even if the variable name is the same symbol function.

If function already has a non-void function definition that is not an autoload object, autoload does nothing and returns nil. If the function cell of function is void, or is already an autoload object, then it is defined as an autoload object like this:

(autoload filename docstring interactive type)

For example,

(symbol-function 'run-prolog)
     => (autoload "prolog" 169681 t nil)

In this case, "prolog" is the name of the file to load, 169681 refers to the documentation string in the `emacs/etc/DOC-version' file (see section Documentation Basics), t means the function is interactive, and nil that it is not a macro or a keymap.

The autoloaded file usually contains other definitions and may require or provide one or more features. If the file is not completely loaded (due to an error in the evaluation of its contents), any function definitions or provide calls that occurred during the load are undone. This is to ensure that the next attempt to call any function autoloading from this file will try again to load the file. If not for this, then some of the functions in the file might be defined by the aborted load, but fail to work properly for the lack of certain subroutines not loaded successfully because they come later in the file.

If the autoloaded file fails to define the desired Lisp function or macro, then an error is signaled with data "Autoloading failed to define function function-name".

A magic autoload comment consists of `;;;###autoload', on a line by itself, just before the real definition of the function in its autoloadable source file. The command M-x update-file-autoloads writes a corresponding autoload call into `loaddefs.el'. Building Emacs loads `loaddefs.el' and thus calls autoload. M-x update-directory-autoloads is even more powerful; it updates autoloads for all files in the current directory.

The same magic comment can copy any kind of form into `loaddefs.el'. If the form following the magic comment is not a function definition, it is copied verbatim. You can also use a magic comment to execute a form at build time without executing it when the file itself is loaded. To do this, write the form on the same line as the magic comment. Since it is in a comment, it does nothing when you load the source file; but M-x update-file-autoloads copies it to `loaddefs.el', where it is executed while building Emacs.

The following example shows how doctor is prepared for autoloading with a magic comment:

;;;###autoload
(defun doctor ()
  "Switch to *doctor* buffer and start giving psychotherapy."
  (interactive)
  (switch-to-buffer "*doctor*")
  (doctor-mode))

Here's what that produces in `loaddefs.el':

(autoload 'doctor "doctor"
  "\
Switch to *doctor* buffer and start giving psychotherapy."
  t)

The backslash and newline immediately following the double-quote are a convention used only in the preloaded Lisp files such as `loaddefs.el'; they tell make-docfile to put the documentation string in the `etc/DOC' file. See section Building Emacs.

Repeated Loading

You can load a given file more than once in an Emacs session. For example, after you have rewritten and reinstalled a function definition by editing it in a buffer, you may wish to return to the original version; you can do this by reloading the file it came from.

When you load or reload files, bear in mind that the load and load-library functions automatically load a byte-compiled file rather than a non-compiled file of similar name. If you rewrite a file that you intend to save and reinstall, you need to byte-compile the new version; otherwise Emacs will load the older, byte-compiled file instead of your newer, non-compiled file! If that happens, the message displayed when loading the file includes, `(compiled; note, source is newer)', to remind you to recompile it.

When writing the forms in a Lisp library file, keep in mind that the file might be loaded more than once. For example, think about whether each variable should be reinitialized when you reload the library; defvar does not change the value if the variable is already initialized. (See section Defining Global Variables.)

The simplest way to add an element to an alist is like this:

(setq minor-mode-alist
      (cons '(leif-mode " Leif") minor-mode-alist))

But this would add multiple elements if the library is reloaded. To avoid the problem, write this:

(or (assq 'leif-mode minor-mode-alist)
    (setq minor-mode-alist
          (cons '(leif-mode " Leif") minor-mode-alist)))

To add an element to a list just once, you can also use add-to-list (see section How to Alter a Variable Value).

Occasionally you will want to test explicitly whether a library has already been loaded. Here's one way to test, in a library, whether it has been loaded before:

(defvar foo-was-loaded nil)

(unless foo-was-loaded
  execute-first-time-only
  (setq foo-was-loaded t))

If the library uses provide to provide a named feature, you can use featurep earlier in the file to test whether the provide call has been executed before.

Features

provide and require are an alternative to autoload for loading files automatically. They work in terms of named features. Autoloading is triggered by calling a specific function, but a feature is loaded the first time another program asks for it by name.

A feature name is a symbol that stands for a collection of functions, variables, etc. The file that defines them should provide the feature. Another program that uses them may ensure they are defined by requiring the feature. This loads the file of definitions if it hasn't been loaded already.

To require the presence of a feature, call require with the feature name as argument. require looks in the global variable features to see whether the desired feature has been provided already. If not, it loads the feature from the appropriate file. This file should call provide at the top level to add the feature to features; if it fails to do so, require signals an error.

For example, in `emacs/lisp/prolog.el', the definition for run-prolog includes the following code:

(defun run-prolog ()
  "Run an inferior Prolog process, with I/O via buffer *prolog*."
  (interactive)
  (require 'comint)
  (switch-to-buffer (make-comint "prolog" prolog-program-name))
  (inferior-prolog-mode))

The expression (require 'comint) loads the file `comint.el' if it has not yet been loaded. This ensures that make-comint is defined. Features are normally named after the files that provide them, so that require need not be given the file name.

The `comint.el' file contains the following top-level expression:

(provide 'comint)

This adds comint to the global features list, so that (require 'comint) will henceforth know that nothing needs to be done.

When require is used at top level in a file, it takes effect when you byte-compile that file (see section Byte Compilation) as well as when you load it. This is in case the required package contains macros that the byte compiler must know about.

Although top-level calls to require are evaluated during byte compilation, provide calls are not. Therefore, you can ensure that a file of definitions is loaded before it is byte-compiled by including a provide followed by a require for the same feature, as in the following example.

(provide 'my-feature)  ; Ignored by byte compiler,
                       ;   evaluated by load.
(require 'my-feature)  ; Evaluated by byte compiler.

The compiler ignores the provide, then processes the require by loading the file in question. Loading the file does execute the provide call, so the subsequent require call does nothing when the file is loaded.

Function: provide feature
This function announces that feature is now loaded, or being loaded, into the current Emacs session. This means that the facilities associated with feature are or will be available for other Lisp programs.

The direct effect of calling provide is to add feature to the front of the list features if it is not already in the list. The argument feature must be a symbol. provide returns feature.

features
     => (bar bish)

(provide 'foo)
     => foo
features
     => (foo bar bish)

When a file is loaded to satisfy an autoload, and it stops due to an error in the evaluating its contents, any function definitions or provide calls that occurred during the load are undone. See section Autoload.

Function: require feature &optional filename
This function checks whether feature is present in the current Emacs session (using (featurep feature); see below). The argument feature must be a symbol.

If the feature is not present, then require loads filename with load. If filename is not supplied, then the name of the symbol feature is used as the base file name to load. However, in this case, require insists on finding feature with an added suffix; a file whose name is just feature won't be used.

If loading the file fails to provide feature, require signals an error, `Required feature feature was not provided'.

Function: featurep feature
This function returns t if feature has been provided in the current Emacs session (i.e., if feature is a member of features.)

Variable: features
The value of this variable is a list of symbols that are the features loaded in the current Emacs session. Each symbol was put in this list with a call to provide. The order of the elements in the features list is not significant.

Unloading

You can discard the functions and variables loaded by a library to reclaim memory for other Lisp objects. To do this, use the function unload-feature:

Command: unload-feature feature &optional force
This command unloads the library that provided feature feature. It undefines all functions, macros, and variables defined in that library with defun, defalias, defsubst, defmacro, defconst, defvar, and defcustom. It then restores any autoloads formerly associated with those symbols. (Loading saves these in the autoload property of the symbol.)

Before restoring the previous definitions, unload-feature runs remove-hook to remove functions in the library from certain hooks. These hooks include variables whose names end in `hook' or `-hooks', plus those listed in loadhist-special-hooks. This is to prevent Emacs from ceasing to function because important hooks refer to functions that are no longer defined.

If these measures are not sufficient to prevent malfunction, a library can define an explicit unload hook. If feature-unload-hook is defined, it is run as a normal hook before restoring the previous definitions, instead of the usual hook-removing actions. The unload hook ought to undo all the global state changes made by the library that might cease to work once the library is unloaded.

Ordinarily, unload-feature refuses to unload a library on which other loaded libraries depend. (A library a depends on library b if a contains a require for b.) If the optional argument force is non-nil, dependencies are ignored and you can unload any library.

The unload-feature function is written in Lisp; its actions are based on the variable load-history.

Variable: load-history
This variable's value is an alist connecting library names with the names of functions and variables they define, the features they provide, and the features they require.

Each element is a list and describes one library. The CAR of the list is the name of the library, as a string. The rest of the list is composed of these kinds of objects:

The value of load-history may have one element whose CAR is nil. This element describes definitions made with eval-buffer on a buffer that is not visiting a file.

The command eval-region updates load-history, but does so by adding the symbols defined to the element for the file being visited, rather than replacing that element. See section Eval.

Preloaded libraries don't contribute to load-history.

Variable: loadhist-special-hooks
This variable holds a list of hooks to be scanned before unloading a library, to remove functions defined in the library.

Hooks for Loading

You can ask for code to be executed if and when a particular library is loaded, by calling eval-after-load.

Function: eval-after-load library form
This function arranges to evaluate form at the end of loading the library library, if and when library is loaded. If library is already loaded, it evaluates form right away.

The library name library must exactly match the argument of load. To get the proper results when an installed library is found by searching load-path, you should not include any directory names in library.

An error in form does not undo the load, but does prevent execution of the rest of form.

In general, well-designed Lisp programs should not use this feature. The clean and modular ways to interact with a Lisp library are (1) examine and set the library's variables (those which are meant for outside use), and (2) call the library's functions. If you wish to do (1), you can do it immediately--there is no need to wait for when the library is loaded. To do (2), you must load the library (preferably with require).

But it is OK to use eval-after-load in your personal customizations if you don't feel they must meet the design standards for programs meant for wider use.

Variable: after-load-alist
An alist of expressions to evaluate if and when particular libraries are loaded. Each element looks like this:

(filename forms...)

The function load checks after-load-alist in order to implement eval-after-load.

Byte Compilation

Emacs Lisp has a compiler that translates functions written in Lisp into a special representation called byte-code that can be executed more efficiently. The compiler replaces Lisp function definitions with byte-code. When a byte-code function is called, its definition is evaluated by the byte-code interpreter.

Because the byte-compiled code is evaluated by the byte-code interpreter, instead of being executed directly by the machine's hardware (as true compiled code is), byte-code is completely transportable from machine to machine without recompilation. It is not, however, as fast as true compiled code.

Compiling a Lisp file with the Emacs byte compiler always reads the file as multibyte text, even if Emacs was started with `--unibyte', unless the file specifies otherwise. This is so that compilation gives results compatible with running the same file without compilation. See section Loading Non-ASCII Characters.

In general, any version of Emacs can run byte-compiled code produced by recent earlier versions of Emacs, but the reverse is not true. A major incompatible change was introduced in Emacs version 19.29, and files compiled with versions since that one will definitely not run in earlier versions unless you specify a special option. See section Documentation Strings and Compilation. In addition, the modifier bits in keyboard characters were renumbered in Emacs 19.29; as a result, files compiled in versions before 19.29 will not work in subsequent versions if they contain character constants with modifier bits.

See section Debugging Problems in Compilation, for how to investigate errors occurring in byte compilation.

Performance of Byte-Compiled Code

A byte-compiled function is not as efficient as a primitive function written in C, but runs much faster than the version written in Lisp. Here is an example:

(defun silly-loop (n)
  "Return time before and after N iterations of a loop."
  (let ((t1 (current-time-string)))
    (while (> (setq n (1- n)) 
              0))
    (list t1 (current-time-string))))
=> silly-loop

(silly-loop 100000)
=> ("Fri Mar 18 17:25:57 1994"
    "Fri Mar 18 17:26:28 1994")  ; 31 seconds

(byte-compile 'silly-loop)
=> [Compiled code not shown]

(silly-loop 100000)
=> ("Fri Mar 18 17:26:52 1994"
    "Fri Mar 18 17:26:58 1994")  ; 6 seconds

In this example, the interpreted code required 31 seconds to run, whereas the byte-compiled code required 6 seconds. These results are representative, but actual results will vary greatly.

The Compilation Functions

You can byte-compile an individual function or macro definition with the byte-compile function. You can compile a whole file with byte-compile-file, or several files with byte-recompile-directory or batch-byte-compile.

The byte compiler produces error messages and warnings about each file in a buffer called `*Compile-Log*'. These report things in your program that suggest a problem but are not necessarily erroneous.

Be careful when writing macro calls in files that you may someday byte-compile. Macro calls are expanded when they are compiled, so the macros must already be defined for proper compilation. For more details, see section Macros and Byte Compilation.

Normally, compiling a file does not evaluate the file's contents or load the file. But it does execute any require calls at top level in the file. One way to ensure that necessary macro definitions are available during compilation is to require the file that defines them (see section Features). To avoid loading the macro definition files when someone runs the compiled program, write eval-when-compile around the require calls (see section Evaluation During Compilation).

Function: byte-compile symbol
This function byte-compiles the function definition of symbol, replacing the previous definition with the compiled one. The function definition of symbol must be the actual code for the function; i.e., the compiler does not follow indirection to another symbol. byte-compile returns the new, compiled definition of symbol.

If symbol's definition is a byte-code function object, byte-compile does nothing and returns nil. Lisp records only one function definition for any symbol, and if that is already compiled, non-compiled code is not available anywhere. So there is no way to "compile the same definition again."

(defun factorial (integer)
  "Compute factorial of INTEGER."
  (if (= 1 integer) 1
    (* integer (factorial (1- integer)))))
=> factorial

(byte-compile 'factorial)
=>
#[(integer)
  "^H\301U\203^H^@\301\207\302^H\303^HS!\"\207"
  [integer 1 * factorial]
  4 "Compute factorial of INTEGER."]

The result is a byte-code function object. The string it contains is the actual byte-code; each character in it is an instruction or an operand of an instruction. The vector contains all the constants, variable names and function names used by the function, except for certain primitives that are coded as special instructions.

Command: compile-defun
This command reads the defun containing point, compiles it, and evaluates the result. If you use this on a defun that is actually a function definition, the effect is to install a compiled version of that function.

Command: byte-compile-file filename
This function compiles a file of Lisp code named filename into a file of byte-code. The output file's name is made by changing the `.el' suffix into `.elc'; if filename does not end in `.el', it adds `.elc' to the end of filename.

Compilation works by reading the input file one form at a time. If it is a definition of a function or macro, the compiled function or macro definition is written out. Other forms are batched together, then each batch is compiled, and written so that its compiled code will be executed when the file is read. All comments are discarded when the input file is read.

This command returns t. When called interactively, it prompts for the file name.

% ls -l push*
-rw-r--r--  1 lewis     791 Oct  5 20:31 push.el

(byte-compile-file "~/emacs/push.el")
     => t

% ls -l push*
-rw-r--r--  1 lewis     791 Oct  5 20:31 push.el
-rw-rw-rw-  1 lewis     638 Oct  8 20:25 push.elc

Command: byte-recompile-directory directory flag
This function recompiles every `.el' file in directory that needs recompilation. A file needs recompilation if a `.elc' file exists but is older than the `.el' file.

When a `.el' file has no corresponding `.elc' file, flag says what to do. If it is nil, these files are ignored. If it is non-nil, the user is asked whether to compile each such file.

The returned value of this command is unpredictable.

Function: batch-byte-compile
This function runs byte-compile-file on files specified on the command line. This function must be used only in a batch execution of Emacs, as it kills Emacs on completion. An error in one file does not prevent processing of subsequent files, but no output file will be generated for it, and the Emacs process will terminate with a nonzero status code.

% emacs -batch -f batch-byte-compile *.el

Function: byte-code code-string data-vector max-stack
This function actually interprets byte-code. A byte-compiled function is actually defined with a body that calls byte-code. Don't call this function yourself--only the byte compiler knows how to generate valid calls to this function.

In Emacs version 18, byte-code was always executed by way of a call to the function byte-code. Nowadays, byte-code is usually executed as part of a byte-code function object, and only rarely through an explicit call to byte-code.

Documentation Strings and Compilation

Functions and variables loaded from a byte-compiled file access their documentation strings dynamically from the file whenever needed. This saves space within Emacs, and makes loading faster because the documentation strings themselves need not be processed while loading the file. Actual access to the documentation strings becomes slower as a result, but this normally is not enough to bother users.

Dynamic access to documentation strings does have drawbacks:

If your site installs Emacs following the usual procedures, these problems will never normally occur. Installing a new version uses a new directory with a different name; as long as the old version remains installed, its files will remain unmodified in the places where they are expected to be.

However, if you have built Emacs yourself and use it from the directory where you built it, you will experience this problem occasionally if you edit and recompile Lisp files. When it happens, you can cure the problem by reloading the file after recompiling it.

Byte-compiled files made with recent versions of Emacs (since 19.29) will not load into older versions because the older versions don't support this feature. You can turn off this feature at compile time by setting byte-compile-dynamic-docstrings to nil; then you can compile files that will load into older Emacs versions. You can do this globally, or for one source file by specifying a file-local binding for the variable. One way to do that is by adding this string to the file's first line:

-*-byte-compile-dynamic-docstrings: nil;-*-

Variable: byte-compile-dynamic-docstrings
If this is non-nil, the byte compiler generates compiled files that are set up for dynamic loading of documentation strings.

The dynamic documentation string feature writes compiled files that use a special Lisp reader construct, `#@count'. This construct skips the next count characters. It also uses the `#$' construct, which stands for "the name of this file, as a string." It is usually best not to use these constructs in Lisp source files, since they are not designed to be clear to humans reading the file.

Dynamic Loading of Individual Functions

When you compile a file, you can optionally enable the dynamic function loading feature (also known as lazy loading). With dynamic function loading, loading the file doesn't fully read the function definitions in the file. Instead, each function definition contains a place-holder which refers to the file. The first time each function is called, it reads the full definition from the file, to replace the place-holder.

The advantage of dynamic function loading is that loading the file becomes much faster. This is a good thing for a file which contains many separate user-callable functions, if using one of them does not imply you will probably also use the rest. A specialized mode which provides many keyboard commands often has that usage pattern: a user may invoke the mode, but use only a few of the commands it provides.

The dynamic loading feature has certain disadvantages:

These problems will never happen in normal circumstances with installed Emacs files. But they are quite likely to happen with Lisp files that you are changing. The easiest way to prevent these problems is to reload the new compiled file immediately after each recompilation.

The byte compiler uses the dynamic function loading feature if the variable byte-compile-dynamic is non-nil at compilation time. Do not set this variable globally, since dynamic loading is desirable only for certain files. Instead, enable the feature for specific source files with file-local variable bindings. For example, you could do it by writing this text in the source file's first line:

-*-byte-compile-dynamic: t;-*-

Variable: byte-compile-dynamic
If this is non-nil, the byte compiler generates compiled files that are set up for dynamic function loading.

Function: fetch-bytecode function
This immediately finishes loading the definition of function from its byte-compiled file, if it is not fully loaded already. The argument function may be a byte-code function object or a function name.

Evaluation During Compilation

These features permit you to write code to be evaluated during compilation of a program.

Special Form: eval-and-compile body
This form marks body to be evaluated both when you compile the containing code and when you run it (whether compiled or not).

You can get a similar result by putting body in a separate file and referring to that file with require. That method is preferable when body is large.

Special Form: eval-when-compile body
This form marks body to be evaluated at compile time but not when the compiled program is loaded. The result of evaluation by the compiler becomes a constant which appears in the compiled program. If you load the source file, rather than compiling it, body is evaluated normally.

Common Lisp Note: At top level, this is analogous to the Common Lisp idiom (eval-when (compile eval) ...). Elsewhere, the Common Lisp `#.' reader macro (but not when interpreting) is closer to what eval-when-compile does.

Byte-Code Function Objects

Byte-compiled functions have a special data type: they are byte-code function objects.

Internally, a byte-code function object is much like a vector; however, the evaluator handles this data type specially when it appears as a function to be called. The printed representation for a byte-code function object is like that for a vector, with an additional `#' before the opening `['.

A byte-code function object must have at least four elements; there is no maximum number, but only the first six elements have any normal use. They are:

arglist
The list of argument symbols.
byte-code
The string containing the byte-code instructions.
constants
The vector of Lisp objects referenced by the byte code. These include symbols used as function names and variable names.
stacksize
The maximum stack size this function needs.
docstring
The documentation string (if any); otherwise, nil. The value may be a number or a list, in case the documentation string is stored in a file. Use the function documentation to get the real documentation string (see section Access to Documentation Strings).
interactive
The interactive spec (if any). This can be a string or a Lisp expression. It is nil for a function that isn't interactive.

Here's an example of a byte-code function object, in printed representation. It is the definition of the command backward-sexp.

#[(&optional arg)
  "^H\204^F^@\301^P\302^H[!\207"
  [arg 1 forward-sexp]
  2
  254435
  "p"]

The primitive way to create a byte-code object is with make-byte-code:

Function: make-byte-code &rest elements
This function constructs and returns a byte-code function object with elements as its elements.

You should not try to come up with the elements for a byte-code function yourself, because if they are inconsistent, Emacs may crash when you call the function. Always leave it to the byte compiler to create these objects; it makes the elements consistent (we hope).

You can access the elements of a byte-code object using aref; you can also use vconcat to create a vector with the same elements.

Disassembled Byte-Code

People do not write byte-code; that job is left to the byte compiler. But we provide a disassembler to satisfy a cat-like curiosity. The disassembler converts the byte-compiled code into humanly readable form.

The byte-code interpreter is implemented as a simple stack machine. It pushes values onto a stack of its own, then pops them off to use them in calculations whose results are themselves pushed back on the stack. When a byte-code function returns, it pops a value off the stack and returns it as the value of the function.

In addition to the stack, byte-code functions can use, bind, and set ordinary Lisp variables, by transferring values between variables and the stack.

Command: disassemble object &optional stream
This function prints the disassembled code for object. If stream is supplied, then output goes there. Otherwise, the disassembled code is printed to the stream standard-output. The argument object can be a function name or a lambda expression.

As a special exception, if this function is used interactively, it outputs to a buffer named `*Disassemble*'.

Here are two examples of using the disassemble function. We have added explanatory comments to help you relate the byte-code to the Lisp source; these do not appear in the output of disassemble. These examples show unoptimized byte-code. Nowadays byte-code is usually optimized, but we did not want to rewrite these examples, since they still serve their purpose.

(defun factorial (integer)
  "Compute factorial of an integer."
  (if (= 1 integer) 1
    (* integer (factorial (1- integer)))))
     => factorial

(factorial 4)
     => 24

(disassemble 'factorial)
     -| byte-code for factorial:
 doc: Compute factorial of an integer.
 args: (integer)

0   constant 1              ; Push 1 onto stack.

1   varref   integer        ; Get value of integer 
                            ;   from the environment
                            ;   and push the value
                            ;   onto the stack.

2   eqlsign                 ; Pop top two values off stack,
                            ;   compare them,
                            ;   and push result onto stack.

3   goto-if-nil 10          ; Pop and test top of stack;
                            ;   if nil, go to 10,
                            ;   else continue.

6   constant 1              ; Push 1 onto top of stack.

7   goto     17             ; Go to 17 (in this case, 1 will be
                            ;   returned by the function).

10  constant *              ; Push symbol * onto stack.

11  varref   integer        ; Push value of integer onto stack.

12  constant factorial      ; Push factorial onto stack.

13  varref   integer        ; Push value of integer onto stack.

14  sub1                    ; Pop integer, decrement value,
                            ;   push new value onto stack.

                            ; Stack now contains:
                            ;   - decremented value of integer
                            ;   - factorial 
                            ;   - value of integer
                            ;   - *

15  call     1              ; Call function factorial using
                            ;   the first (i.e., the top) element
                            ;   of the stack as the argument;
                            ;   push returned value onto stack.

                            ; Stack now contains:
                            ;   - result of recursive
                            ;        call to factorial
                            ;   - value of integer
                            ;   - *

16  call     2              ; Using the first two
                            ;   (i.e., the top two)
                            ;   elements of the stack
                            ;   as arguments,
                            ;   call the function *,
                            ;   pushing the result onto the stack.

17  return                  ; Return the top element
                            ;   of the stack.
     => nil

The silly-loop function is somewhat more complex:

(defun silly-loop (n)
  "Return time before and after N iterations of a loop."
  (let ((t1 (current-time-string)))
    (while (> (setq n (1- n)) 
              0))
    (list t1 (current-time-string))))
     => silly-loop

(disassemble 'silly-loop)
     -| byte-code for silly-loop:
 doc: Return time before and after N iterations of a loop.
 args: (n)

0   constant current-time-string  ; Push
                                  ;   current-time-string
                                  ;   onto top of stack.

1   call     0              ; Call current-time-string
                            ;    with no argument,
                            ;    pushing result onto stack.

2   varbind  t1             ; Pop stack and bind t1
                            ;   to popped value.

3   varref   n              ; Get value of n from
                            ;   the environment and push
                            ;   the value onto the stack.

4   sub1                    ; Subtract 1 from top of stack.

5   dup                     ; Duplicate the top of the stack;
                            ;   i.e., copy the top of
                            ;   the stack and push the
                            ;   copy onto the stack.

6   varset   n              ; Pop the top of the stack,
                            ;   and bind n to the value.

                            ; In effect, the sequence dup varset
                            ;   copies the top of the stack
                            ;   into the value of n
                            ;   without popping it.

7   constant 0              ; Push 0 onto stack.

8   gtr                     ; Pop top two values off stack,
                            ;   test if n is greater than 0
                            ;   and push result onto stack.

9   goto-if-nil-else-pop 17 ; Goto 17 if n <= 0
                            ;   (this exits the while loop).
                            ;   else pop top of stack
                            ;   and continue

12  constant nil            ; Push nil onto stack
                            ;   (this is the body of the loop).

13  discard                 ; Discard result of the body
                            ;   of the loop (a while loop
                            ;   is always evaluated for
                            ;   its side effects).

14  goto     3              ; Jump back to beginning
                            ;   of while loop.

17  discard                 ; Discard result of while loop
                            ;   by popping top of stack.
                            ;   This result is the value nil that
                            ;   was not popped by the goto at 9.

18  varref   t1             ; Push value of t1 onto stack.

19  constant current-time-string  ; Push 
                                  ;   current-time-string
                                  ;   onto top of stack.

20  call     0              ; Call current-time-string again.

21  list2                   ; Pop top two elements off stack,
                            ;   create a list of them,
                            ;   and push list onto stack.

22  unbind   1              ; Unbind t1 in local environment.

23  return                  ; Return value of the top of stack.

     => nil

Advising Emacs Lisp Functions

The advice feature lets you add to the existing definition of a function, by advising the function. This is a clean method for a library to customize functions defined by other parts of Emacs--cleaner than redefining the whole function.

Each function can have multiple pieces of advice, separately defined. Each defined piece of advice can be enabled or disabled explicitly. The enabled pieces of advice for any given function actually take effect when you activate advice for that function, or when that function is subsequently defined or redefined.

Usage Note: Advice is useful for altering the behavior of existing calls to an existing function. If you want the new behavior for new calls, or for key bindings, it is cleaner to define a new function (or a new command) which uses the existing function.

A Simple Advice Example

The command next-line moves point down vertically one or more lines; it is the standard binding of C-n. When used on the last line of the buffer, this command inserts a newline to create a line to move to (if next-line-add-newlines is non-nil).

Suppose you wanted to add a similar feature to previous-line, which would insert a new line at the beginning of the buffer for the command to move to. How could you do this?

You could do it by redefining the whole function, but that is not modular. The advice feature provides a cleaner alternative: you can effectively add your code to the existing function definition, without actually changing or even seeing that definition. Here is how to do this:

(defadvice previous-line (before next-line-at-end (arg))
  "Insert an empty line when moving up from the top line."
  (if (and next-line-add-newlines (= arg 1)
           (save-excursion (beginning-of-line) (bobp)))
      (progn
        (beginning-of-line)
        (newline))))

This expression defines a piece of advice for the function previous-line. This piece of advice is named next-line-at-end, and the symbol before says that it is before-advice which should run before the regular definition of previous-line. (arg) specifies how the advice code can refer to the function's arguments.

When this piece of advice runs, it creates an additional line, in the situation where that is appropriate, but does not move point to that line. This is the correct way to write the advice, because the normal definition will run afterward and will move back to the newly inserted line.

Defining the advice doesn't immediately change the function previous-line. That happens when you activate the advice, like this:

(ad-activate 'previous-line)

This is what actually begins to use the advice that has been defined so far for the function previous-line. Henceforth, whenever that function is run, whether invoked by the user with C-p or M-x, or called from Lisp, it runs the advice first, and its regular definition second.

This example illustrates before-advice, which is one class of advice: it runs before the function's base definition. There are two other advice classes: after-advice, which runs after the base definition, and around-advice, which lets you specify an expression to wrap around the invocation of the base definition.

Defining Advice

To define a piece of advice, use the macro defadvice. A call to defadvice has the following syntax, which is based on the syntax of defun and defmacro, but adds more:

(defadvice function (class name
                         [position] [arglist]
                         flags...)
  [documentation-string]
  [interactive-form]
  body-forms...)

Here, function is the name of the function (or macro or special form) to be advised. From now on, we will write just "function" when describing the entity being advised, but this always includes macros and special forms.

class specifies the class of the advice--one of before, after, or around. Before-advice runs before the function itself; after-advice runs after the function itself; around-advice is wrapped around the execution of the function itself. After-advice and around-advice can override the return value by setting ad-return-value.

Variable: ad-return-value
While advice is executing, after the function's original definition has been executed, this variable holds its return value, which will ultimately be returned to the caller after finishing all the advice. After-advice and around-advice can arrange to return some other value by storing it in this variable.

The argument name is the name of the advice, a non-nil symbol. The advice name uniquely identifies one piece of advice, within all the pieces of advice in a particular class for a particular function. The name allows you to refer to the piece of advice--to redefine it, or to enable or disable it.

In place of the argument list in an ordinary definition, an advice definition calls for several different pieces of information.

The optional position specifies where, in the current list of advice of the specified class, this new advice should be placed. It should be either first, last or a number that specifies a zero-based position (first is equivalent to 0). If no position is specified, the default is first. Position values outside the range of existing positions in this class are mapped to the beginning or the end of the range, whichever is closer. The position value is ignored when redefining an existing piece of advice.

The optional arglist can be used to define the argument list for the sake of advice. This becomes the argument list of the combined definition that is generated in order to run the advice (see section The Combined Definition). Therefore, the advice expressions can use the argument variables in this list to access argument values.

This argument list must be compatible with the argument list of the original function, so that it can handle the ways the function is actually called. If more than one piece of advice specifies an argument list, then the first one (the one with the smallest position) found in the list of all classes of advice is used.

The remaining elements, flags, are symbols that specify further information about how to use this piece of advice. Here are the valid symbols and their meanings:

activate
Activate the advice for function now. Changes in a function's advice always take effect the next time you activate advice for the function; this flag says to do so, for function, immediately after defining this piece of advice. This flag has no effect if function itself is not defined yet (a situation known as forward advice), because it is impossible to activate an undefined function's advice. However, defining function will automatically activate its advice.
protect
Protect this piece of advice against non-local exits and errors in preceding code and advice. Protecting advice places it as a cleanup in an unwind-protect form, so that it will execute even if the previous code gets an error or uses throw. See section Cleaning Up from Nonlocal Exits.
compile
Compile the combined definition that is used to run the advice. This flag is ignored unless activate is also specified. See section The Combined Definition.
disable
Initially disable this piece of advice, so that it will not be used unless subsequently explicitly enabled. See section Enabling and Disabling Advice.
preactivate
Activate advice for function when this defadvice is compiled or macroexpanded. This generates a compiled advised definition according to the current advice state, which will be used during activation if appropriate. This is useful only if this defadvice is byte-compiled.

The optional documentation-string serves to document this piece of advice. When advice is active for function, the documentation for function (as returned by documentation) combines the documentation strings of all the advice for function with the documentation string of its original function definition.

The optional interactive-form form can be supplied to change the interactive behavior of the original function. If more than one piece of advice has an interactive-form, then the first one (the one with the smallest position) found among all the advice takes precedence.

The possibly empty list of body-forms specifies the body of the advice. The body of an advice can access or change the arguments, the return value, the binding environment, and perform any other kind of side effect.

Warning: When you advise a macro, keep in mind that macros are expanded when a program is compiled, not when a compiled program is run. All subroutines used by the advice need to be available when the byte compiler expands the macro.

Around-Advice

Around-advice lets you "wrap" a Lisp expression "around" the original function definition. You specify where the original function definition should go by means of the special symbol ad-do-it. Where this symbol occurs inside the around-advice body, it is replaced with a progn containing the forms of the surrounded code. Here is an example:

(defadvice foo (around foo-around)
  "Ignore case in `foo'."
  (let ((case-fold-search t))
    ad-do-it))

Its effect is to make sure that case is ignored in searches when the original definition of foo is run.

Variable: ad-do-it
This is not really a variable, but it is somewhat used like one in around-advice. It specifies the place to run the function's original definition and other "earlier" around-advice.

If the around-advice does not use ad-do-it, then it does not run the original function definition. This provides a way to override the original definition completely. (It also overrides lower-positioned pieces of around-advice).

Computed Advice

The macro defadvice resembles defun in that the code for the advice, and all other information about it, are explicitly stated in the source code. You can also create advice whose details are computed, using the function ad-add-advice.

Function: ad-add-advice function advice class position
Calling ad-add-advice adds advice as a piece of advice to function in class class. The argument advice has this form:

(name protected enabled definition)

Here protected and enabled are flags, and definition is the expression that says what the advice should do. If enabled is nil, this piece of advice is initially disabled (see section Enabling and Disabling Advice).

If function already has one or more pieces of advice in the specified class, then position specifies where in the list to put the new piece of advice. The value of position can either be first, last, or a number (counting from 0 at the beginning of the list). Numbers outside the range are mapped to the closest extreme position.

If function already has a piece of advice with the same name, then the position argument is ignored and the old advice is replaced with the new one.

Activation of Advice

By default, advice does not take effect when you define it--only when you activate advice for the function that was advised. You can request the activation of advice for a function when you define the advice, by specifying the activate flag in the defadvice. But normally you activate the advice for a function by calling the function ad-activate or one of the other activation commands listed below.

Separating the activation of advice from the act of defining it permits you to add several pieces of advice to one function efficiently, without redefining the function over and over as each advice is added. More importantly, it permits defining advice for a function before that function is actually defined.

When a function's advice is first activated, the function's original definition is saved, and all enabled pieces of advice for that function are combined with the original definition to make a new definition. (Pieces of advice that are currently disabled are not used; see section Enabling and Disabling Advice.) This definition is installed, and optionally byte-compiled as well, depending on conditions described below.

In all of the commands to activate advice, if compile is t, the command also compiles the combined definition which implements the advice.

Command: ad-activate function &optional compile
This command activates the advice for function.

To activate advice for a function whose advice is already active is not a no-op. It is a useful operation which puts into effect any changes in that function's advice since the previous activation of advice for that function.

Command: ad-deactivate function
This command deactivates the advice for function.

Command: ad-activate-all &optional compile
This command activates the advice for all functions.

Command: ad-deactivate-all
This command deactivates the advice for all functions.

Command: ad-activate-regexp regexp &optional compile
This command activates all pieces of advice whose names match regexp. More precisely, it activates all advice for any function which has at least one piece of advice that matches regexp.

Command: ad-deactivate-regexp regexp
This command deactivates all pieces of advice whose names match regexp. More precisely, it deactivates all advice for any function which has at least one piece of advice that matches regexp.

Command: ad-update-regexp regexp &optional compile
This command activates pieces of advice whose names match regexp, but only those for functions whose advice is already activated.

Reactivating a function's advice is useful for putting into effect all the changes that have been made in its advice (including enabling and disabling specific pieces of advice; see section Enabling and Disabling Advice) since the last time it was activated.

Command: ad-start-advice
Turn on automatic advice activation when a function is defined or redefined. If you turn on this mode, then advice really does take effect immediately when defined.

Command: ad-stop-advice
Turn off automatic advice activation when a function is defined or redefined.

User Option: ad-default-compilation-action
This variable controls whether to compile the combined definition that results from activating advice for a function.

If the advised definition was constructed during "preactivation" (see section Preactivation), then that definition must already be compiled, because it was constructed during byte-compilation of the file that contained the defadvice with the preactivate flag.

Enabling and Disabling Advice

Each piece of advice has a flag that says whether it is enabled or not. By enabling or disabling a piece of advice, you can turn it on and off without having to undefine and redefine it. For example, here is how to disable a particular piece of advice named my-advice for the function foo:

(ad-disable-advice 'foo 'before 'my-advice)

This function by itself only changes the enable flag for a piece of advice. To make the change take effect in the advised definition, you must activate the advice for foo again:

(ad-activate 'foo)

Command: ad-disable-advice function class name
This command disables the piece of advice named name in class class on function.

Command: ad-enable-advice function class name
This command enables the piece of advice named name in class class on function.

You can also disable many pieces of advice at once, for various functions, using a regular expression. As always, the changes take real effect only when you next reactivate advice for the functions in question.

Command: ad-disable-regexp regexp
This command disables all pieces of advice whose names match regexp, in all classes, on all functions.

Command: ad-enable-regexp regexp
This command enables all pieces of advice whose names match regexp, in all classes, on all functions.

Preactivation

Constructing a combined definition to execute advice is moderately expensive. When a library advises many functions, this can make loading the library slow. In that case, you can use preactivation to construct suitable combined definitions in advance.

To use preactivation, specify the preactivate flag when you define the advice with defadvice. This defadvice call creates a combined definition which embodies this piece of advice (whether enabled or not) plus any other currently enabled advice for the same function, and the function's own definition. If the defadvice is compiled, that compiles the combined definition also.

When the function's advice is subsequently activated, if the enabled advice for the function matches what was used to make this combined definition, then the existing combined definition is used, thus avoiding the need to construct one. Thus, preactivation never causes wrong results--but it may fail to do any good, if the enabled advice at the time of activation doesn't match what was used for preactivation.

Here are some symptoms that can indicate that a preactivation did not work properly, because of a mismatch.

Compiled preactivated advice works properly even if the function itself is not defined until later; however, the function needs to be defined when you compile the preactivated advice.

There is no elegant way to find out why preactivated advice is not being used. What you can do is to trace the function ad-cache-id-verification-code (with the function trace-function-background) before the advised function's advice is activated. After activation, check the value returned by ad-cache-id-verification-code for that function: verified means that the preactivated advice was used, while other values give some information about why they were considered inappropriate.

Warning: There is one known case that can make preactivation fail, in that a preconstructed combined definition is used even though it fails to match the current state of advice. This can happen when two packages define different pieces of advice with the same name, in the same class, for the same function. But you should avoid that anyway.

Argument Access in Advice

The simplest way to access the arguments of an advised function in the body of a piece of advice is to use the same names that the function definition uses. To do this, you need to know the names of the argument variables of the original function.

While this simple method is sufficient in many cases, it has a disadvantage: it is not robust, because it hard-codes the argument names into the advice. If the definition of the original function changes, the advice might break.

Another method is to specify an argument list in the advice itself. This avoids the need to know the original function definition's argument names, but it has a limitation: all the advice on any particular function must use the same argument list, because the argument list actually used for all the advice comes from the first piece of advice for that function.

A more robust method is to use macros that are translated into the proper access forms at activation time, i.e., when constructing the advised definition. Access macros access actual arguments by position regardless of how these actual arguments get distributed onto the argument variables of a function. This is robust because in Emacs Lisp the meaning of an argument is strictly determined by its position in the argument list.

Macro: ad-get-arg position
This returns the actual argument that was supplied at position.

Macro: ad-get-args position
This returns the list of actual arguments supplied starting at position.

Macro: ad-set-arg position value
This sets the value of the actual argument at position to value

Macro: ad-set-args position value-list
This sets the list of actual arguments starting at position to value-list.

Now an example. Suppose the function foo is defined as

(defun foo (x y &optional z &rest r) ...)

and is then called with

(foo 0 1 2 3 4 5 6)

which means that x is 0, y is 1, z is 2 and r is (3 4 5 6) within the body of foo. Here is what ad-get-arg and ad-get-args return in this case:

(ad-get-arg 0) => 0
(ad-get-arg 1) => 1
(ad-get-arg 2) => 2
(ad-get-arg 3) => 3
(ad-get-args 2) => (2 3 4 5 6)
(ad-get-args 4) => (4 5 6)

Setting arguments also makes sense in this example:

(ad-set-arg 5 "five")

has the effect of changing the sixth argument to "five". If this happens in advice executed before the body of foo is run, then r will be (3 4 "five" 6) within that body.

Here is an example of setting a tail of the argument list:

(ad-set-args 0 '(5 4 3 2 1 0))

If this happens in advice executed before the body of foo is run, then within that body, x will be 5, y will be 4, z will be 3, and r will be (2 1 0) inside the body of foo.

These argument constructs are not really implemented as Lisp macros. Instead they are implemented specially by the advice mechanism.

Definition of Subr Argument Lists

When the advice facility constructs the combined definition, it needs to know the argument list of the original function. This is not always possible for primitive functions. When advice cannot determine the argument list, it uses (&rest ad-subr-args), which always works but is inefficient because it constructs a list of the argument values. You can use ad-define-subr-args to declare the proper argument names for a primitive function:

Function: ad-define-subr-args function arglist
This function specifies that arglist should be used as the argument list for function function.

For example,

(ad-define-subr-args 'fset '(sym newdef))

specifies the argument list for the function fset.

The Combined Definition

Suppose that a function has n pieces of before-advice, m pieces of around-advice and k pieces of after-advice. Assuming no piece of advice is protected, the combined definition produced to implement the advice for a function looks like this:

(lambda arglist
  [ [advised-docstring] [(interactive ...)] ]
  (let (ad-return-value)
    before-0-body-form...
         ....
    before-n-1-body-form...
    around-0-body-form...
       around-1-body-form...
             ....
          around-m-1-body-form...
             (setq ad-return-value
                   apply original definition to arglist)
          other-around-m-1-body-form...
             ....
       other-around-1-body-form...
    other-around-0-body-form...
    after-0-body-form...
          ....
    after-k-1-body-form...
    ad-return-value))

Macros are redefined as macros, which means adding macro to the beginning of the combined definition.

The interactive form is present if the original function or some piece of advice specifies one. When an interactive primitive function is advised, a special method is used: to call the primitive with call-interactively so that it will read its own arguments. In this case, the advice cannot access the arguments.

The body forms of the various advice in each class are assembled according to their specified order. The forms of around-advice l are included in one of the forms of around-advice l - 1.

The innermost part of the around advice onion is

apply original definition to arglist

whose form depends on the type of the original function. The variable ad-return-value is set to whatever this returns. The variable is visible to all pieces of advice, which can access and modify it before it is actually returned from the advised function.

The semantic structure of advised functions that contain protected pieces of advice is the same. The only difference is that unwind-protect forms ensure that the protected advice gets executed even if some previous piece of advice had an error or a non-local exit. If any around-advice is protected, then the whole around-advice onion is protected as a result.

Debugging Lisp Programs

There are three ways to investigate a problem in an Emacs Lisp program, depending on what you are doing with the program when the problem appears.

Another useful debugging tool is the dribble file. When a dribble file is open, Emacs copies all keyboard input characters to that file. Afterward, you can examine the file to find out what input was used. See section Terminal Input.

For debugging problems in terminal descriptions, the open-termscript function can be useful. See section Terminal Output.

The Lisp Debugger

The ordinary Lisp debugger provides the ability to suspend evaluation of a form. While evaluation is suspended (a state that is commonly known as a break), you may examine the run time stack, examine the values of local or global variables, or change those values. Since a break is a recursive edit, all the usual editing facilities of Emacs are available; you can even run programs that will enter the debugger recursively. See section Recursive Editing.

Entering the Debugger on an Error

The most important time to enter the debugger is when a Lisp error happens. This allows you to investigate the immediate causes of the error.

However, entry to the debugger is not a normal consequence of an error. Many commands frequently cause Lisp errors when invoked inappropriately (such as C-f at the end of the buffer), and during ordinary editing it would be very inconvenient to enter the debugger each time this happens. So if you want errors to enter the debugger, set the variable debug-on-error to non-nil. (The command toggle-debug-on-error provides an easy way to do this.)

User Option: debug-on-error
This variable determines whether the debugger is called when an error is signaled and not handled. If debug-on-error is t, all kinds of errors call the debugger (except those listed in debug-ignored-errors). If it is nil, none call the debugger.

The value can also be a list of error conditions that should call the debugger. For example, if you set it to the list (void-variable), then only errors about a variable that has no value invoke the debugger.

When this variable is non-nil, Emacs does not create an error handler around process filter functions and sentinels. Therefore, errors in these functions also invoke the debugger. See section Processes.

User Option: debug-ignored-errors
This variable specifies certain kinds of errors that should not enter the debugger. Its value is a list of error condition symbols and/or regular expressions. If the error has any of those condition symbols, or if the error message matches any of the regular expressions, then that error does not enter the debugger, regardless of the value of debug-on-error.

The normal value of this variable lists several errors that happen often during editing but rarely result from bugs in Lisp programs. However, "rarely" is not "never"; if your program fails with an error that matches this list, you will need to change this list in order to debug the error. The easiest way is usually to set debug-ignored-errors to nil.

User Option: debug-on-signal
Normally, errors that are caught by condition-case never run the debugger, even if debug-on-error is non-nil. In other words, condition-case gets a chance to handle the error before the debugger gets a chance.

If you set debug-on-signal to a non-nil value, then the debugger gets the first chance at every error; an error will invoke the debugger regardless of any condition-case, if it fits the criteria specified by the values of debug-on-error and debug-ignored-errors.

Warning: This variable is strong medicine! Various parts of Emacs handle errors in the normal course of affairs, and you may not even realize that errors happen there. If you set debug-on-signal to a non-nil value, those errors will enter the debugger.

Warning: debug-on-signal has no effect when debug-on-error is nil.

To debug an error that happens during loading of the `.emacs' file, use the option `--debug-init', which binds debug-on-error to t while loading `.emacs', and bypasses the condition-case which normally catches errors in the init file.

If your `.emacs' file sets debug-on-error, the effect may not last past the end of loading `.emacs'. (This is an undesirable byproduct of the code that implements the `--debug-init' command line option.) The best way to make `.emacs' set debug-on-error permanently is with after-init-hook, like this:

(add-hook 'after-init-hook
          '(lambda () (setq debug-on-error t)))

Debugging Infinite Loops

When a program loops infinitely and fails to return, your first problem is to stop the loop. On most operating systems, you can do this with C-g, which causes quit.

Ordinary quitting gives no information about why the program was looping. To get more information, you can set the variable debug-on-quit to non-nil. Quitting with C-g is not considered an error, and debug-on-error has no effect on the handling of C-g. Likewise, debug-on-quit has no effect on errors.

Once you have the debugger running in the middle of the infinite loop, you can proceed from the debugger using the stepping commands. If you step through the entire loop, you will probably get enough information to solve the problem.

User Option: debug-on-quit
This variable determines whether the debugger is called when quit is signaled and not handled. If debug-on-quit is non-nil, then the debugger is called whenever you quit (that is, type C-g). If debug-on-quit is nil, then the debugger is not called when you quit. See section Quitting.

Entering the Debugger on a Function Call

To investigate a problem that happens in the middle of a program, one useful technique is to enter the debugger whenever a certain function is called. You can do this to the function in which the problem occurs, and then step through the function, or you can do this to a function called shortly before the problem, step quickly over the call to that function, and then step through its caller.

Command: debug-on-entry function-name
This function requests function-name to invoke the debugger each time it is called. It works by inserting the form (debug 'debug) into the function definition as the first form.

Any function defined as Lisp code may be set to break on entry, regardless of whether it is interpreted code or compiled code. If the function is a command, it will enter the debugger when called from Lisp and when called interactively (after the reading of the arguments). You can't debug primitive functions (i.e., those written in C) this way.

When debug-on-entry is called interactively, it prompts for function-name in the minibuffer. If the function is already set up to invoke the debugger on entry, debug-on-entry does nothing. debug-on-entry always returns function-name.

Note: if you redefine a function after using debug-on-entry on it, the code to enter the debugger is discarded by the redefinition. In effect, redefining the function cancels the break-on-entry feature for that function.

(defun fact (n)
  (if (zerop n) 1
      (* n (fact (1- n)))))
     => fact
(debug-on-entry 'fact)
     => fact
(fact 3)

------ Buffer: *Backtrace* ------
Entering:
* fact(3)
  eval-region(4870 4878 t)
  byte-code("...")
  eval-last-sexp(nil)
  (let ...)
  eval-insert-last-sexp(nil)
* call-interactively(eval-insert-last-sexp)
------ Buffer: *Backtrace* ------

(symbol-function 'fact)
     => (lambda (n)
          (debug (quote debug))
          (if (zerop n) 1 (* n (fact (1- n)))))

Command: cancel-debug-on-entry function-name
This function undoes the effect of debug-on-entry on function-name. When called interactively, it prompts for function-name in the minibuffer. If function-name is nil or the empty string, it cancels break-on-entry for all functions.

Calling cancel-debug-on-entry does nothing to a function which is not currently set up to break on entry. It always returns function-name.

Explicit Entry to the Debugger

You can cause the debugger to be called at a certain point in your program by writing the expression (debug) at that point. To do this, visit the source file, insert the text `(debug)' at the proper place, and type C-M-x. Warning: if you do this for temporary debugging purposes, be sure to undo this insertion before you save the file!

The place where you insert `(debug)' must be a place where an additional form can be evaluated and its value ignored. (If the value of (debug) isn't ignored, it will alter the execution of the program!) The most common suitable places are inside a progn or an implicit progn (see section Sequencing).

Using the Debugger

When the debugger is entered, it displays the previously selected buffer in one window and a buffer named `*Backtrace*' in another window. The backtrace buffer contains one line for each level of Lisp function execution currently going on. At the beginning of this buffer is a message describing the reason that the debugger was invoked (such as the error message and associated data, if it was invoked due to an error).

The backtrace buffer is read-only and uses a special major mode, Debugger mode, in which letters are defined as debugger commands. The usual Emacs editing commands are available; thus, you can switch windows to examine the buffer that was being edited at the time of the error, switch buffers, visit files, or do any other sort of editing. However, the debugger is a recursive editing level (see section Recursive Editing) and it is wise to go back to the backtrace buffer and exit the debugger (with the q command) when you are finished with it. Exiting the debugger gets out of the recursive edit and kills the backtrace buffer.

The backtrace buffer shows you the functions that are executing and their argument values. It also allows you to specify a stack frame by moving point to the line describing that frame. (A stack frame is the place where the Lisp interpreter records information about a particular invocation of a function.) The frame whose line point is on is considered the current frame. Some of the debugger commands operate on the current frame.

The debugger itself must be run byte-compiled, since it makes assumptions about how many stack frames are used for the debugger itself. These assumptions are false if the debugger is running interpreted.

Debugger Commands

Inside the debugger (in Debugger mode), these special commands are available in addition to the usual cursor motion commands. (Keep in mind that all the usual facilities of Emacs, such as switching windows or buffers, are still available.)

The most important use of debugger commands is for stepping through code, so that you can see how control flows. The debugger can step through the control structures of an interpreted function, but cannot do so in a byte-compiled function. If you would like to step through a byte-compiled function, replace it with an interpreted definition of the same function. (To do this, visit the source for the function and type C-M-x on its definition.)

Here is a list of Debugger mode commands:

c
Exit the debugger and continue execution. When continuing is possible, it resumes execution of the program as if the debugger had never been entered (aside from any side-effects that you caused by changing variable values or data structures while inside the debugger). Continuing is possible after entry to the debugger due to function entry or exit, explicit invocation, or quitting. You cannot continue if the debugger was entered because of an error.
d
Continue execution, but enter the debugger the next time any Lisp function is called. This allows you to step through the subexpressions of an expression, seeing what values the subexpressions compute, and what else they do. The stack frame made for the function call which enters the debugger in this way will be flagged automatically so that the debugger will be called again when the frame is exited. You can use the u command to cancel this flag.
b
Flag the current frame so that the debugger will be entered when the frame is exited. Frames flagged in this way are marked with stars in the backtrace buffer.
u
Don't enter the debugger when the current frame is exited. This cancels a b command on that frame. The visible effect is to remove the star from the line in the backtrace buffer.
e
Read a Lisp expression in the minibuffer, evaluate it, and print the value in the echo area. The debugger alters certain important variables, and the current buffer, as part of its operation; e temporarily restores their values from outside the debugger, so you can examine and change them. This makes the debugger more transparent. By contrast, M-: does nothing special in the debugger; it shows you the variable values within the debugger.
R
Like e, but also save the result of evaluation in the buffer `*Debugger-record*'.
q
Terminate the program being debugged; return to top-level Emacs command execution. If the debugger was entered due to a C-g but you really want to quit, and not debug, use the q command.
r
Return a value from the debugger. The value is computed by reading an expression with the minibuffer and evaluating it. The r command is useful when the debugger was invoked due to exit from a Lisp call frame (as requested with b or by entering the frame with d); then the value specified in the r command is used as the value of that frame. It is also useful if you call debug and use its return value. Otherwise, r has the same effect as c, and the specified return value does not matter. You can't use r when the debugger was entered due to an error.

Invoking the Debugger

Here we describe in full detail the function debug that is used to invoke the debugger.

Function: debug &rest debugger-args
This function enters the debugger. It switches buffers to a buffer named `*Backtrace*' (or `*Backtrace*<2>' if it is the second recursive entry to the debugger, etc.), and fills it with information about the stack of Lisp function calls. It then enters a recursive edit, showing the backtrace buffer in Debugger mode.

The Debugger mode c and r commands exit the recursive edit; then debug switches back to the previous buffer and returns to whatever called debug. This is the only way the function debug can return to its caller.

The use of the debugger-args is that debug displays the rest of its arguments at the top of the `*Backtrace*' buffer, so that the user can see them. Except as described below, this is the only way these arguments are used.

However, certain values for first argument to debug have a special significance. (Normally, these values are used only by the internals of Emacs, and not by programmers calling debug.) Here is a table of these special values:

lambda
A first argument of lambda means debug was called because of entry to a function when debug-on-next-call was non-nil. The debugger displays `Entering:' as a line of text at the top of the buffer.
debug
debug as first argument indicates a call to debug because of entry to a function that was set to debug on entry. The debugger displays `Entering:', just as in the lambda case. It also marks the stack frame for that function so that it will invoke the debugger when exited.
t
When the first argument is t, this indicates a call to debug due to evaluation of a list form when debug-on-next-call is non-nil. The debugger displays the following as the top line in the buffer:
Beginning evaluation of function call form:
exit
When the first argument is exit, it indicates the exit of a stack frame previously marked to invoke the debugger on exit. The second argument given to debug in this case is the value being returned from the frame. The debugger displays `Return value:' in the top line of the buffer, followed by the value being returned.
error
When the first argument is error, the debugger indicates that it is being entered because an error or quit was signaled and not handled, by displaying `Signaling:' followed by the error signaled and any arguments to signal. For example,
(let ((debug-on-error t))
  (/ 1 0))

------ Buffer: *Backtrace* ------
Signaling: (arith-error)
  /(1 0)
...
------ Buffer: *Backtrace* ------
If an error was signaled, presumably the variable debug-on-error is non-nil. If quit was signaled, then presumably the variable debug-on-quit is non-nil.
nil
Use nil as the first of the debugger-args when you want to enter the debugger explicitly. The rest of the debugger-args are printed on the top line of the buffer. You can use this feature to display messages--for example, to remind yourself of the conditions under which debug is called.

Internals of the Debugger

This section describes functions and variables used internally by the debugger.

Variable: debugger
The value of this variable is the function to call to invoke the debugger. Its value must be a function of any number of arguments (or, more typically, the name of a function). Presumably this function will enter some kind of debugger. The default value of the variable is debug.

The first argument that Lisp hands to the function indicates why it was called. The convention for arguments is detailed in the description of debug.

Command: backtrace
This function prints a trace of Lisp function calls currently active. This is the function used by debug to fill up the `*Backtrace*' buffer. It is written in C, since it must have access to the stack to determine which function calls are active. The return value is always nil.

In the following example, a Lisp expression calls backtrace explicitly. This prints the backtrace to the stream standard-output: in this case, to the buffer `backtrace-output'. Each line of the backtrace represents one function call. The line shows the values of the function's arguments if they are all known. If they are still being computed, the line says so. The arguments of special forms are elided.

(with-output-to-temp-buffer "backtrace-output"
  (let ((var 1))
    (save-excursion
      (setq var (eval '(progn
                         (1+ var)
                         (list 'testing (backtrace))))))))

     => nil

----------- Buffer: backtrace-output ------------
  backtrace()
  (list ...computing arguments...)
  (progn ...)
  eval((progn (1+ var) (list (quote testing) (backtrace))))
  (setq ...)
  (save-excursion ...)
  (let ...)
  (with-output-to-temp-buffer ...)
  eval-region(1973 2142 #<buffer *scratch*>)
  byte-code("...  for eval-print-last-sexp ...")
  eval-print-last-sexp(nil)
* call-interactively(eval-print-last-sexp)
----------- Buffer: backtrace-output ------------

The character `*' indicates a frame whose debug-on-exit flag is set.

Variable: debug-on-next-call
If this variable is non-nil, it says to call the debugger before the next eval, apply or funcall. Entering the debugger sets debug-on-next-call to nil.

The d command in the debugger works by setting this variable.

Function: backtrace-debug level flag
This function sets the debug-on-exit flag of the stack frame level levels down the stack, giving it the value flag. If flag is non-nil, this will cause the debugger to be entered when that frame later exits. Even a nonlocal exit through that frame will enter the debugger.

This function is used only by the debugger.

Variable: command-debug-status
This variable records the debugging status of the current interactive command. Each time a command is called interactively, this variable is bound to nil. The debugger can set this variable to leave information for future debugger invocations during the same command invocation.

The advantage, for the debugger, of using this variable rather than an ordinary global variable is that the data will never carry over to a subsequent command invocation.

Function: backtrace-frame frame-number
The function backtrace-frame is intended for use in Lisp debuggers. It returns information about what computation is happening in the stack frame frame-number levels down.

If that frame has not evaluated the arguments yet (or is a special form), the value is (nil function arg-forms...).

If that frame has evaluated its arguments and called its function already, the value is (t function arg-values...).

In the return value, function is whatever was supplied as the CAR of the evaluated list, or a lambda expression in the case of a macro call. If the function has a &rest argument, that is represented as the tail of the list arg-values.

If frame-number is out of range, backtrace-frame returns nil.

Edebug

Edebug is a source-level debugger for Emacs Lisp programs with which you can:

The first three sections below should tell you enough about Edebug to enable you to use it.

Using Edebug

To debug a Lisp program with Edebug, you must first instrument the Lisp code that you want to debug. A simple way to do this is to first move point into the definition of a function or macro and then do C-u C-M-x (eval-defun with a prefix argument). See section Instrumenting for Edebug, for alternative ways to instrument code.

Once a function is instrumented, any call to the function activates Edebug. Activating Edebug may stop execution and let you step through the function, or it may update the display and continue execution while checking for debugging commands, depending on which Edebug execution mode you have selected. The default execution mode is step, which does stop execution. See section Edebug Execution Modes.

Within Edebug, you normally view an Emacs buffer showing the source of the Lisp code you are debugging. This is referred to as the source code buffer. This buffer is temporarily read-only.

An arrow at the left margin indicates the line where the function is executing. Point initially shows where within the line the function is executing, but this ceases to be true if you move point yourself.

If you instrument the definition of fac (shown below) and then execute (fac 3), here is what you normally see. Point is at the open-parenthesis before if.

(defun fac (n)
=>-!-(if (< 0 n)
      (* n (fac (1- n)))
    1))

The places within a function where Edebug can stop execution are called stop points. These occur both before and after each subexpression that is a list, and also after each variable reference. Here we show with periods the stop points found in the function fac:

(defun fac (n)
  .(if .(< 0 n.).
      .(* n. .(fac (1- n.).).).
    1).)

The special commands of Edebug are available in the source code buffer in addition to the commands of Emacs Lisp mode. For example, you can type the Edebug command SPC to execute until the next stop point. If you type SPC once after entry to fac, here is the display you will see:

(defun fac (n)
=>(if -!-(< 0 n)
      (* n (fac (1- n)))
    1))

When Edebug stops execution after an expression, it displays the expression's value in the echo area.

Other frequently used commands are b to set a breakpoint at a stop point, g to execute until a breakpoint is reached, and q to exit Edebug and return to the top-level command loop. Type ? to display a list of all Edebug commands.

Instrumenting for Edebug

In order to use Edebug to debug Lisp code, you must first instrument the code. Instrumenting code inserts additional code into it, to invoke Edebug at the proper places.

Once you have loaded Edebug, the command C-M-x (eval-defun) is redefined so that when invoked with a prefix argument on a definition, it instruments the definition before evaluating it. (The source code itself is not modified.) If the variable edebug-all-defs is non-nil, that inverts the meaning of the prefix argument: then C-M-x instruments the definition unless it has a prefix argument. The default value of edebug-all-defs is nil. The command M-x edebug-all-defs toggles the value of the variable edebug-all-defs.

If edebug-all-defs is non-nil, then the commands eval-region, eval-current-buffer, and eval-buffer also instrument any definitions they evaluate. Similarly, edebug-all-forms controls whether eval-region should instrument any form, even non-defining forms. This doesn't apply to loading or evaluations in the minibuffer. The command M-x edebug-all-forms toggles this option.

Another command, M-x edebug-eval-top-level-form, is available to instrument any top-level form regardless of the values of edebug-all-defs and edebug-all-forms.

While Edebug is active, the command I (edebug-instrument-callee) instruments the definition of the function or macro called by the list form after point, if is not already instrumented. This is possible only if Edebug knows where to find the source for that function; after loading Edebug, eval-region records the position of every definition it evaluates, even if not instrumenting it. See also the i command (see section Jumping), which steps into the call after instrumenting the function.

Edebug knows how to instrument all the standard special forms, interactive forms with an expression argument, anonymous lambda expressions, and other defining forms. Edebug cannot know what a user-defined macro will do with the arguments of a macro call, so you must tell it; see section Instrumenting Macro Calls, for details.

When Edebug is about to instrument code for the first time in a session, it runs the hook edebug-setup-hook, then sets it to nil. You can use this to arrange to load Edebug specifications (see section Instrumenting Macro Calls) associated with a package you are using, but actually load them only if you use Edebug.

To remove instrumentation from a definition, simply re-evaluate its definition in a way that does not instrument. There are two ways of evaluating forms that never instrument them: from a file with load, and from the minibuffer with eval-expression (M-:).

If Edebug detects a syntax error while instrumenting, it leaves point at the erroneous code and signals an invalid-read-syntax error.

See section Evaluation, for other evaluation functions available inside of Edebug.

Edebug Execution Modes

Edebug supports several execution modes for running the program you are debugging. We call these alternatives Edebug execution modes; do not confuse them with major or minor modes. The current Edebug execution mode determines how far Edebug continues execution before stopping--whether it stops at each stop point, or continues to the next breakpoint, for example--and how much Edebug displays the progress of the evaluation before it stops.

Normally, you specify the Edebug execution mode by typing a command to continue the program in a certain mode. Here is a table of these commands. All except for S resume execution of the program, at least for a certain distance.

S
Stop: don't execute any more of the program for now, just wait for more Edebug commands (edebug-stop).
SPC
Step: stop at the next stop point encountered (edebug-step-mode).
n
Next: stop at the next stop point encountered after an expression (edebug-next-mode). Also see edebug-forward-sexp in section Miscellaneous Edebug Commands.
t
Trace: pause one second at each Edebug stop point (edebug-trace-mode).
T
Rapid trace: update the display at each stop point, but don't actually pause (edebug-Trace-fast-mode).
g
Go: run until the next breakpoint (edebug-go-mode). See section Breakpoints.
c
Continue: pause one second at each breakpoint, and then continue (edebug-continue-mode).
C
Rapid continue: move point to each breakpoint, but don't pause (edebug-Continue-fast-mode).
G
Go non-stop: ignore breakpoints (edebug-Go-nonstop-mode). You can still stop the program by typing S, or any editing command.

In general, the execution modes earlier in the above list run the program more slowly or stop sooner than the modes later in the list.

While executing or tracing, you can interrupt the execution by typing any Edebug command. Edebug stops the program at the next stop point and then executes the command you typed. For example, typing t during execution switches to trace mode at the next stop point. You can use S to stop execution without doing anything else.

If your function happens to read input, a character you type intending to interrupt execution may be read by the function instead. You can avoid such unintended results by paying attention to when your program wants input.

Keyboard macros containing the commands in this section do not completely work: exiting from Edebug, to resume the program, loses track of the keyboard macro. This is not easy to fix. Also, defining or executing a keyboard macro outside of Edebug does not affect commands inside Edebug. This is usually an advantage. But see the edebug-continue-kbd-macro option (see section Edebug Options).

When you enter a new Edebug level, the initial execution mode comes from the value of the variable edebug-initial-mode. By default, this specifies step mode. Note that you may reenter the same Edebug level several times if, for example, an instrumented function is called several times from one command.

Jumping

The commands described in this section execute until they reach a specified location. All except i make a temporary breakpoint to establish the place to stop, then switch to go mode. Any other breakpoint reached before the intended stop point will also stop execution. See section Breakpoints, for the details on breakpoints.

These commands may fail to work as expected in case of nonlocal exit, because a nonlocal exit can bypass the temporary breakpoint where you expected the program to stop.

h
Proceed to the stop point near where point is (edebug-goto-here).
f
Run the program forward over one expression (edebug-forward-sexp).
o
Run the program until the end of the containing sexp.
i
Step into the function or macro called by the form after point.

The h command proceeds to the stop point near the current location of point, using a temporary breakpoint. See section Breakpoints, for more information about breakpoints.

The f command runs the program forward over one expression. More precisely, it sets a temporary breakpoint at the position that C-M-f would reach, then executes in go mode so that the program will stop at breakpoints.

With a prefix argument n, the temporary breakpoint is placed n sexps beyond point. If the containing list ends before n more elements, then the place to stop is after the containing expression.

Be careful that the position C-M-f finds is a place that the program will really get to; this may not be true in a cond, for example.

The f command does forward-sexp starting at point, rather than at the stop point, for flexibility. If you want to execute one expression from the current stop point, type w first, to move point there, and then type f.

The o command continues "out of" an expression. It places a temporary breakpoint at the end of the sexp containing point. If the containing sexp is a function definition itself, o continues until just before the last sexp in the definition. If that is where you are now, it returns from the function and then stops. In other words, this command does not exit the currently executing function unless you are positioned after the last sexp.

The i command steps into the function or macro called by the list form after point, and stops at its first stop point. Note that the form need not be the one about to be evaluated. But if the form is a function call about to be evaluated, remember to use this command before any of the arguments are evaluated, since otherwise it will be too late.

The i command instruments the function or macro it's supposed to step into, if it isn't instrumented already. This is convenient, but keep in mind that the function or macro remains instrumented unless you explicitly arrange to deinstrument it.

Miscellaneous Edebug Commands

Some miscellaneous Edebug commands are described here.

?
Display the help message for Edebug (edebug-help).
C-]
Abort one level back to the previous command level (abort-recursive-edit).
q
Return to the top level editor command loop (top-level). This exits all recursive editing levels, including all levels of Edebug activity. However, instrumented code protected with unwind-protect or condition-case forms may resume debugging.
Q
Like q but don't stop even for protected code (top-level-nonstop).
r
Redisplay the most recently known expression result in the echo area (edebug-previous-result).
d
Display a backtrace, excluding Edebug's own functions for clarity (edebug-backtrace). You cannot use debugger commands in the backtrace buffer in Edebug as you would in the standard debugger. The backtrace buffer is killed automatically when you continue execution.

From the Edebug recursive edit, you may invoke commands that activate Edebug again recursively. Any time Edebug is active, you can quit to the top level with q or abort one recursive edit level with C-]. You can display a backtrace of all the pending evaluations with d.

Breakpoints

Edebug's step mode stops execution at the next stop point reached. There are three other ways to stop Edebug execution once it has started: breakpoints, the global break condition, and source breakpoints.

While using Edebug, you can specify breakpoints in the program you are testing: points where execution should stop. You can set a breakpoint at any stop point, as defined in section Using Edebug. For setting and unsetting breakpoints, the stop point that is affected is the first one at or after point in the source code buffer. Here are the Edebug commands for breakpoints:

b
Set a breakpoint at the stop point at or after point (edebug-set-breakpoint). If you use a prefix argument, the breakpoint is temporary (it turns off the first time it stops the program).
u
Unset the breakpoint (if any) at the stop point at or after point (edebug-unset-breakpoint).
x condition RET
Set a conditional breakpoint which stops the program only if condition evaluates to a non-nil value (edebug-set-conditional-breakpoint). With a prefix argument, the breakpoint is temporary.
B
Move point to the next breakpoint in the current definition (edebug-next-breakpoint).

While in Edebug, you can set a breakpoint with b and unset one with u. First move point to the Edebug stop point of your choice, then type b or u to set or unset a breakpoint there. Unsetting a breakpoint where none has been set has no effect.

Re-evaluating or reinstrumenting a definition forgets all its breakpoints.

A conditional breakpoint tests a condition each time the program gets there. Any errors that occur as a result of evaluating the condition are ignored, as if the result were nil. To set a conditional breakpoint, use x, and specify the condition expression in the minibuffer. Setting a conditional breakpoint at a stop point that has a previously established conditional breakpoint puts the previous condition expression in the minibuffer so you can edit it.

You can make a conditional or unconditional breakpoint temporary by using a prefix argument with the command to set the breakpoint. When a temporary breakpoint stops the program, it is automatically unset.

Edebug always stops or pauses at a breakpoint except when the Edebug mode is Go-nonstop. In that mode, it ignores breakpoints entirely.

To find out where your breakpoints are, use the B command, which moves point to the next breakpoint following point, within the same function, or to the first breakpoint if there are no following breakpoints. This command does not continue execution--it just moves point in the buffer.

Global Break Condition

A global break condition stops execution when a specified condition is satisfied, no matter where that may occur. Edebug evaluates the global break condition at every stop point. If it evaluates to a non-nil value, then execution stops or pauses depending on the execution mode, as if a breakpoint had been hit. If evaluating the condition gets an error, execution does not stop.

The condition expression is stored in edebug-global-break-condition. You can specify a new expression using the X command (edebug-set-global-break-condition).

The global break condition is the simplest way to find where in your code some event occurs, but it makes code run much more slowly. So you should reset the condition to nil when not using it.

Source Breakpoints

All breakpoints in a definition are forgotten each time you reinstrument it. To make a breakpoint that won't be forgotten, you can write a source breakpoint, which is simply a call to the function edebug in your source code. You can, of course, make such a call conditional. For example, in the fac function, insert the first line as shown below to stop when the argument reaches zero:

(defun fac (n)
  (if (= n 0) (edebug))
  (if (< 0 n)
      (* n (fac (1- n)))
    1))

When the fac definition is instrumented and the function is called, the call to edebug acts as a breakpoint. Depending on the execution mode, Edebug stops or pauses there.

If no instrumented code is being executed when edebug is called, that function calls debug.

Trapping Errors

Emacs normally displays an error message when an error is signaled and not handled with condition-case. While Edebug is active and executing instrumented code, it normally responds to all unhandled errors. You can customize this with the options edebug-on-error and edebug-on-quit; see section Edebug Options.

When Edebug responds to an error, it shows the last stop point encountered before the error. This may be the location of a call to a function which was not instrumented, within which the error actually occurred. For an unbound variable error, the last known stop point might be quite distant from the offending variable reference. In that case you might want to display a full backtrace (see section Miscellaneous Edebug Commands).

If you change debug-on-error or debug-on-quit while Edebug is active, these changes will be forgotten when Edebug becomes inactive. Furthermore, during Edebug's recursive edit, these variables are bound to the values they had outside of Edebug.

Edebug Views

These Edebug commands let you view aspects of the buffer and window status as they were before entry to Edebug. The outside window configuration is the collection of windows and contents that were in effect outside of Edebug.

v
Temporarily view the outside window configuration (edebug-view-outside).
p
Temporarily display the outside current buffer with point at its outside position (edebug-bounce-point). With a prefix argument n, pause for n seconds instead.
w
Move point back to the current stop point in the source code buffer (edebug-where). If you use this command in a different window displaying the same buffer, that window will be used instead to display the current definition in the future.
W
Toggle whether Edebug saves and restores the outside window configuration (edebug-toggle-save-windows). With a prefix argument, W only toggles saving and restoring of the selected window. To specify a window that is not displaying the source code buffer, you must use C-x X W from the global keymap.

You can view the outside window configuration with v or just bounce to the point in the current buffer with p, even if it is not normally displayed. After moving point, you may wish to jump back to the stop point with w from a source code buffer.

Each time you use W to turn saving off, Edebug forgets the saved outside window configuration--so that even if you turn saving back on, the current window configuration remains unchanged when you next exit Edebug (by continuing the program). However, the automatic redisplay of `*edebug*' and `*edebug-trace*' may conflict with the buffers you wish to see unless you have enough windows open.

Evaluation

While within Edebug, you can evaluate expressions "as if" Edebug were not running. Edebug tries to be invisible to the expression's evaluation and printing. Evaluation of expressions that cause side effects will work as expected except for things that Edebug explicitly saves and restores. See section The Outside Context, for details on this process.

e exp RET
Evaluate expression exp in the context outside of Edebug (edebug-eval-expression). That is, Edebug tries to minimize its interference with the evaluation.
M-: exp RET
Evaluate expression exp in the context of Edebug itself.
C-x C-e
Evaluate the expression before point, in the context outside of Edebug (edebug-eval-last-sexp).

Edebug supports evaluation of expressions containing references to lexically bound symbols created by the following constructs in `cl.el' (version 2.03 or later): lexical-let, macrolet, and symbol-macrolet.

Evaluation List Buffer

You can use the evaluation list buffer, called `*edebug*', to evaluate expressions interactively. You can also set up the evaluation list of expressions to be evaluated automatically each time Edebug updates the display.

E
Switch to the evaluation list buffer `*edebug*' (edebug-visit-eval-list).

In the `*edebug*' buffer you can use the commands of Lisp Interaction mode (see section `Lisp Interaction' in The GNU Emacs Manual) as well as these special commands:

C-j
Evaluate the expression before point, in the outside context, and insert the value in the buffer (edebug-eval-print-last-sexp).
C-x C-e
Evaluate the expression before point, in the context outside of Edebug (edebug-eval-last-sexp).
C-c C-u
Build a new evaluation list from the contents of the buffer (edebug-update-eval-list).
C-c C-d
Delete the evaluation list group that point is in (edebug-delete-eval-item).
C-c C-w
Switch back to the source code buffer at the current stop point (edebug-where).

You can evaluate expressions in the evaluation list window with C-j or C-x C-e, just as you would in `*scratch*'; but they are evaluated in the context outside of Edebug.

The expressions you enter interactively (and their results) are lost when you continue execution; but you can set up an evaluation list consisting of expressions to be evaluated each time execution stops.

To do this, write one or more evaluation list groups in the evaluation list buffer. An evaluation list group consists of one or more Lisp expressions. Groups are separated by comment lines.

The command C-c C-u (edebug-update-eval-list) rebuilds the evaluation list, scanning the buffer and using the first expression of each group. (The idea is that the second expression of the group is the value previously computed and displayed.)

Each entry to Edebug redisplays the evaluation list by inserting each expression in the buffer, followed by its current value. It also inserts comment lines so that each expression becomes its own group. Thus, if you type C-c C-u again without changing the buffer text, the evaluation list is effectively unchanged.

If an error occurs during an evaluation from the evaluation list, the error message is displayed in a string as if it were the result. Therefore, expressions that use variables not currently valid do not interrupt your debugging.

Here is an example of what the evaluation list window looks like after several expressions have been added to it:

(current-buffer)
#<buffer *scratch*>
;---------------------------------------------------------------
(selected-window)
#<window 16 on *scratch*>
;---------------------------------------------------------------
(point)
196
;---------------------------------------------------------------
bad-var
"Symbol's value as variable is void: bad-var"
;---------------------------------------------------------------
(recursion-depth)
0
;---------------------------------------------------------------
this-command
eval-last-sexp
;---------------------------------------------------------------

To delete a group, move point into it and type C-c C-d, or simply delete the text for the group and update the evaluation list with C-c C-u. To add a new expression to the evaluation list, insert the expression at a suitable place, and insert a new comment line. (You need not insert dashes in the comment line--its contents don't matter.) Then type C-c C-u.

After selecting `*edebug*', you can return to the source code buffer with C-c C-w. The `*edebug*' buffer is killed when you continue execution, and recreated next time it is needed.

Printing in Edebug

If an expression in your program produces a value containing circular list structure, you may get an error when Edebug attempts to print it.

One way to cope with circular structure is to set print-length or print-level to truncate the printing. Edebug does this for you; it binds print-length and print-level to 50 if they were nil. (Actually, the variables edebug-print-length and edebug-print-level specify the values to use within Edebug.) See section Variables Affecting Output.

User Option: edebug-print-length
If non-nil, bind print-length to this while printing results in Edebug. The default value is 50.

User Option: edebug-print-level
If non-nil, bind print-level to this while printing results in Edebug. The default value is 50.

You can also print circular structures and structures that share elements more informatively by using the `cust-print' package.

To load `cust-print' and activate custom printing only for Edebug, simply use the command M-x edebug-install-custom-print. To restore the standard print functions, use M-x edebug-uninstall-custom-print.

Here is an example of code that creates a circular structure:

(setq a '(x y))
(setcar a a)

Custom printing prints this as `Result: #1=(#1# y)'. The `#1=' notation labels the structure that follows it with the label `1', and the `#1#' notation references the previously labeled structure. This notation is used for any shared elements of lists or vectors.

User Option: edebug-print-circle
If non-nil, bind print-circle to this while printing results in Edebug. The default value is nil.

Other programs can also use custom printing; see `cust-print.el' for details.

Trace Buffer

Edebug can record an execution trace, storing it in a buffer named `*edebug-trace*'. This is a log of function calls and returns, showing the function names and their arguments and values. To enable trace recording, set edebug-trace to a non-nil value.

Making a trace buffer is not the same thing as using trace execution mode (see section Edebug Execution Modes).

When trace recording is enabled, each function entry and exit adds lines to the trace buffer. A function entry record looks like `::::{' followed by the function name and argument values. A function exit record looks like `::::}' followed by the function name and result of the function.

The number of `:'s in an entry shows its recursion depth. You can use the braces in the trace buffer to find the matching beginning or end of function calls.

You can customize trace recording for function entry and exit by redefining the functions edebug-print-trace-before and edebug-print-trace-after.

Macro: edebug-tracing string body...
This macro requests additional trace information around the execution of the body forms. The argument string specifies text to put in the trace buffer. All the arguments are evaluated. edebug-tracing returns the value of the last form in body.

Function: edebug-trace format-string &rest format-args
This function inserts text in the trace buffer. It computes the text with (apply 'format format-string format-args). It also appends a newline to separate entries.

edebug-tracing and edebug-trace insert lines in the trace buffer whenever they are called, even if Edebug is not active. Adding text to the trace buffer also scrolls its window to show the last lines inserted.

Coverage Testing

Edebug provides rudimentary coverage testing and display of execution frequency.

Coverage testing works by comparing the result of each expression with the previous result; each form in the program is considered "covered" if it has returned two different values since you began testing coverage in the current Emacs session. Thus, to do coverage testing on your program, execute it under various conditions and note whether it behaves correctly; Edebug will tell you when you have tried enough different conditions that each form has returned two different values.

Coverage testing makes execution slower, so it is only done if edebug-test-coverage is non-nil. Frequency counting is performed for all execution of an instrumented function, even if the execution mode is Go-nonstop, and regardless of whether coverage testing is enabled.

Use M-x edebug-display-freq-count to display both the coverage information and the frequency counts for a definition.

Command: edebug-display-freq-count
This command displays the frequency count data for each line of the current definition.

The frequency counts appear as comment lines after each line of code, and you can undo all insertions with one undo command. The counts appear under the `(' before an expression or the `)' after an expression, or on the last character of a variable. To simplify the display, a count is not shown if it is equal to the count of an earlier expression on the same line.

The character `=' following the count for an expression says that the expression has returned the same value each time it was evaluated. In other words, it is not yet "covered" for coverage testing purposes.

To clear the frequency count and coverage data for a definition, simply reinstrument it with eval-defun.

For example, after evaluating (fac 5) with a source breakpoint, and setting edebug-test-coverage to t, when the breakpoint is reached, the frequency data looks like this:

(defun fac (n)
  (if (= n 0) (edebug))
;#6           1      0 =5 
  (if (< 0 n)
;#5         = 
      (* n (fac (1- n)))
;#    5               0  
    1))
;#   0 

The comment lines show that fac was called 6 times. The first if statement returned 5 times with the same result each time; the same is true of the condition on the second if. The recursive call of fac did not return at all.

The Outside Context

Edebug tries to be transparent to the program you are debugging, but it does not succeed completely. Edebug also tries to be transparent when you evaluate expressions with e or with the evaluation list buffer, by temporarily restoring the outside context. This section explains precisely what context Edebug restores, and how Edebug fails to be completely transparent.

Checking Whether to Stop

Whenever Edebug is entered, it needs to save and restore certain data before even deciding whether to make trace information or stop the program.

Edebug Display Update

When Edebug needs to display something (e.g., in trace mode), it saves the current window configuration from "outside" Edebug (see section Window Configurations). When you exit Edebug (by continuing the program), it restores the previous window configuration.

Emacs redisplays only when it pauses. Usually, when you continue execution, the program comes back into Edebug at a breakpoint or after stepping without pausing or reading input in between. In such cases, Emacs never gets a chance to redisplay the "outside" configuration. What you see is the same window configuration as the last time Edebug was active, with no interruption.

Entry to Edebug for displaying something also saves and restores the following data, but some of these are deliberately not restored if an error or quit signal occurs.

Edebug Recursive Edit

When Edebug is entered and actually reads commands from the user, it saves (and later restores) these additional data:

Instrumenting Macro Calls

When Edebug instruments an expression that calls a Lisp macro, it needs additional information about the macro to do the job properly. This is because there is no a-priori way to tell which subexpressions of the macro call are forms to be evaluated. (Evaluation may occur explicitly in the macro body, or when the resulting expansion is evaluated, or any time later.)

Therefore, you must define an Edebug specification for each macro that Edebug will encounter, to explain the format of calls to that macro. To do this, use def-edebug-spec.

Macro: def-edebug-spec macro specification
Specify which expressions of a call to macro macro are forms to be evaluated. For simple macros, the specification often looks very similar to the formal argument list of the macro definition, but specifications are much more general than macro arguments.

The macro argument can actually be any symbol, not just a macro name.

Here is a simple example that defines the specification for the for example macro (see section Evaluating Macro Arguments Repeatedly), followed by an alternative, equivalent specification.

(def-edebug-spec for
  (symbolp "from" form "to" form "do" &rest form))

(def-edebug-spec for
  (symbolp ['from form] ['to form] ['do body]))

Here is a table of the possibilities for specification and how each directs processing of arguments.

t
All arguments are instrumented for evaluation.
0
None of the arguments is instrumented.
a symbol
The symbol must have an Edebug specification which is used instead. This indirection is repeated until another kind of specification is found. This allows you to inherit the specification from another macro.
a list
The elements of the list describe the types of the arguments of a calling form. The possible elements of a specification list are described in the following sections.

Specification List

A specification list is required for an Edebug specification if some arguments of a macro call are evaluated while others are not. Some elements in a specification list match one or more arguments, but others modify the processing of all following elements. The latter, called specification keywords, are symbols beginning with `&' (such as &optional).

A specification list may contain sublists which match arguments that are themselves lists, or it may contain vectors used for grouping. Sublists and groups thus subdivide the specification list into a hierarchy of levels. Specification keywords apply only to the remainder of the sublist or group they are contained in.

When a specification list involves alternatives or repetition, matching it against an actual macro call may require backtracking. See section Backtracking in Specifications, for more details.

Edebug specifications provide the power of regular expression matching, plus some context-free grammar constructs: the matching of sublists with balanced parentheses, recursive processing of forms, and recursion via indirect specifications.

Here's a table of the possible elements of a specification list, with their meanings:

sexp
A single unevaluated Lisp object, which is not instrumented.
form
A single evaluated expression, which is instrumented.
place
A place to store a value, as in the Common Lisp setf construct.
body
Short for &rest form. See &rest below.
function-form
A function form: either a quoted function symbol, a quoted lambda expression, or a form (that should evaluate to a function symbol or lambda expression). This is useful when an argument that's a lambda expression might be quoted with quote rather than function, since it instruments the body of the lambda expression either way.
lambda-expr
A lambda expression with no quoting.
&optional
All following elements in the specification list are optional; as soon as one does not match, Edebug stops matching at this level. To make just a few elements optional followed by non-optional elements, use [&optional specs...]. To specify that several elements must all match or none, use &optional [specs...]. See the defun example below.
&rest
All following elements in the specification list are repeated zero or more times. In the last repetition, however, it is not a problem if the expression runs out before matching all of the elements of the specification list. To repeat only a few elements, use [&rest specs...]. To specify several elements that must all match on every repetition, use &rest [specs...].
&or
Each of the following elements in the specification list is an alternative. One of the alternatives must match, or the &or specification fails. Each list element following &or is a single alternative. To group two or more list elements as a single alternative, enclose them in [...].
&not
Each of the following elements is matched as alternatives as if by using &or, but if any of them match, the specification fails. If none of them match, nothing is matched, but the &not specification succeeds.
&define
Indicates that the specification is for a defining form. The defining form itself is not instrumented (that is, Edebug does not stop before and after the defining form), but forms inside it typically will be instrumented. The &define keyword should be the first element in a list specification.
nil
This is successful when there are no more arguments to match at the current argument list level; otherwise it fails. See sublist specifications and the backquote example below.
gate
No argument is matched but backtracking through the gate is disabled while matching the remainder of the specifications at this level. This is primarily used to generate more specific syntax error messages. See section Backtracking in Specifications, for more details. Also see the let example below.
other-symbol
Any other symbol in a specification list may be a predicate or an indirect specification. If the symbol has an Edebug specification, this indirect specification should be either a list specification that is used in place of the symbol, or a function that is called to process the arguments. The specification may be defined with def-edebug-spec just as for macros. See the defun example below. Otherwise, the symbol should be a predicate. The predicate is called with the argument and the specification fails if the predicate returns nil. In either case, that argument is not instrumented. Some suitable predicates include symbolp, integerp, stringp, vectorp, and atom.
[elements...]
A vector of elements groups the elements into a single group specification. Its meaning has nothing to do with vectors.
"string"
The argument should be a symbol named string. This specification is equivalent to the quoted symbol, 'symbol, where the name of symbol is the string, but the string form is preferred.
(vector elements...)
The argument should be a vector whose elements must match the elements in the specification. See the backquote example below.
(elements...)
Any other list is a sublist specification and the argument must be a list whose elements match the specification elements. A sublist specification may be a dotted list and the corresponding list argument may then be a dotted list. Alternatively, the last CDR of a dotted list specification may be another sublist specification (via a grouping or an indirect specification, e.g., (spec . [(more specs...)])) whose elements match the non-dotted list arguments. This is useful in recursive specifications such as in the backquote example below. Also see the description of a nil specification above for terminating such recursion. Note that a sublist specification written as (specs . nil) is equivalent to (specs), and (specs . (sublist-elements...)) is equivalent to (specs sublist-elements...).

Here is a list of additional specifications that may appear only after &define. See the defun example below.

name
The argument, a symbol, is the name of the defining form. A defining form is not required to have a name field; and it may have multiple name fields.
:name
This construct does not actually match an argument. The element following :name should be a symbol; it is used as an additional name component for the definition. You can use this to add a unique, static component to the name of the definition. It may be used more than once.
arg
The argument, a symbol, is the name of an argument of the defining form. However, lambda-list keywords (symbols starting with `&') are not allowed.
lambda-list
This matches a lambda list--the argument list of a lambda expression.
def-body
The argument is the body of code in a definition. This is like body, described above, but a definition body must be instrumented with a different Edebug call that looks up information associated with the definition. Use def-body for the highest level list of forms within the definition.
def-form
The argument is a single, highest-level form in a definition. This is like def-body, except use this to match a single form rather than a list of forms. As a special case, def-form also means that tracing information is not output when the form is executed. See the interactive example below.

Backtracking in Specifications

If a specification fails to match at some point, this does not necessarily mean a syntax error will be signaled; instead, backtracking will take place until all alternatives have been exhausted. Eventually every element of the argument list must be matched by some element in the specification, and every required element in the specification must match some argument. When a syntax error is detected, it might not be reported until much later after higher-level alternatives have been exhausted, and with the point positioned further from the real error. But if backtracking is disabled when an error occurs, it can be reported immediately. Note that backtracking is also reenabled automatically in several situations; it is reenabled when a new alternative is established by &optional, &rest, or &or, or at the start of processing a sublist, group, or indirect specification. The effect of enabling or disabling backtracking is limited to the remainder of the level currently being processed and lower levels.

Backtracking is disabled while matching any of the form specifications (that is, form, body, def-form, and def-body). These specifications will match any form so any error must be in the form itself rather than at a higher level.

Backtracking is also disabled after successfully matching a quoted symbol or string specification, since this usually indicates a recognized construct. But if you have a set of alternative constructs that all begin with the same symbol, you can usually work around this constraint by factoring the symbol out of the alternatives, e.g., ["foo" &or [first case] [second case] ...].

Most needs are satisfied by these two ways that bactracking is automatically disabled, but occasionally it is useful to explicitly disable backtracking by using the gate specification. This is useful when you know that no higher alternatives could apply. See the example of the let specification.

Specification Examples

It may be easier to understand Edebug specifications by studying the examples provided here.

A let special form has a sequence of bindings and a body. Each of the bindings is either a symbol or a sublist with a symbol and optional expression. In the specification below, notice the gate inside of the sublist to prevent backtracking once a sublist is found.

(def-edebug-spec let
  ((&rest
    &or symbolp (gate symbolp &optional form))
   body))

Edebug uses the following specifications for defun and defmacro and the associated argument list and interactive specifications. It is necessary to handle interactive forms specially since an expression argument it is actually evaluated outside of the function body.

(def-edebug-spec defmacro defun) ; Indirect ref to defun spec.
(def-edebug-spec defun 
  (&define name lambda-list 
           [&optional stringp]   ; Match the doc string, if present.
           [&optional ("interactive" interactive)]
           def-body))

(def-edebug-spec lambda-list
  (([&rest arg]
    [&optional ["&optional" arg &rest arg]]
    &optional ["&rest" arg]
    )))

(def-edebug-spec interactive
  (&optional &or stringp def-form))    ; Notice: def-form

The specification for backquote below illustrates how to match dotted lists and use nil to terminate recursion. It also illustrates how components of a vector may be matched. (The actual specification defined by Edebug does not support dotted lists because doing so causes very deep recursion that could fail.)

(def-edebug-spec ` (backquote-form))   ; Alias just for clarity.

(def-edebug-spec backquote-form
  (&or ([&or "," ",@"] &or ("quote" backquote-form) form)
       (backquote-form . [&or nil backquote-form])
       (vector &rest backquote-form)
       sexp))

Edebug Options

These options affect the behavior of Edebug:

User Option: edebug-setup-hook
Functions to call before Edebug is used. Each time it is set to a new value, Edebug will call those functions once and then edebug-setup-hook is reset to nil. You could use this to load up Edebug specifications associated with a package you are using but only when you also use Edebug. See section Instrumenting for Edebug.

User Option: edebug-all-defs
If this is non-nil, normal evaluation of defining forms such as defun and defmacro instruments them for Edebug. This applies to eval-defun, eval-region, eval-buffer, and eval-current-buffer.

Use the command M-x edebug-all-defs to toggle the value of this option. See section Instrumenting for Edebug.

User Option: edebug-all-forms
If this is non-nil, the commands eval-defun, eval-region, eval-buffer, and eval-current-buffer instrument all forms, even those that don't define anything. This doesn't apply to loading or evaluations in the minibuffer.

Use the command M-x edebug-all-forms to toggle the value of this option. See section Instrumenting for Edebug.

User Option: edebug-save-windows
If this is non-nil, Edebug saves and restores the window configuration. That takes some time, so if your program does not care what happens to the window configurations, it is better to set this variable to nil.

If the value is a list, only the listed windows are saved and restored.

You can use the W command in Edebug to change this variable interactively. See section Edebug Display Update.

User Option: edebug-save-displayed-buffer-points
If this is non-nil, Edebug saves and restores point in all displayed buffers.

Saving and restoring point in other buffers is necessary if you are debugging code that changes the point of a buffer which is displayed in a non-selected window. If Edebug or the user then selects the window, point in that buffer will move to the window's value of point.

Saving and restoring point in all buffers is expensive, since it requires selecting each window twice, so enable this only if you need it. See section Edebug Display Update.

User Option: edebug-initial-mode
If this variable is non-nil, it specifies the initial execution mode for Edebug when it is first activated. Possible values are step, next, go, Go-nonstop, trace, Trace-fast, continue, and Continue-fast.

The default value is step. See section Edebug Execution Modes.

User Option: edebug-trace
Non-nil means display a trace of function entry and exit. Tracing output is displayed in a buffer named `*edebug-trace*', one function entry or exit per line, indented by the recursion level.

The default value is nil.

Also see edebug-tracing, in section Trace Buffer.

User Option: edebug-test-coverage
If non-nil, Edebug tests coverage of all expressions debugged. See section Coverage Testing.

User Option: edebug-continue-kbd-macro
If non-nil, continue defining or executing any keyboard macro that is executing outside of Edebug. Use this with caution since it is not debugged. See section Edebug Execution Modes.

User Option: edebug-on-error
Edebug binds debug-on-error to this value, if debug-on-error was previously nil. See section Trapping Errors.

User Option: edebug-on-quit
Edebug binds debug-on-quit to this value, if debug-on-quit was previously nil. See section Trapping Errors.

If you change the values of edebug-on-error or edebug-on-quit while Edebug is active, their values won't be used until the next time Edebug is invoked via a new command.

User Option: edebug-global-break-condition
If non-nil, an expression to test for at every stop point. If the result is non-nil, then break. Errors are ignored. See section Global Break Condition.

Debugging Invalid Lisp Syntax

The Lisp reader reports invalid syntax, but cannot say where the real problem is. For example, the error "End of file during parsing" in evaluating an expression indicates an excess of open parentheses (or square brackets). The reader detects this imbalance at the end of the file, but it cannot figure out where the close parenthesis should have been. Likewise, "Invalid read syntax: ")"" indicates an excess close parenthesis or missing open parenthesis, but does not say where the missing parenthesis belongs. How, then, to find what to change?

If the problem is not simply an imbalance of parentheses, a useful technique is to try C-M-e at the beginning of each defun, and see if it goes to the place where that defun appears to end. If it does not, there is a problem in that defun.

However, unmatched parentheses are the most common syntax errors in Lisp, and we can give further advice for those cases. (In addition, just moving point through the code with Show Paren mode enabled might find the mismatch.)

Excess Open Parentheses

The first step is to find the defun that is unbalanced. If there is an excess open parenthesis, the way to do this is to insert a close parenthesis at the end of the file and type C-M-b (backward-sexp). This will move you to the beginning of the defun that is unbalanced. (Then type C-SPC C-_ C-u C-SPC to set the mark there, undo the insertion of the close parenthesis, and finally return to the mark.)

The next step is to determine precisely what is wrong. There is no way to be sure of this except by studying the program, but often the existing indentation is a clue to where the parentheses should have been. The easiest way to use this clue is to reindent with C-M-q and see what moves. But don't do this yet! Keep reading, first.

Before you do this, make sure the defun has enough close parentheses. Otherwise, C-M-q will get an error, or will reindent all the rest of the file until the end. So move to the end of the defun and insert a close parenthesis there. Don't use C-M-e to move there, since that too will fail to work until the defun is balanced.

Now you can go to the beginning of the defun and type C-M-q. Usually all the lines from a certain point to the end of the function will shift to the right. There is probably a missing close parenthesis, or a superfluous open parenthesis, near that point. (However, don't assume this is true; study the code to make sure.) Once you have found the discrepancy, undo the C-M-q with C-_, since the old indentation is probably appropriate to the intended parentheses.

After you think you have fixed the problem, use C-M-q again. If the old indentation actually fit the intended nesting of parentheses, and you have put back those parentheses, C-M-q should not change anything.

Excess Close Parentheses

To deal with an excess close parenthesis, first insert an open parenthesis at the beginning of the file, back up over it, and type C-M-f to find the end of the unbalanced defun. (Then type C-SPC C-_ C-u C-SPC to set the mark there, undo the insertion of the open parenthesis, and finally return to the mark.)

Then find the actual matching close parenthesis by typing C-M-f at the beginning of that defun. This will leave you somewhere short of the place where the defun ought to end. It is possible that you will find a spurious close parenthesis in that vicinity.

If you don't see a problem at that point, the next thing to do is to type C-M-q at the beginning of the defun. A range of lines will probably shift left; if so, the missing open parenthesis or spurious close parenthesis is probably near the first of those lines. (However, don't assume this is true; study the code to make sure.) Once you have found the discrepancy, undo the C-M-q with C-_, since the old indentation is probably appropriate to the intended parentheses.

After you think you have fixed the problem, use C-M-q again. If the old indentation actually fit the intended nesting of parentheses, and you have put back those parentheses, C-M-q should not change anything.

Debugging Problems in Compilation

When an error happens during byte compilation, it is normally due to invalid syntax in the program you are compiling. The compiler prints a suitable error message in the `*Compile-Log*' buffer, and then stops. The message may state a function name in which the error was found, or it may not. Either way, here is how to find out where in the file the error occurred.

What you should do is switch to the buffer ` *Compiler Input*'. (Note that the buffer name starts with a space, so it does not show up in M-x list-buffers.) This buffer contains the program being compiled, and point shows how far the byte compiler was able to read.

If the error was due to invalid Lisp syntax, point shows exactly where the invalid syntax was detected. The cause of the error is not necessarily near by! Use the techniques in the previous section to find the error.

If the error was detected while compiling a form that had been read successfully, then point is located at the end of the form. In this case, this technique can't localize the error precisely, but can still show you which function to check.

Reading and Printing Lisp Objects

Printing and reading are the operations of converting Lisp objects to textual form and vice versa. They use the printed representations and read syntax described in section Lisp Data Types.

This chapter describes the Lisp functions for reading and printing. It also describes streams, which specify where to get the text (if reading) or where to put it (if printing).

Introduction to Reading and Printing

Reading a Lisp object means parsing a Lisp expression in textual form and producing a corresponding Lisp object. This is how Lisp programs get into Lisp from files of Lisp code. We call the text the read syntax of the object. For example, the text `(a . 5)' is the read syntax for a cons cell whose CAR is a and whose CDR is the number 5.

Printing a Lisp object means producing text that represents that object--converting the object to its printed representation (see section Printed Representation and Read Syntax). Printing the cons cell described above produces the text `(a . 5)'.

Reading and printing are more or less inverse operations: printing the object that results from reading a given piece of text often produces the same text, and reading the text that results from printing an object usually produces a similar-looking object. For example, printing the symbol foo produces the text `foo', and reading that text returns the symbol foo. Printing a list whose elements are a and b produces the text `(a b)', and reading that text produces a list (but not the same list) with elements a and b.

However, these two operations are not precisely inverses. There are three kinds of exceptions:

Input Streams

Most of the Lisp functions for reading text take an input stream as an argument. The input stream specifies where or how to get the characters of the text to be read. Here are the possible types of input stream:

buffer
The input characters are read from buffer, starting with the character directly after point. Point advances as characters are read.
marker
The input characters are read from the buffer that marker is in, starting with the character directly after the marker. The marker position advances as characters are read. The value of point in the buffer has no effect when the stream is a marker.
string
The input characters are taken from string, starting at the first character in the string and using as many characters as required.
function
The input characters are generated by function, which must support two kinds of calls:
t
t used as a stream means that the input is read from the minibuffer. In fact, the minibuffer is invoked once and the text given by the user is made into a string that is then used as the input stream.
nil
nil supplied as an input stream means to use the value of standard-input instead; that value is the default input stream, and must be a non-nil input stream.
symbol
A symbol as input stream is equivalent to the symbol's function definition (if any).

Here is an example of reading from a stream that is a buffer, showing where point is located before and after:

---------- Buffer: foo ----------
This-!- is the contents of foo.
---------- Buffer: foo ----------

(read (get-buffer "foo"))
     => is
(read (get-buffer "foo"))
     => the

---------- Buffer: foo ----------
This is the-!- contents of foo.
---------- Buffer: foo ----------

Note that the first read skips a space. Reading skips any amount of whitespace preceding the significant text.

Here is an example of reading from a stream that is a marker, initially positioned at the beginning of the buffer shown. The value read is the symbol This.

---------- Buffer: foo ----------
This is the contents of foo.
---------- Buffer: foo ----------

(setq m (set-marker (make-marker) 1 (get-buffer "foo")))
     => #<marker at 1 in foo>
(read m)
     => This
m
     => #<marker at 5 in foo>   ;; Before the first space.

Here we read from the contents of a string:

(read "(When in) the course")
     => (When in)

The following example reads from the minibuffer. The prompt is: `Lisp expression: '. (That is always the prompt used when you read from the stream t.) The user's input is shown following the prompt.

(read t)
     => 23
---------- Buffer: Minibuffer ----------
Lisp expression: 23 RET
---------- Buffer: Minibuffer ----------

Finally, here is an example of a stream that is a function, named useless-stream. Before we use the stream, we initialize the variable useless-list to a list of characters. Then each call to the function useless-stream obtains the next character in the list or unreads a character by adding it to the front of the list.

(setq useless-list (append "XY()" nil))
     => (88 89 40 41)

(defun useless-stream (&optional unread)
  (if unread
      (setq useless-list (cons unread useless-list))
    (prog1 (car useless-list)
           (setq useless-list (cdr useless-list)))))
     => useless-stream

Now we read using the stream thus constructed:

(read 'useless-stream)
     => XY

useless-list
     => (40 41)

Note that the open and close parentheses remain in the list. The Lisp reader encountered the open parenthesis, decided that it ended the input, and unread it. Another attempt to read from the stream at this point would read `()' and return nil.

Function: get-file-char
This function is used internally as an input stream to read from the input file opened by the function load. Don't use this function yourself.

Input Functions

This section describes the Lisp functions and variables that pertain to reading.

In the functions below, stream stands for an input stream (see the previous section). If stream is nil or omitted, it defaults to the value of standard-input.

An end-of-file error is signaled if reading encounters an unterminated list, vector, or string.

Function: read &optional stream
This function reads one textual Lisp expression from stream, returning it as a Lisp object. This is the basic Lisp input function.

Function: read-from-string string &optional start end
This function reads the first textual Lisp expression from the text in string. It returns a cons cell whose CAR is that expression, and whose CDR is an integer giving the position of the next remaining character in the string (i.e., the first one not read).

If start is supplied, then reading begins at index start in the string (where the first character is at index 0). If you specify end, then reading is forced to stop just before that index, as if the rest of the string were not there.

For example:

(read-from-string "(setq x 55) (setq y 5)")
     => ((setq x 55) . 11)
(read-from-string "\"A short string\"")
     => ("A short string" . 16)

;; Read starting at the first character.
(read-from-string "(list 112)" 0)
     => ((list 112) . 10)
;; Read starting at the second character.
(read-from-string "(list 112)" 1)
     => (list . 5)
;; Read starting at the seventh character,
;;   and stopping at the ninth.
(read-from-string "(list 112)" 6 8)
     => (11 . 8)

Variable: standard-input
This variable holds the default input stream--the stream that read uses when the stream argument is nil.

Output Streams

An output stream specifies what to do with the characters produced by printing. Most print functions accept an output stream as an optional argument. Here are the possible types of output stream:

buffer
The output characters are inserted into buffer at point. Point advances as characters are inserted.
marker
The output characters are inserted into the buffer that marker points into, at the marker position. The marker position advances as characters are inserted. The value of point in the buffer has no effect on printing when the stream is a marker, and this kind of printing does not move point.
function
The output characters are passed to function, which is responsible for storing them away. It is called with a single character as argument, as many times as there are characters to be output, and is responsible for storing the characters wherever you want to put them.
t
The output characters are displayed in the echo area.
nil
nil specified as an output stream means to use the value of standard-output instead; that value is the default output stream, and must not be nil.
symbol
A symbol as output stream is equivalent to the symbol's function definition (if any).

Many of the valid output streams are also valid as input streams. The difference between input and output streams is therefore more a matter of how you use a Lisp object, than of different types of object.

Here is an example of a buffer used as an output stream. Point is initially located as shown immediately before the `h' in `the'. At the end, point is located directly before that same `h'.

---------- Buffer: foo ----------
This is t-!-he contents of foo.
---------- Buffer: foo ----------

(print "This is the output" (get-buffer "foo"))
     => "This is the output"

---------- Buffer: foo ----------
This is t
"This is the output"
-!-he contents of foo.
---------- Buffer: foo ----------

Now we show a use of a marker as an output stream. Initially, the marker is in buffer foo, between the `t' and the `h' in the word `the'. At the end, the marker has advanced over the inserted text so that it remains positioned before the same `h'. Note that the location of point, shown in the usual fashion, has no effect.

---------- Buffer: foo ----------
This is the -!-output
---------- Buffer: foo ----------

(setq m (copy-marker 10))
     => #<marker at 10 in foo>

(print "More output for foo." m)
     => "More output for foo."

---------- Buffer: foo ----------
This is t
"More output for foo."
he -!-output
---------- Buffer: foo ----------

m
     => #<marker at 34 in foo>

The following example shows output to the echo area:

(print "Echo Area output" t)
     => "Echo Area output"
---------- Echo Area ----------
"Echo Area output"
---------- Echo Area ----------

Finally, we show the use of a function as an output stream. The function eat-output takes each character that it is given and conses it onto the front of the list last-output (see section Building Cons Cells and Lists). At the end, the list contains all the characters output, but in reverse order.

(setq last-output nil)
     => nil

(defun eat-output (c)
  (setq last-output (cons c last-output)))
     => eat-output

(print "This is the output" 'eat-output)
     => "This is the output"

last-output
     => (10 34 116 117 112 116 117 111 32 101 104 
    116 32 115 105 32 115 105 104 84 34 10)

Now we can put the output in the proper order by reversing the list:

(concat (nreverse last-output))
     => "
\"This is the output\"
"

Calling concat converts the list to a string so you can see its contents more clearly.

Output Functions

This section describes the Lisp functions for printing Lisp objects--converting objects into their printed representation.

Some of the Emacs printing functions add quoting characters to the output when necessary so that it can be read properly. The quoting characters used are `"' and `\'; they distinguish strings from symbols, and prevent punctuation characters in strings and symbols from being taken as delimiters when reading. See section Printed Representation and Read Syntax, for full details. You specify quoting or no quoting by the choice of printing function.

If the text is to be read back into Lisp, then you should print with quoting characters to avoid ambiguity. Likewise, if the purpose is to describe a Lisp object clearly for a Lisp programmer. However, if the purpose of the output is to look nice for humans, then it is usually better to print without quoting.

Lisp objects can refer to themselves. Printing a self-referential object in the normal way would require an infinite amount of text, and the attempt could cause infinite recursion. Emacs detects such recursion and prints `#level' instead of recursively printing an object already being printed. For example, here `#0' indicates a recursive reference to the object at level 0 of the current print operation:

(setq foo (list nil))
     => (nil)
(setcar foo foo)
     => (#0)

In the functions below, stream stands for an output stream. (See the previous section for a description of output streams.) If stream is nil or omitted, it defaults to the value of standard-output.

Function: print object &optional stream
The print function is a convenient way of printing. It outputs the printed representation of object to stream, printing in addition one newline before object and another after it. Quoting characters are used. print returns object. For example:

(progn (print 'The\ cat\ in)
       (print "the hat")
       (print " came back"))
     -| 
     -| The\ cat\ in
     -| 
     -| "the hat"
     -| 
     -| " came back"
     -| 
     => " came back"

Function: prin1 object &optional stream
This function outputs the printed representation of object to stream. It does not print newlines to separate output as print does, but it does use quoting characters just like print. It returns object.

(progn (prin1 'The\ cat\ in) 
       (prin1 "the hat") 
       (prin1 " came back"))
     -| The\ cat\ in"the hat"" came back"
     => " came back"

Function: princ object &optional stream
This function outputs the printed representation of object to stream. It returns object.

This function is intended to produce output that is readable by people, not by read, so it doesn't insert quoting characters and doesn't put double-quotes around the contents of strings. It does not add any spacing between calls.

(progn
  (princ 'The\ cat)
  (princ " in the \"hat\""))
     -| The cat in the "hat"
     => " in the \"hat\""

Function: terpri &optional stream
This function outputs a newline to stream. The name stands for "terminate print".

Function: write-char character &optional stream
This function outputs character to stream. It returns character.

Function: prin1-to-string object &optional noescape
This function returns a string containing the text that prin1 would have printed for the same argument.

(prin1-to-string 'foo)
     => "foo"
(prin1-to-string (mark-marker))
     => "#<marker at 2773 in strings.texi>"

If noescape is non-nil, that inhibits use of quoting characters in the output. (This argument is supported in Emacs versions 19 and later.)

(prin1-to-string "foo")
     => "\"foo\""
(prin1-to-string "foo" t)
     => "foo"

See format, in section Conversion of Characters and Strings, for other ways to obtain the printed representation of a Lisp object as a string.

Macro: with-output-to-string body...
This macro executes the body forms with standard-output set up to feed output into a string. Then it returns that string.

For example, if the current buffer name is `foo',

(with-output-to-string
  (princ "The buffer is ")
  (princ (buffer-name)))

returns "The buffer is foo".

Variables Affecting Output

Variable: standard-output
The value of this variable is the default output stream--the stream that print functions use when the stream argument is nil.

Variable: print-escape-newlines
If this variable is non-nil, then newline characters in strings are printed as `\n' and formfeeds are printed as `\f'. Normally these characters are printed as actual newlines and formfeeds.

This variable affects the print functions prin1 and print that print with quoting. It does not affect princ. Here is an example using prin1:

(prin1 "a\nb")
     -| "a
     -| b"
     => "a
b"

(let ((print-escape-newlines t))
  (prin1 "a\nb"))
     -| "a\nb"
     => "a
b"

In the second expression, the local binding of print-escape-newlines is in effect during the call to prin1, but not during the printing of the result.

Variable: print-escape-nonascii
If this variable is non-nil, then unibyte non-ASCII characters in strings are unconditionally printed as backslash sequences by the print functions prin1 and print that print with quoting.

Those functions also use backslash sequences for unibyte non-ASCII characters, regardless of the value of this variable, when the output stream is a multibyte buffer or a marker pointing into one.

Variable: print-escape-multibyte
If this variable is non-nil, then multibyte non-ASCII characters in strings are unconditionally printed as backslash sequences by the print functions prin1 and print that print with quoting.

Those functions also use backslash sequences for multibyte non-ASCII characters, regardless of the value of this variable, when the output stream is a unibyte buffer or a marker pointing into one.

Variable: print-length
The value of this variable is the maximum number of elements to print in any list, vector or bool-vector. If an object being printed has more than this many elements, it is abbreviated with an ellipsis.

If the value is nil (the default), then there is no limit.

(setq print-length 2)
     => 2
(print '(1 2 3 4 5))
     -| (1 2 ...)
     => (1 2 ...)

Variable: print-level
The value of this variable is the maximum depth of nesting of parentheses and brackets when printed. Any list or vector at a depth exceeding this limit is abbreviated with an ellipsis. A value of nil (which is the default) means no limit.

Minibuffers

A minibuffer is a special buffer that Emacs commands use to read arguments more complicated than the single numeric prefix argument. These arguments include file names, buffer names, and command names (as in M-x). The minibuffer is displayed on the bottom line of the frame, in the same place as the echo area, but only while it is in use for reading an argument.

Introduction to Minibuffers

In most ways, a minibuffer is a normal Emacs buffer. Most operations within a buffer, such as editing commands, work normally in a minibuffer. However, many operations for managing buffers do not apply to minibuffers. The name of a minibuffer always has the form ` *Minibuf-number', and it cannot be changed. Minibuffers are displayed only in special windows used only for minibuffers; these windows always appear at the bottom of a frame. (Sometimes frames have no minibuffer window, and sometimes a special kind of frame contains nothing but a minibuffer window; see section Minibuffers and Frames.)

The minibuffer's window is normally a single line. You can resize it temporarily with the window sizing commands; it reverts to its normal size when the minibuffer is exited. You can resize it permanently by using the window sizing commands in the frame's other window, when the minibuffer is not active. If the frame contains just a minibuffer, you can change the minibuffer's size by changing the frame's size.

If a command uses a minibuffer while there is an active minibuffer, this is called a recursive minibuffer. The first minibuffer is named ` *Minibuf-0*'. Recursive minibuffers are named by incrementing the number at the end of the name. (The names begin with a space so that they won't show up in normal buffer lists.) Of several recursive minibuffers, the innermost (or most recently entered) is the active minibuffer. We usually call this "the" minibuffer. You can permit or forbid recursive minibuffers by setting the variable enable-recursive-minibuffers or by putting properties of that name on command symbols (see section Minibuffer Miscellany).

Like other buffers, a minibuffer may use any of several local keymaps (see section Keymaps); these contain various exit commands and in some cases completion commands (see section Completion).

Reading Text Strings with the Minibuffer

Most often, the minibuffer is used to read text as a string. It can also be used to read a Lisp object in textual form. The most basic primitive for minibuffer input is read-from-minibuffer; it can do either one.

In most cases, you should not call minibuffer input functions in the middle of a Lisp function. Instead, do all minibuffer input as part of reading the arguments for a command, in the interactive specification. See section Defining Commands.

Function: read-from-minibuffer prompt-string &optional initial-contents keymap read hist default inherit-input-method
This function is the most general way to get input through the minibuffer. By default, it accepts arbitrary text and returns it as a string; however, if read is non-nil, then it uses read to convert the text into a Lisp object (see section Input Functions).

The first thing this function does is to activate a minibuffer and display it with prompt-string as the prompt. This value must be a string. Then the user can edit text in the minibuffer.

When the user types a command to exit the minibuffer, read-from-minibuffer constructs the return value from the text in the minibuffer. Normally it returns a string containing that text. However, if read is non-nil, read-from-minibuffer reads the text and returns the resulting Lisp object, unevaluated. (See section Input Functions, for information about reading.)

The argument default specifies a default value to make available through the history commands. It should be a string, or nil. If read is non-nil, then default is also used as the input to read, if the user enters empty input. However, in the usual case (where read is nil), read-from-minibuffer does not return default when the user enters empty input; it returns an empty string, "". In this respect, it is different from all the other minibuffer input functions in this chapter.

If keymap is non-nil, that keymap is the local keymap to use in the minibuffer. If keymap is omitted or nil, the value of minibuffer-local-map is used as the keymap. Specifying a keymap is the most important way to customize the minibuffer for various applications such as completion.

The argument hist specifies which history list variable to use for saving the input and for history commands used in the minibuffer. It defaults to minibuffer-history. See section Minibuffer History.

If the variable minibuffer-allow-text-properties is non-nil, then the string which is returned includes whatever text properties were present in the minibuffer. Otherwise all the text properties are stripped when the value is returned.

If the argument inherit-input-method is non-nil, then the minibuffer inherits the current input method (see section Input Methods) and the setting of enable-multibyte-characters (see section Text Representations) from whichever buffer was current before entering the minibuffer.

If initial-contents is a string, read-from-minibuffer inserts it into the minibuffer, leaving point at the end, before the user starts to edit the text. The minibuffer appears with this text as its initial contents.

Alternatively, initial-contents can be a cons cell of the form (string . position). This means to insert string in the minibuffer but put point position characters from the beginning, rather than at the end.

Usage note: The initial-contents argument and the default argument are two alternative features for more or less the same job. It does not make sense to use both features in a single call to read-from-minibuffer. In general, we recommend using default, since this permits the user to insert the default value when it is wanted, but does not burden the user with deleting it from the minibuffer on other occasions.

Function: read-string prompt &optional initial history default inherit-input-method
This function reads a string from the minibuffer and returns it. The arguments prompt and initial are used as in read-from-minibuffer. The keymap used is minibuffer-local-map.

The optional argument history, if non-nil, specifies a history list and optionally the initial position in the list. The optional argument default specifies a default value to return if the user enters null input; it should be a string. The optional argument inherit-input-method specifies whether to inherit the current buffer's input method.

This function is a simplified interface to the read-from-minibuffer function:

(read-string prompt initial history default inherit)
==
(let ((value
       (read-from-minibuffer prompt initial nil nil
                             history default inherit)))
  (if (equal value "")
      default
    value))

Variable: minibuffer-allow-text-properties
If this variable is nil, then read-from-minibuffer strips all text properties from the minibuffer input before returning it. Since all minibuffer input uses read-from-minibuffer, this variable applies to all minibuffer input.

Note that the completion functions discard text properties unconditionally, regardless of the value of this variable.

Variable: minibuffer-local-map
This is the default local keymap for reading from the minibuffer. By default, it makes the following bindings:

C-j
exit-minibuffer
RET
exit-minibuffer
C-g
abort-recursive-edit
M-n
next-history-element
M-p
previous-history-element
M-r
next-matching-history-element
M-s
previous-matching-history-element

Function: read-no-blanks-input prompt &optional initial inherit-input-method
This function reads a string from the minibuffer, but does not allow whitespace characters as part of the input: instead, those characters terminate the input. The arguments prompt, initial, and inherit-input-method are used as in read-from-minibuffer.

This is a simplified interface to the read-from-minibuffer function, and passes the value of the minibuffer-local-ns-map keymap as the keymap argument for that function. Since the keymap minibuffer-local-ns-map does not rebind C-q, it is possible to put a space into the string, by quoting it.

(read-no-blanks-input prompt initial)
==
(read-from-minibuffer prompt initial minibuffer-local-ns-map)

Variable: minibuffer-local-ns-map
This built-in variable is the keymap used as the minibuffer local keymap in the function read-no-blanks-input. By default, it makes the following bindings, in addition to those of minibuffer-local-map:

SPC
exit-minibuffer
TAB
exit-minibuffer
?
self-insert-and-exit

Reading Lisp Objects with the Minibuffer

This section describes functions for reading Lisp objects with the minibuffer.

Function: read-minibuffer prompt &optional initial
This function reads a Lisp object using the minibuffer, and returns it without evaluating it. The arguments prompt and initial are used as in read-from-minibuffer.

This is a simplified interface to the read-from-minibuffer function:

(read-minibuffer prompt initial)
==
(read-from-minibuffer prompt initial nil t)

Here is an example in which we supply the string "(testing)" as initial input:

(read-minibuffer
 "Enter an expression: " (format "%s" '(testing)))

;; Here is how the minibuffer is displayed:

---------- Buffer: Minibuffer ----------
Enter an expression: (testing)-!-
---------- Buffer: Minibuffer ----------

The user can type RET immediately to use the initial input as a default, or can edit the input.

Function: eval-minibuffer prompt &optional initial
This function reads a Lisp expression using the minibuffer, evaluates it, then returns the result. The arguments prompt and initial are used as in read-from-minibuffer.

This function simply evaluates the result of a call to read-minibuffer:

(eval-minibuffer prompt initial)
==
(eval (read-minibuffer prompt initial))

Function: edit-and-eval-command prompt form
This function reads a Lisp expression in the minibuffer, and then evaluates it. The difference between this command and eval-minibuffer is that here the initial form is not optional and it is treated as a Lisp object to be converted to printed representation rather than as a string of text. It is printed with prin1, so if it is a string, double-quote characters (`"') appear in the initial text. See section Output Functions.

The first thing edit-and-eval-command does is to activate the minibuffer with prompt as the prompt. Then it inserts the printed representation of form in the minibuffer, and lets the user edit it. When the user exits the minibuffer, the edited text is read with read and then evaluated. The resulting value becomes the value of edit-and-eval-command.

In the following example, we offer the user an expression with initial text which is a valid form already:

(edit-and-eval-command "Please edit: " '(forward-word 1))

;; After evaluation of the preceding expression, 
;;   the following appears in the minibuffer:

---------- Buffer: Minibuffer ----------
Please edit: (forward-word 1)-!-
---------- Buffer: Minibuffer ----------

Typing RET right away would exit the minibuffer and evaluate the expression, thus moving point forward one word. edit-and-eval-command returns nil in this example.

Minibuffer History

A minibuffer history list records previous minibuffer inputs so the user can reuse them conveniently. A history list is actually a symbol, not a list; it is a variable whose value is a list of strings (previous inputs), most recent first.

There are many separate history lists, used for different kinds of inputs. It's the Lisp programmer's job to specify the right history list for each use of the minibuffer.

The basic minibuffer input functions read-from-minibuffer and completing-read both accept an optional argument named hist which is how you specify the history list. Here are the possible values:

variable
Use variable (a symbol) as the history list.
(variable . startpos)
Use variable (a symbol) as the history list, and assume that the initial history position is startpos (an integer, counting from zero which specifies the most recent element of the history). If you specify startpos, then you should also specify that element of the history as the initial minibuffer contents, for consistency.

If you don't specify hist, then the default history list minibuffer-history is used. For other standard history lists, see below. You can also create your own history list variable; just initialize it to nil before the first use.

Both read-from-minibuffer and completing-read add new elements to the history list automatically, and provide commands to allow the user to reuse items on the list. The only thing your program needs to do to use a history list is to initialize it and to pass its name to the input functions when you wish. But it is safe to modify the list by hand when the minibuffer input functions are not using it.

Here are some of the standard minibuffer history list variables:

Variable: minibuffer-history
The default history list for minibuffer history input.

Variable: query-replace-history
A history list for arguments to query-replace (and similar arguments to other commands).

Variable: file-name-history
A history list for file-name arguments.

Variable: buffer-name-history
A history list for buffer-name arguments.

Variable: regexp-history
A history list for regular expression arguments.

Variable: extended-command-history
A history list for arguments that are names of extended commands.

Variable: shell-command-history
A history list for arguments that are shell commands.

Variable: read-expression-history
A history list for arguments that are Lisp expressions to evaluate.

Completion

Completion is a feature that fills in the rest of a name starting from an abbreviation for it. Completion works by comparing the user's input against a list of valid names and determining how much of the name is determined uniquely by what the user has typed. For example, when you type C-x b (switch-to-buffer) and then type the first few letters of the name of the buffer to which you wish to switch, and then type TAB (minibuffer-complete), Emacs extends the name as far as it can.

Standard Emacs commands offer completion for names of symbols, files, buffers, and processes; with the functions in this section, you can implement completion for other kinds of names.

The try-completion function is the basic primitive for completion: it returns the longest determined completion of a given initial string, with a given set of strings to match against.

The function completing-read provides a higher-level interface for completion. A call to completing-read specifies how to determine the list of valid names. The function then activates the minibuffer with a local keymap that binds a few keys to commands useful for completion. Other functions provide convenient simple interfaces for reading certain kinds of names with completion.

Basic Completion Functions

The two functions try-completion and all-completions have nothing in themselves to do with minibuffers. We describe them in this chapter so as to keep them near the higher-level completion features that do use the minibuffer.

Function: try-completion string collection &optional predicate
This function returns the longest common substring of all possible completions of string in collection. The value of collection must be an alist, an obarray, or a function that implements a virtual set of strings (see below).

Completion compares string against each of the permissible completions specified by collection; if the beginning of the permissible completion equals string, it matches. If no permissible completions match, try-completion returns nil. If only one permissible completion matches, and the match is exact, then try-completion returns t. Otherwise, the value is the longest initial sequence common to all the permissible completions that match.

If collection is an alist (see section Association Lists), the CARs of the alist elements form the set of permissible completions.

If collection is an obarray (see section Creating and Interning Symbols), the names of all symbols in the obarray form the set of permissible completions. The global variable obarray holds an obarray containing the names of all interned Lisp symbols.

Note that the only valid way to make a new obarray is to create it empty and then add symbols to it one by one using intern. Also, you cannot intern a given symbol in more than one obarray.

If the argument predicate is non-nil, then it must be a function of one argument. It is used to test each possible match, and the match is accepted only if predicate returns non-nil. The argument given to predicate is either a cons cell from the alist (the CAR of which is a string) or else it is a symbol (not a symbol name) from the obarray.

You can also use a symbol that is a function as collection. Then the function is solely responsible for performing completion; try-completion returns whatever this function returns. The function is called with three arguments: string, predicate and nil. (The reason for the third argument is so that the same function can be used in all-completions and do the appropriate thing in either case.) See section Programmed Completion.

In the first of the following examples, the string `foo' is matched by three of the alist CARs. All of the matches begin with the characters `fooba', so that is the result. In the second example, there is only one possible match, and it is exact, so the value is t.

(try-completion 
 "foo"
 '(("foobar1" 1) ("barfoo" 2) ("foobaz" 3) ("foobar2" 4)))
     => "fooba"

(try-completion "foo" '(("barfoo" 2) ("foo" 3)))
     => t

In the following example, numerous symbols begin with the characters `forw', and all of them begin with the word `forward'. In most of the symbols, this is followed with a `-', but not in all, so no more than `forward' can be completed.

(try-completion "forw" obarray)
     => "forward"

Finally, in the following example, only two of the three possible matches pass the predicate test (the string `foobaz' is too short). Both of those begin with the string `foobar'.

(defun test (s) 
  (> (length (car s)) 6))
     => test
(try-completion 
 "foo"
 '(("foobar1" 1) ("barfoo" 2) ("foobaz" 3) ("foobar2" 4)) 
 'test)
     => "foobar"

Function: all-completions string collection &optional predicate nospace
This function returns a list of all possible completions of string. The arguments to this function are the same as those of try-completion.

If collection is a function, it is called with three arguments: string, predicate and t; then all-completions returns whatever the function returns. See section Programmed Completion.

If nospace is non-nil, completions that start with a space are ignored unless string also starts with a space.

Here is an example, using the function test shown in the example for try-completion:

(defun test (s) 
  (> (length (car s)) 6))
     => test

(all-completions  
 "foo"
 '(("foobar1" 1) ("barfoo" 2) ("foobaz" 3) ("foobar2" 4))
 'test)
     => ("foobar1" "foobar2")

Variable: completion-ignore-case
If the value of this variable is non-nil, Emacs does not consider case significant in completion.

Completion and the Minibuffer

This section describes the basic interface for reading from the minibuffer with completion.

Function: completing-read prompt collection &optional predicate require-match initial hist default inherit-input-method
This function reads a string in the minibuffer, assisting the user by providing completion. It activates the minibuffer with prompt prompt, which must be a string.

The actual completion is done by passing collection and predicate to the function try-completion. This happens in certain commands bound in the local keymaps used for completion.

If require-match is nil, the exit commands work regardless of the input in the minibuffer. If require-match is t, the usual minibuffer exit commands won't exit unless the input completes to an element of collection. If require-match is neither nil nor t, then the exit commands won't exit unless the input already in the buffer matches an element of collection.

However, empty input is always permitted, regardless of the value of require-match; in that case, completing-read returns default. The value of default (if non-nil) is also available to the user through the history commands.

The user can exit with null input by typing RET with an empty minibuffer. Then completing-read returns "". This is how the user requests whatever default the command uses for the value being read. The user can return using RET in this way regardless of the value of require-match, and regardless of whether the empty string is included in collection.

The function completing-read works by calling read-minibuffer. It uses minibuffer-local-completion-map as the keymap if require-match is nil, and uses minibuffer-local-must-match-map if require-match is non-nil. See section Minibuffer Commands That Do Completion.

The argument hist specifies which history list variable to use for saving the input and for minibuffer history commands. It defaults to minibuffer-history. See section Minibuffer History.

If initial is non-nil, completing-read inserts it into the minibuffer as part of the input. Then it allows the user to edit the input, providing several commands to attempt completion. In most cases, we recommend using default, and not initial.

If the argument inherit-input-method is non-nil, then the minibuffer inherits the current input method (see section Input Methods) and the setting of enable-multibyte-characters (see section Text Representations) from whichever buffer was current before entering the minibuffer.

Completion ignores case when comparing the input against the possible matches, if the built-in variable completion-ignore-case is non-nil. See section Basic Completion Functions.

Here's an example of using completing-read:

(completing-read
 "Complete a foo: "
 '(("foobar1" 1) ("barfoo" 2) ("foobaz" 3) ("foobar2" 4))
 nil t "fo")

;; After evaluation of the preceding expression, 
;;   the following appears in the minibuffer:

---------- Buffer: Minibuffer ----------
Complete a foo: fo-!-
---------- Buffer: Minibuffer ----------

If the user then types DEL DEL b RET, completing-read returns barfoo.

The completing-read function binds three variables to pass information to the commands that actually do completion. These variables are minibuffer-completion-table, minibuffer-completion-predicate and minibuffer-completion-confirm. For more information about them, see section Minibuffer Commands That Do Completion.

Minibuffer Commands That Do Completion

This section describes the keymaps, commands and user options used in the minibuffer to do completion.

Variable: minibuffer-local-completion-map
completing-read uses this value as the local keymap when an exact match of one of the completions is not required. By default, this keymap makes the following bindings:

?
minibuffer-completion-help
SPC
minibuffer-complete-word
TAB
minibuffer-complete

with other characters bound as in minibuffer-local-map (see section Reading Text Strings with the Minibuffer).

Variable: minibuffer-local-must-match-map
completing-read uses this value as the local keymap when an exact match of one of the completions is required. Therefore, no keys are bound to exit-minibuffer, the command that exits the minibuffer unconditionally. By default, this keymap makes the following bindings:

?
minibuffer-completion-help
SPC
minibuffer-complete-word
TAB
minibuffer-complete
C-j
minibuffer-complete-and-exit
RET
minibuffer-complete-and-exit

with other characters bound as in minibuffer-local-map.

Variable: minibuffer-completion-table
The value of this variable is the alist or obarray used for completion in the minibuffer. This is the global variable that contains what completing-read passes to try-completion. It is used by minibuffer completion commands such as minibuffer-complete-word.

Variable: minibuffer-completion-predicate
This variable's value is the predicate that completing-read passes to try-completion. The variable is also used by the other minibuffer completion functions.

Command: minibuffer-complete-word
This function completes the minibuffer contents by at most a single word. Even if the minibuffer contents have only one completion, minibuffer-complete-word does not add any characters beyond the first character that is not a word constituent. See section Syntax Tables.

Command: minibuffer-complete
This function completes the minibuffer contents as far as possible.

Command: minibuffer-complete-and-exit
This function completes the minibuffer contents, and exits if confirmation is not required, i.e., if minibuffer-completion-confirm is nil. If confirmation is required, it is given by repeating this command immediately--the command is programmed to work without confirmation when run twice in succession.

Variable: minibuffer-completion-confirm
When the value of this variable is non-nil, Emacs asks for confirmation of a completion before exiting the minibuffer. The function minibuffer-complete-and-exit checks the value of this variable before it exits.

Command: minibuffer-completion-help
This function creates a list of the possible completions of the current minibuffer contents. It works by calling all-completions using the value of the variable minibuffer-completion-table as the collection argument, and the value of minibuffer-completion-predicate as the predicate argument. The list of completions is displayed as text in a buffer named `*Completions*'.

Function: display-completion-list completions
This function displays completions to the stream in standard-output, usually a buffer. (See section Reading and Printing Lisp Objects, for more information about streams.) The argument completions is normally a list of completions just returned by all-completions, but it does not have to be. Each element may be a symbol or a string, either of which is simply printed, or a list of two strings, which is printed as if the strings were concatenated.

This function is called by minibuffer-completion-help. The most common way to use it is together with with-output-to-temp-buffer, like this:

(with-output-to-temp-buffer "*Completions*"
  (display-completion-list
    (all-completions (buffer-string) my-alist)))

User Option: completion-auto-help
If this variable is non-nil, the completion commands automatically display a list of possible completions whenever nothing can be completed because the next character is not uniquely determined.

High-Level Completion Functions

This section describes the higher-level convenient functions for reading certain sorts of names with completion.

In most cases, you should not call these functions in the middle of a Lisp function. When possible, do all minibuffer input as part of reading the arguments for a command, in the interactive specification. See section Defining Commands.

Function: read-buffer prompt &optional default existing
This function reads the name of a buffer and returns it as a string. The argument default is the default name to use, the value to return if the user exits with an empty minibuffer. If non-nil, it should be a string or a buffer. It is mentioned in the prompt, but is not inserted in the minibuffer as initial input.

If existing is non-nil, then the name specified must be that of an existing buffer. The usual commands to exit the minibuffer do not exit if the text is not valid, and RET does completion to attempt to find a valid name. (However, default is not checked for validity; it is returned, whatever it is, if the user exits with the minibuffer empty.)

In the following example, the user enters `minibuffer.t', and then types RET. The argument existing is t, and the only buffer name starting with the given input is `minibuffer.texi', so that name is the value.

(read-buffer "Buffer name? " "foo" t)
;; After evaluation of the preceding expression, 
;;   the following prompt appears,
;;   with an empty minibuffer:

---------- Buffer: Minibuffer ----------
Buffer name? (default foo) -!-
---------- Buffer: Minibuffer ----------

;; The user types minibuffer.t RET.
     => "minibuffer.texi"

Variable: read-buffer-function
This variable specifies how to read buffer names. For example, if you set this variable to iswitchb-read-buffer, all Emacs commands that call read-buffer to read a buffer name will actually use the iswitchb package to read it.

Function: read-command prompt &optional default
This function reads the name of a command and returns it as a Lisp symbol. The argument prompt is used as in read-from-minibuffer. Recall that a command is anything for which commandp returns t, and a command name is a symbol for which commandp returns t. See section Interactive Call.

The argument default specifies what to return if the user enters null input. It can be a symbol or a string; if it is a string, read-command interns it before returning it. If default is nil, that means no default has been specified; then if the user enters null input, the return value is nil.

(read-command "Command name? ")

;; After evaluation of the preceding expression, 
;;   the following prompt appears with an empty minibuffer:

---------- Buffer: Minibuffer ---------- 
Command name?  
---------- Buffer: Minibuffer ----------

If the user types forward-c RET, then this function returns forward-char.

The read-command function is a simplified interface to completing-read. It uses the variable obarray so as to complete in the set of extant Lisp symbols, and it uses the commandp predicate so as to accept only command names:

(read-command prompt)
==
(intern (completing-read prompt obarray 
                         'commandp t nil))

Function: read-variable prompt &optional default
This function reads the name of a user variable and returns it as a symbol.

The argument default specifies what to return if the user enters null input. It can be a symbol or a string; if it is a string, read-variable interns it before returning it. If default is nil, that means no default has been specified; then if the user enters null input, the return value is nil.

(read-variable "Variable name? ")

;; After evaluation of the preceding expression, 
;;   the following prompt appears, 
;;   with an empty minibuffer:

---------- Buffer: Minibuffer ----------
Variable name? -!-
---------- Buffer: Minibuffer ----------

If the user then types fill-p RET, read-variable returns fill-prefix.

This function is similar to read-command, but uses the predicate user-variable-p instead of commandp:

(read-variable prompt)
==
(intern
 (completing-read prompt obarray
                  'user-variable-p t nil))

See also the functions read-coding-system and read-non-nil-coding-system, in section User-Chosen Coding Systems.

Reading File Names

Here is another high-level completion function, designed for reading a file name. It provides special features including automatic insertion of the default directory.

Function: read-file-name prompt &optional directory default existing initial
This function reads a file name in the minibuffer, prompting with prompt and providing completion. If default is non-nil, then the function returns default if the user just types RET. default is not checked for validity; it is returned, whatever it is, if the user exits with the minibuffer empty.

If existing is non-nil, then the user must specify the name of an existing file; RET performs completion to make the name valid if possible, and then refuses to exit if it is not valid. If the value of existing is neither nil nor t, then RET also requires confirmation after completion. If existing is nil, then the name of a nonexistent file is acceptable.

The argument directory specifies the directory to use for completion of relative file names. If insert-default-directory is non-nil, directory is also inserted in the minibuffer as initial input. It defaults to the current buffer's value of default-directory.

If you specify initial, that is an initial file name to insert in the buffer (after directory, if that is inserted). In this case, point goes at the beginning of initial. The default for initial is nil---don't insert any file name. To see what initial does, try the command C-x C-v. Note: we recommend using default rather than initial in most cases.

Here is an example:

(read-file-name "The file is ")

;; After evaluation of the preceding expression, 
;;   the following appears in the minibuffer:

---------- Buffer: Minibuffer ----------
The file is /gp/gnu/elisp/-!-
---------- Buffer: Minibuffer ----------

Typing manual TAB results in the following:

---------- Buffer: Minibuffer ----------
The file is /gp/gnu/elisp/manual.texi-!-
---------- Buffer: Minibuffer ----------

If the user types RET, read-file-name returns the file name as the string "/gp/gnu/elisp/manual.texi".

User Option: insert-default-directory
This variable is used by read-file-name. Its value controls whether read-file-name starts by placing the name of the default directory in the minibuffer, plus the initial file name if any. If the value of this variable is nil, then read-file-name does not place any initial input in the minibuffer (unless you specify initial input with the initial argument). In that case, the default directory is still used for completion of relative file names, but is not displayed.

For example:

;; Here the minibuffer starts out with the default directory.
(let ((insert-default-directory t))
  (read-file-name "The file is "))

---------- Buffer: Minibuffer ----------
The file is ~lewis/manual/-!-
---------- Buffer: Minibuffer ----------

;; Here the minibuffer is empty and only the prompt
;;   appears on its line.
(let ((insert-default-directory nil))
  (read-file-name "The file is "))

---------- Buffer: Minibuffer ----------
The file is -!-
---------- Buffer: Minibuffer ----------

Programmed Completion

Sometimes it is not possible to create an alist or an obarray containing all the intended possible completions. In such a case, you can supply your own function to compute the completion of a given string. This is called programmed completion.

To use this feature, pass a symbol with a function definition as the collection argument to completing-read. The function completing-read arranges to pass your completion function along to try-completion and all-completions, which will then let your function do all the work.

The completion function should accept three arguments:

There are three flag values for three operations:

It would be consistent and clean for completion functions to allow lambda expressions (lists that are functions) as well as function symbols as collection, but this is impossible. Lists as completion tables are already assigned another meaning--as alists. It would be unreliable to fail to handle an alist normally because it is also a possible function. So you must arrange for any function you wish to use for completion to be encapsulated in a symbol.

Emacs uses programmed completion when completing file names. See section File Name Completion.

Yes-or-No Queries

This section describes functions used to ask the user a yes-or-no question. The function y-or-n-p can be answered with a single character; it is useful for questions where an inadvertent wrong answer will not have serious consequences. yes-or-no-p is suitable for more momentous questions, since it requires three or four characters to answer.

If either of these functions is called in a command that was invoked using the mouse--more precisely, if last-nonmenu-event (see section Information from the Command Loop) is either nil or a list--then it uses a dialog box or pop-up menu to ask the question. Otherwise, it uses keyboard input. You can force use of the mouse or use of keyboard input by binding last-nonmenu-event to a suitable value around the call.

Strictly speaking, yes-or-no-p uses the minibuffer and y-or-n-p does not; but it seems best to describe them together.

Function: y-or-n-p prompt
This function asks the user a question, expecting input in the echo area. It returns t if the user types y, nil if the user types n. This function also accepts SPC to mean yes and DEL to mean no. It accepts C-] to mean "quit", like C-g, because the question might look like a minibuffer and for that reason the user might try to use C-] to get out. The answer is a single character, with no RET needed to terminate it. Upper and lower case are equivalent.

"Asking the question" means printing prompt in the echo area, followed by the string `(y or n) '. If the input is not one of the expected answers (y, n, SPC, DEL, or something that quits), the function responds `Please answer y or n.', and repeats the request.

This function does not actually use the minibuffer, since it does not allow editing of the answer. It actually uses the echo area (see section The Echo Area), which uses the same screen space as the minibuffer. The cursor moves to the echo area while the question is being asked.

The answers and their meanings, even `y' and `n', are not hardwired. The keymap query-replace-map specifies them. See section Search and Replace.

In the following example, the user first types q, which is invalid. At the next prompt the user types y.

(y-or-n-p "Do you need a lift? ")

;; After evaluation of the preceding expression, 
;;   the following prompt appears in the echo area:

---------- Echo area ----------
Do you need a lift? (y or n) 
---------- Echo area ----------

;; If the user then types q, the following appears:

---------- Echo area ----------
Please answer y or n.  Do you need a lift? (y or n) 
---------- Echo area ----------

;; When the user types a valid answer,
;;   it is displayed after the question:

---------- Echo area ----------
Do you need a lift? (y or n) y
---------- Echo area ----------

We show successive lines of echo area messages, but only one actually appears on the screen at a time.

Function: y-or-n-p-with-timeout prompt seconds default-value
Like y-or-n-p, except that if the user fails to answer within seconds seconds, this function stops waiting and returns default-value. It works by setting up a timer; see section Timers for Delayed Execution. The argument seconds may be an integer or a floating point number.

Function: yes-or-no-p prompt
This function asks the user a question, expecting input in the minibuffer. It returns t if the user enters `yes', nil if the user types `no'. The user must type RET to finalize the response. Upper and lower case are equivalent.

yes-or-no-p starts by displaying prompt in the echo area, followed by `(yes or no) '. The user must type one of the expected responses; otherwise, the function responds `Please answer yes or no.', waits about two seconds and repeats the request.

yes-or-no-p requires more work from the user than y-or-n-p and is appropriate for more crucial decisions.

Here is an example:

(yes-or-no-p "Do you really want to remove everything? ")

;; After evaluation of the preceding expression, 
;;   the following prompt appears, 
;;   with an empty minibuffer:

---------- Buffer: minibuffer ----------
Do you really want to remove everything? (yes or no) 
---------- Buffer: minibuffer ----------

If the user first types y RET, which is invalid because this function demands the entire word `yes', it responds by displaying these prompts, with a brief pause between them:

---------- Buffer: minibuffer ----------
Please answer yes or no.
Do you really want to remove everything? (yes or no)
---------- Buffer: minibuffer ----------

Asking Multiple Y-or-N Questions

When you have a series of similar questions to ask, such as "Do you want to save this buffer" for each buffer in turn, you should use map-y-or-n-p to ask the collection of questions, rather than asking each question individually. This gives the user certain convenient facilities such as the ability to answer the whole series at once.

Function: map-y-or-n-p prompter actor list &optional help action-alist
This function asks the user a series of questions, reading a single-character answer in the echo area for each one.

The value of list specifies the objects to ask questions about. It should be either a list of objects or a generator function. If it is a function, it should expect no arguments, and should return either the next object to ask about, or nil meaning stop asking questions.

The argument prompter specifies how to ask each question. If prompter is a string, the question text is computed like this:

(format prompter object)

where object is the next object to ask about (as obtained from list).

If not a string, prompter should be a function of one argument (the next object to ask about) and should return the question text. If the value is a string, that is the question to ask the user. The function can also return t meaning do act on this object (and don't ask the user), or nil meaning ignore this object (and don't ask the user).

The argument actor says how to act on the answers that the user gives. It should be a function of one argument, and it is called with each object that the user says yes for. Its argument is always an object obtained from list.

If the argument help is given, it should be a list of this form:

(singular plural action)

where singular is a string containing a singular noun that describes the objects conceptually being acted on, plural is the corresponding plural noun, and action is a transitive verb describing what actor does.

If you don't specify help, the default is ("object" "objects" "act on").

Each time a question is asked, the user may enter y, Y, or SPC to act on that object; n, N, or DEL to skip that object; ! to act on all following objects; ESC or q to exit (skip all following objects); . (period) to act on the current object and then exit; or C-h to get help. These are the same answers that query-replace accepts. The keymap query-replace-map defines their meaning for map-y-or-n-p as well as for query-replace; see section Search and Replace.

You can use action-alist to specify additional possible answers and what they mean. It is an alist of elements of the form (char function help), each of which defines one additional answer. In this element, char is a character (the answer); function is a function of one argument (an object from list); help is a string.

When the user responds with char, map-y-or-n-p calls function. If it returns non-nil, the object is considered "acted upon", and map-y-or-n-p advances to the next object in list. If it returns nil, the prompt is repeated for the same object.

If map-y-or-n-p is called in a command that was invoked using the mouse--more precisely, if last-nonmenu-event (see section Information from the Command Loop) is either nil or a list--then it uses a dialog box or pop-up menu to ask the question. In this case, it does not use keyboard input or the echo area. You can force use of the mouse or use of keyboard input by binding last-nonmenu-event to a suitable value around the call.

The return value of map-y-or-n-p is the number of objects acted on.

Reading a Password

To read a password to pass to another program, you can use the function read-passwd.

Function: read-passwd prompt &optional confirm default
This function reads a password, prompting with prompt. It does not echo the password as the user types it; instead, it echoes `.' for each character in the password.

The optional argument confirm, if non-nil, says to read the password twice and insist it must be the same both times. If it isn't the same, the user has to type it over and over until the last two times match.

The optional argument default specifies the default password to return if the user enters empty input. If default is nil, then read-passwd returns the null string in that case.

Minibuffer Miscellany

This section describes some basic functions and variables related to minibuffers.

Command: exit-minibuffer
This command exits the active minibuffer. It is normally bound to keys in minibuffer local keymaps.

Command: self-insert-and-exit
This command exits the active minibuffer after inserting the last character typed on the keyboard (found in last-command-char; see section Information from the Command Loop).

Command: previous-history-element n
This command replaces the minibuffer contents with the value of the nth previous (older) history element.

Command: next-history-element n
This command replaces the minibuffer contents with the value of the nth more recent history element.

Command: previous-matching-history-element pattern
This command replaces the minibuffer contents with the value of the previous (older) history element that matches pattern (a regular expression).

Command: next-matching-history-element pattern
This command replaces the minibuffer contents with the value of the next (newer) history element that matches pattern (a regular expression).

Function: minibuffer-prompt
This function returns the prompt string of the currently active minibuffer. If no minibuffer is active, it returns nil.

Function: minibuffer-prompt-width
This function returns the display width of the prompt string of the currently active minibuffer. If no minibuffer is active, it returns 0.

Variable: minibuffer-setup-hook
This is a normal hook that is run whenever the minibuffer is entered. See section Hooks.

Variable: minibuffer-exit-hook
This is a normal hook that is run whenever the minibuffer is exited. See section Hooks.

Variable: minibuffer-help-form
The current value of this variable is used to rebind help-form locally inside the minibuffer (see section Help Functions).

Function: active-minibuffer-window
This function returns the currently active minibuffer window, or nil if none is currently active.

Function: minibuffer-window &optional frame
This function returns the minibuffer window used for frame frame. If frame is nil, that stands for the current frame. Note that the minibuffer window used by a frame need not be part of that frame--a frame that has no minibuffer of its own necessarily uses some other frame's minibuffer window.

Function: window-minibuffer-p window
This function returns non-nil if window is a minibuffer window.

It is not correct to determine whether a given window is a minibuffer by comparing it with the result of (minibuffer-window), because there can be more than one minibuffer window if there is more than one frame.

Function: minibuffer-window-active-p window
This function returns non-nil if window, assumed to be a minibuffer window, is currently active.

Variable: minibuffer-scroll-window
If the value of this variable is non-nil, it should be a window object. When the function scroll-other-window is called in the minibuffer, it scrolls this window.

Finally, some functions and variables deal with recursive minibuffers (see section Recursive Editing):

Function: minibuffer-depth
This function returns the current depth of activations of the minibuffer, a nonnegative integer. If no minibuffers are active, it returns zero.

User Option: enable-recursive-minibuffers
If this variable is non-nil, you can invoke commands (such as find-file) that use minibuffers even while the minibuffer window is active. Such invocation produces a recursive editing level for a new minibuffer. The outer-level minibuffer is invisible while you are editing the inner one.

If this variable is nil, you cannot invoke minibuffer commands when the minibuffer window is active, not even if you switch to another window to do it.

If a command name has a property enable-recursive-minibuffers that is non-nil, then the command can use the minibuffer to read arguments even if it is invoked from the minibuffer. The minibuffer command next-matching-history-element (normally M-s in the minibuffer) uses this feature.

Command Loop

When you run Emacs, it enters the editor command loop almost immediately. This loop reads key sequences, executes their definitions, and displays the results. In this chapter, we describe how these things are done, and the subroutines that allow Lisp programs to do them.

Command Loop Overview

The first thing the command loop must do is read a key sequence, which is a sequence of events that translates into a command. It does this by calling the function read-key-sequence. Your Lisp code can also call this function (see section Key Sequence Input). Lisp programs can also do input at a lower level with read-event (see section Reading One Event) or discard pending input with discard-input (see section Miscellaneous Event Input Features).

The key sequence is translated into a command through the currently active keymaps. See section Key Lookup, for information on how this is done. The result should be a keyboard macro or an interactively callable function. If the key is M-x, then it reads the name of another command, which it then calls. This is done by the command execute-extended-command (see section Interactive Call).

To execute a command requires first reading the arguments for it. This is done by calling command-execute (see section Interactive Call). For commands written in Lisp, the interactive specification says how to read the arguments. This may use the prefix argument (see section Prefix Command Arguments) or may read with prompting in the minibuffer (see section Minibuffers). For example, the command find-file has an interactive specification which says to read a file name using the minibuffer. The command's function body does not use the minibuffer; if you call this command from Lisp code as a function, you must supply the file name string as an ordinary Lisp function argument.

If the command is a string or vector (i.e., a keyboard macro) then execute-kbd-macro is used to execute it. You can call this function yourself (see section Keyboard Macros).

To terminate the execution of a running command, type C-g. This character causes quitting (see section Quitting).

Variable: pre-command-hook
The editor command loop runs this normal hook before each command. At that time, this-command contains the command that is about to run, and last-command describes the previous command. See section Hooks.

Variable: post-command-hook
The editor command loop runs this normal hook after each command (including commands terminated prematurely by quitting or by errors), and also when the command loop is first entered. At that time, this-command describes the command that just ran, and last-command describes the command before that. See section Hooks.

Quitting is suppressed while running pre-command-hook and post-command-hook. If an error happens while executing one of these hooks, it terminates execution of the hook, and clears the hook variable to nil so as to prevent an infinite loop of errors.

Defining Commands

A Lisp function becomes a command when its body contains, at top level, a form that calls the special form interactive. This form does nothing when actually executed, but its presence serves as a flag to indicate that interactive calling is permitted. Its argument controls the reading of arguments for an interactive call.

Using interactive

This section describes how to write the interactive form that makes a Lisp function an interactively-callable command.

Special Form: interactive arg-descriptor
This special form declares that the function in which it appears is a command, and that it may therefore be called interactively (via M-x or by entering a key sequence bound to it). The argument arg-descriptor declares how to compute the arguments to the command when the command is called interactively.

A command may be called from Lisp programs like any other function, but then the caller supplies the arguments and arg-descriptor has no effect.

The interactive form has its effect because the command loop (actually, its subroutine call-interactively) scans through the function definition looking for it, before calling the function. Once the function is called, all its body forms including the interactive form are executed, but at this time interactive simply returns nil without even evaluating its argument.

There are three possibilities for the argument arg-descriptor:

Code Characters for interactive

The code character descriptions below contain a number of key words, defined here as follows:

Completion
Provide completion. TAB, SPC, and RET perform name completion because the argument is read using completing-read (see section Completion). ? displays a list of possible completions.
Existing
Require the name of an existing object. An invalid name is not accepted; the commands to exit the minibuffer do not exit if the current input is not valid.
Default
A default value of some sort is used if the user enters no text in the minibuffer. The default depends on the code character.
No I/O
This code letter computes an argument without reading any input. Therefore, it does not use a prompt string, and any prompt string you supply is ignored. Even though the code letter doesn't use a prompt string, you must follow it with a newline if it is not the last code character in the string.
Prompt
A prompt immediately follows the code character. The prompt ends either with the end of the string or with a newline.
Special
This code character is meaningful only at the beginning of the interactive string, and it does not look for a prompt or a newline. It is a single, isolated character.

Here are the code character descriptions for use with interactive:

`*'
Signal an error if the current buffer is read-only. Special.
`@'
Select the window mentioned in the first mouse event in the key sequence that invoked this command. Special.
`a'
A function name (i.e., a symbol satisfying fboundp). Existing, Completion, Prompt.
`b'
The name of an existing buffer. By default, uses the name of the current buffer (see section Buffers). Existing, Completion, Default, Prompt.
`B'
A buffer name. The buffer need not exist. By default, uses the name of a recently used buffer other than the current buffer. Completion, Default, Prompt.
`c'
A character. The cursor does not move into the echo area. Prompt.
`C'
A command name (i.e., a symbol satisfying commandp). Existing, Completion, Prompt.
`d'
The position of point, as an integer (see section Point). No I/O.
`D'
A directory name. The default is the current default directory of the current buffer, default-directory (see section Operating System Environment). Existing, Completion, Default, Prompt.
`e'
The first or next mouse event in the key sequence that invoked the command. More precisely, `e' gets events that are lists, so you can look at the data in the lists. See section Input Events. No I/O. You can use `e' more than once in a single command's interactive specification. If the key sequence that invoked the command has n events that are lists, the nth `e' provides the nth such event. Events that are not lists, such as function keys and ASCII characters, do not count where `e' is concerned.
`f'
A file name of an existing file (see section File Names). The default directory is default-directory. Existing, Completion, Default, Prompt.
`F'
A file name. The file need not exist. Completion, Default, Prompt.
`i'
An irrelevant argument. This code always supplies nil as the argument's value. No I/O.
`k'
A key sequence (see section Keymap Terminology). This keeps reading events until a command (or undefined command) is found in the current key maps. The key sequence argument is represented as a string or vector. The cursor does not move into the echo area. Prompt. This kind of input is used by commands such as describe-key and global-set-key.
`K'
A key sequence, whose definition you intend to change. This works like `k', except that it suppresses, for the last input event in the key sequence, the conversions that are normally used (when necessary) to convert an undefined key into a defined one.
`m'
The position of the mark, as an integer. No I/O.
`M'
Arbitrary text, read in the minibuffer using the current buffer's input method, and returned as a string (see section `Input Methods' in The GNU Emacs Manual). Prompt.
`n'
A number read with the minibuffer. If the input is not a number, the user is asked to try again. The prefix argument, if any, is not used. Prompt.
`N'
The numeric prefix argument; but if there is no prefix argument, read a number as with n. Requires a number. See section Prefix Command Arguments. Prompt.
`p'
The numeric prefix argument. (Note that this `p' is lower case.) No I/O.
`P'
The raw prefix argument. (Note that this `P' is upper case.) No I/O.
`r'
Point and the mark, as two numeric arguments, smallest first. This is the only code letter that specifies two successive arguments rather than one. No I/O.
`s'
Arbitrary text, read in the minibuffer and returned as a string (see section Reading Text Strings with the Minibuffer). Terminate the input with either C-j or RET. (C-q may be used to include either of these characters in the input.) Prompt.
`S'
An interned symbol whose name is read in the minibuffer. Any whitespace character terminates the input. (Use C-q to include whitespace in the string.) Other characters that normally terminate a symbol (e.g., parentheses and brackets) do not do so here. Prompt.
`v'
A variable declared to be a user option (i.e., satisfying the predicate user-variable-p). See section High-Level Completion Functions. Existing, Completion, Prompt.
`x'
A Lisp object, specified with its read syntax, terminated with a C-j or RET. The object is not evaluated. See section Reading Lisp Objects with the Minibuffer. Prompt.
`X'
A Lisp form is read as with x, but then evaluated so that its value becomes the argument for the command. Prompt.
`z'
A coding system name (a symbol). If the user enters null input, the argument value is nil. See section Coding Systems. Completion, Existing, Prompt.
`Z'
A coding system name (a symbol)---but only if this command has a prefix argument. With no prefix argument, `Z' provides nil as the argument value. Completion, Existing, Prompt.

Examples of Using interactive

Here are some examples of interactive:

(defun foo1 ()              ; foo1 takes no arguments,
    (interactive)           ;   just moves forward two words.
    (forward-word 2))
     => foo1

(defun foo2 (n)             ; foo2 takes one argument,
    (interactive "p")       ;   which is the numeric prefix.
    (forward-word (* 2 n)))
     => foo2

(defun foo3 (n)             ; foo3 takes one argument,
    (interactive "nCount:") ;   which is read with the Minibuffer.
    (forward-word (* 2 n)))
     => foo3

(defun three-b (b1 b2 b3)
  "Select three existing buffers.
Put them into three windows, selecting the last one."
    (interactive "bBuffer1:\nbBuffer2:\nbBuffer3:")
    (delete-other-windows)
    (split-window (selected-window) 8)
    (switch-to-buffer b1)
    (other-window 1)
    (split-window (selected-window) 8)
    (switch-to-buffer b2)
    (other-window 1)
    (switch-to-buffer b3))
     => three-b
(three-b "*scratch*" "declarations.texi" "*mail*")
     => nil

Interactive Call

After the command loop has translated a key sequence into a command it invokes that command using the function command-execute. If the command is a function, command-execute calls call-interactively, which reads the arguments and calls the command. You can also call these functions yourself.

Function: commandp object
Returns t if object is suitable for calling interactively; that is, if object is a command. Otherwise, returns nil.

The interactively callable objects include strings and vectors (treated as keyboard macros), lambda expressions that contain a top-level call to interactive, byte-code function objects made from such lambda expressions, autoload objects that are declared as interactive (non-nil fourth argument to autoload), and some of the primitive functions.

A symbol satisfies commandp if its function definition satisfies commandp.

Keys and keymaps are not commands. Rather, they are used to look up commands (see section Keymaps).

See documentation in section Access to Documentation Strings, for a realistic example of using commandp.

Function: call-interactively command &optional record-flag keys
This function calls the interactively callable function command, reading arguments according to its interactive calling specifications. An error is signaled if command is not a function or if it cannot be called interactively (i.e., is not a command). Note that keyboard macros (strings and vectors) are not accepted, even though they are considered commands, because they are not functions.

If record-flag is non-nil, then this command and its arguments are unconditionally added to the list command-history. Otherwise, the command is added only if it uses the minibuffer to read an argument. See section Command History.

The argument keys, if given, specifies the sequence of events to supply if the command inquires which events were used to invoke it.

Function: command-execute command &optional record-flag keys
This function executes command. The argument command must satisfy the commandp predicate; i.e., it must be an interactively callable function or a keyboard macro.

A string or vector as command is executed with execute-kbd-macro. A function is passed to call-interactively, along with the optional record-flag.

A symbol is handled by using its function definition in its place. A symbol with an autoload definition counts as a command if it was declared to stand for an interactively callable function. Such a definition is handled by loading the specified library and then rechecking the definition of the symbol.

The argument keys, if given, specifies the sequence of events to supply if the command inquires which events were used to invoke it.

Command: execute-extended-command prefix-argument
This function reads a command name from the minibuffer using completing-read (see section Completion). Then it uses command-execute to call the specified command. Whatever that command returns becomes the value of execute-extended-command.

If the command asks for a prefix argument, it receives the value prefix-argument. If execute-extended-command is called interactively, the current raw prefix argument is used for prefix-argument, and thus passed on to whatever command is run.

execute-extended-command is the normal definition of M-x, so it uses the string `M-x ' as a prompt. (It would be better to take the prompt from the events used to invoke execute-extended-command, but that is painful to implement.) A description of the value of the prefix argument, if any, also becomes part of the prompt.

(execute-extended-command 1)
---------- Buffer: Minibuffer ----------
1 M-x forward-word RET
---------- Buffer: Minibuffer ----------
     => t

Function: interactive-p
This function returns t if the containing function (the one whose code includes the call to interactive-p) was called interactively, with the function call-interactively. (It makes no difference whether call-interactively was called from Lisp or directly from the editor command loop.) If the containing function was called by Lisp evaluation (or with apply or funcall), then it was not called interactively.

The most common use of interactive-p is for deciding whether to print an informative message. As a special exception, interactive-p returns nil whenever a keyboard macro is being run. This is to suppress the informative messages and speed execution of the macro.

For example:

(defun foo ()
  (interactive)
  (when (interactive-p)
    (message "foo")))
     => foo

(defun bar ()
  (interactive)
  (setq foobar (list (foo) (interactive-p))))
     => bar

;; Type M-x foo.
     -| foo

;; Type M-x bar.
;; This does not print anything.

foobar
     => (nil t)

The other way to do this sort of job is to make the command take an argument print-message which should be non-nil in an interactive call, and use the interactive spec to make sure it is non-nil. Here's how:

(defun foo (&optional print-message)
  (interactive "p")
  (when print-message
    (message "foo")))

The numeric prefix argument, provided by `p', is never nil.

Information from the Command Loop

The editor command loop sets several Lisp variables to keep status records for itself and for commands that are run.

Variable: last-command
This variable records the name of the previous command executed by the command loop (the one before the current command). Normally the value is a symbol with a function definition, but this is not guaranteed.

The value is copied from this-command when a command returns to the command loop, except when the command has specified a prefix argument for the following command.

This variable is always local to the current terminal and cannot be buffer-local. See section Multiple Displays.

Variable: real-last-command
This variable is set up by Emacs just like last-command, but never altered by Lisp programs.

Variable: this-command
This variable records the name of the command now being executed by the editor command loop. Like last-command, it is normally a symbol with a function definition.

The command loop sets this variable just before running a command, and copies its value into last-command when the command finishes (unless the command specified a prefix argument for the following command).

Some commands set this variable during their execution, as a flag for whatever command runs next. In particular, the functions for killing text set this-command to kill-region so that any kill commands immediately following will know to append the killed text to the previous kill.

If you do not want a particular command to be recognized as the previous command in the case where it got an error, you must code that command to prevent this. One way is to set this-command to t at the beginning of the command, and set this-command back to its proper value at the end, like this:

(defun foo (args...)
  (interactive ...)
  (let ((old-this-command this-command))
    (setq this-command t)
    ...do the work...
    (setq this-command old-this-command)))

We do not bind this-command with let because that would restore the old value in case of error--a feature of let which in this case does precisely what we want to avoid.

Function: this-command-keys
This function returns a string or vector containing the key sequence that invoked the present command, plus any previous commands that generated the prefix argument for this command. The value is a string if all those events were characters. See section Input Events.

(this-command-keys)
;; Now use C-u C-x C-e to evaluate that.
     => "^U^X^E"

Function: this-command-keys-vector
Like this-command-keys, except that it always returns the events in a vector, so you do never need to deal with the complexities of storing input events in a string (see section Putting Keyboard Events in Strings).

Variable: last-nonmenu-event
This variable holds the last input event read as part of a key sequence, not counting events resulting from mouse menus.

One use of this variable is for telling x-popup-menu where to pop up a menu. It is also used internally by y-or-n-p (see section Yes-or-No Queries).

Variable: last-command-event
Variable: last-command-char
This variable is set to the last input event that was read by the command loop as part of a command. The principal use of this variable is in self-insert-command, which uses it to decide which character to insert.

last-command-event
;; Now use C-u C-x C-e to evaluate that.
     => 5

The value is 5 because that is the ASCII code for C-e.

The alias last-command-char exists for compatibility with Emacs version 18.

Variable: last-event-frame
This variable records which frame the last input event was directed to. Usually this is the frame that was selected when the event was generated, but if that frame has redirected input focus to another frame, the value is the frame to which the event was redirected. See section Input Focus.

Input Events

The Emacs command loop reads a sequence of input events that represent keyboard or mouse activity. The events for keyboard activity are characters or symbols; mouse events are always lists. This section describes the representation and meaning of input events in detail.

Function: eventp object
This function returns non-nil if object is an input event or event type.

Note that any symbol might be used as an event or an event type. eventp cannot distinguish whether a symbol is intended by Lisp code to be used as an event. Instead, it distinguishes whether the symbol has actually been used in an event that has been read as input in the current Emacs session. If a symbol has not yet been so used, eventp returns nil.

Keyboard Events

There are two kinds of input you can get from the keyboard: ordinary keys, and function keys. Ordinary keys correspond to characters; the events they generate are represented in Lisp as characters. The event type of a character event is the character itself (an integer); see section Classifying Events.

An input character event consists of a basic code between 0 and 524287, plus any or all of these modifier bits:

meta
The bit in the character code indicates a character typed with the meta key held down.
control
The bit in the character code indicates a non-ASCII control character. ASCII control characters such as C-a have special basic codes of their own, so Emacs needs no special bit to indicate them. Thus, the code for C-a is just 1. But if you type a control combination not in ASCII, such as % with the control key, the numeric value you get is the code for % plus (assuming the terminal supports non-ASCII control characters).
shift
The bit in the character code indicates an ASCII control character typed with the shift key held down. For letters, the basic code itself indicates upper versus lower case; for digits and punctuation, the shift key selects an entirely different character with a different basic code. In order to keep within the ASCII character set whenever possible, Emacs avoids using the bit for those characters. However, ASCII provides no way to distinguish C-A from C-a, so Emacs uses the bit in C-A and not in C-a.
hyper
The bit in the character code indicates a character typed with the hyper key held down.
super
The bit in the character code indicates a character typed with the super key held down.
alt
The bit in the character code indicates a character typed with the alt key held down. (On some terminals, the key labeled ALT is actually the meta key.)

It is best to avoid mentioning specific bit numbers in your program. To test the modifier bits of a character, use the function event-modifiers (see section Classifying Events). When making key bindings, you can use the read syntax for characters with modifier bits (`\C-', `\M-', and so on). For making key bindings with define-key, you can use lists such as (control hyper ?x) to specify the characters (see section Changing Key Bindings). The function event-convert-list converts such a list into an event type (see section Classifying Events).

Function Keys

Most keyboards also have function keys---keys that have names or symbols that are not characters. Function keys are represented in Emacs Lisp as symbols; the symbol's name is the function key's label, in lower case. For example, pressing a key labeled F1 places the symbol f1 in the input stream.

The event type of a function key event is the event symbol itself. See section Classifying Events.

Here are a few special cases in the symbol-naming convention for function keys:

backspace, tab, newline, return, delete
These keys correspond to common ASCII control characters that have special keys on most keyboards. In ASCII, C-i and TAB are the same character. If the terminal can distinguish between them, Emacs conveys the distinction to Lisp programs by representing the former as the integer 9, and the latter as the symbol tab. Most of the time, it's not useful to distinguish the two. So normally function-key-map (see section Translating Input Events) is set up to map tab into 9. Thus, a key binding for character code 9 (the character C-i) also applies to tab. Likewise for the other symbols in this group. The function read-char likewise converts these events into characters. In ASCII, BS is really C-h. But backspace converts into the character code 127 (DEL), not into code 8 (BS). This is what most users prefer.
left, up, right, down
Cursor arrow keys
kp-add, kp-decimal, kp-divide, ...
Keypad keys (to the right of the regular keyboard).
kp-0, kp-1, ...
Keypad keys with digits.
kp-f1, kp-f2, kp-f3, kp-f4
Keypad PF keys.
kp-home, kp-left, kp-up, kp-right, kp-down
Keypad arrow keys. Emacs normally translates these into the corresponding non-keypad keys home, left, ...
kp-prior, kp-next, kp-end, kp-begin, kp-insert, kp-delete
Additional keypad duplicates of keys ordinarily found elsewhere. Emacs normally translates these into the like-named non-keypad keys.

You can use the modifier keys ALT, CTRL, HYPER, META, SHIFT, and SUPER with function keys. The way to represent them is with prefixes in the symbol name:

`A-'
The alt modifier.
`C-'
The control modifier.
`H-'
The hyper modifier.
`M-'
The meta modifier.
`S-'
The shift modifier.
`s-'
The super modifier.

Thus, the symbol for the key F3 with META held down is M-f3. When you use more than one prefix, we recommend you write them in alphabetical order; but the order does not matter in arguments to the key-binding lookup and modification functions.

Mouse Events

Emacs supports four kinds of mouse events: click events, drag events, button-down events, and motion events. All mouse events are represented as lists. The CAR of the list is the event type; this says which mouse button was involved, and which modifier keys were used with it. The event type can also distinguish double or triple button presses (see section Repeat Events). The rest of the list elements give position and time information.

For key lookup, only the event type matters: two events of the same type necessarily run the same command. The command can access the full values of these events using the `e' interactive code. See section Code Characters for interactive.

A key sequence that starts with a mouse event is read using the keymaps of the buffer in the window that the mouse was in, not the current buffer. This does not imply that clicking in a window selects that window or its buffer--that is entirely under the control of the command binding of the key sequence.

Click Events

When the user presses a mouse button and releases it at the same location, that generates a click event. Mouse click events have this form:

(event-type
 (window buffer-pos (x . y) timestamp)
 click-count)

Here is what the elements normally mean:

event-type
This is a symbol that indicates which mouse button was used. It is one of the symbols mouse-1, mouse-2, ..., where the buttons are numbered left to right. You can also use prefixes `A-', `C-', `H-', `M-', `S-' and `s-' for modifiers alt, control, hyper, meta, shift and super, just as you would with function keys. This symbol also serves as the event type of the event. Key bindings describe events by their types; thus, if there is a key binding for mouse-1, that binding would apply to all events whose event-type is mouse-1.
window
This is the window in which the click occurred.
x, y
These are the pixel-denominated coordinates of the click, relative to the top left corner of window, which is (0 . 0).
buffer-pos
This is the buffer position of the character clicked on.
timestamp
This is the time at which the event occurred, in milliseconds. (Since this value wraps around the entire range of Emacs Lisp integers in about five hours, it is useful only for relating the times of nearby events.)
click-count
This is the number of rapid repeated presses so far of the same mouse button. See section Repeat Events.

The meanings of buffer-pos, x and y are somewhat different when the event location is in a special part of the screen, such as the mode line or a scroll bar.

If the location is in a scroll bar, then buffer-pos is the symbol vertical-scroll-bar or horizontal-scroll-bar, and the pair (x . y) is replaced with a pair (portion . whole), where portion is the distance of the click from the top or left end of the scroll bar, and whole is the length of the entire scroll bar.

If the position is on a mode line or the vertical line separating window from its neighbor to the right, then buffer-pos is the symbol mode-line or vertical-line. For the mode line, y does not have meaningful data. For the vertical line, x does not have meaningful data.

In one special case, buffer-pos is a list containing a symbol (one of the symbols listed above) instead of just the symbol. This happens after the imaginary prefix keys for the event are inserted into the input stream. See section Key Sequence Input.

Drag Events

With Emacs, you can have a drag event without even changing your clothes. A drag event happens every time the user presses a mouse button and then moves the mouse to a different character position before releasing the button. Like all mouse events, drag events are represented in Lisp as lists. The lists record both the starting mouse position and the final position, like this:

(event-type
 (window1 buffer-pos1 (x1 . y1) timestamp1)
 (window2 buffer-pos2 (x2 . y2) timestamp2)
 click-count)

For a drag event, the name of the symbol event-type contains the prefix `drag-'. For example, dragging the mouse with button 2 held down generates a drag-mouse-2 event. The second and third elements of the event give the starting and ending position of the drag. Aside from that, the data have the same meanings as in a click event (see section Click Events). You can access the second element of any mouse event in the same way, with no need to distinguish drag events from others.

The `drag-' prefix follows the modifier key prefixes such as `C-' and `M-'.

If read-key-sequence receives a drag event that has no key binding, and the corresponding click event does have a binding, it changes the drag event into a click event at the drag's starting position. This means that you don't have to distinguish between click and drag events unless you want to.

Button-Down Events

Click and drag events happen when the user releases a mouse button. They cannot happen earlier, because there is no way to distinguish a click from a drag until the button is released.

If you want to take action as soon as a button is pressed, you need to handle button-down events.(3) These occur as soon as a button is pressed. They are represented by lists that look exactly like click events (see section Click Events), except that the event-type symbol name contains the prefix `down-'. The `down-' prefix follows modifier key prefixes such as `C-' and `M-'.

The function read-key-sequence ignores any button-down events that don't have command bindings; therefore, the Emacs command loop ignores them too. This means that you need not worry about defining button-down events unless you want them to do something. The usual reason to define a button-down event is so that you can track mouse motion (by reading motion events) until the button is released. See section Motion Events.

Repeat Events

If you press the same mouse button more than once in quick succession without moving the mouse, Emacs generates special repeat mouse events for the second and subsequent presses.

The most common repeat events are double-click events. Emacs generates a double-click event when you click a button twice; the event happens when you release the button (as is normal for all click events).

The event type of a double-click event contains the prefix `double-'. Thus, a double click on the second mouse button with meta held down comes to the Lisp program as M-double-mouse-2. If a double-click event has no binding, the binding of the corresponding ordinary click event is used to execute it. Thus, you need not pay attention to the double click feature unless you really want to.

When the user performs a double click, Emacs generates first an ordinary click event, and then a double-click event. Therefore, you must design the command binding of the double click event to assume that the single-click command has already run. It must produce the desired results of a double click, starting from the results of a single click.

This is convenient, if the meaning of a double click somehow "builds on" the meaning of a single click--which is recommended user interface design practice for double clicks.

If you click a button, then press it down again and start moving the mouse with the button held down, then you get a double-drag event when you ultimately release the button. Its event type contains `double-drag' instead of just `drag'. If a double-drag event has no binding, Emacs looks for an alternate binding as if the event were an ordinary drag.

Before the double-click or double-drag event, Emacs generates a double-down event when the user presses the button down for the second time. Its event type contains `double-down' instead of just `down'. If a double-down event has no binding, Emacs looks for an alternate binding as if the event were an ordinary button-down event. If it finds no binding that way either, the double-down event is ignored.

To summarize, when you click a button and then press it again right away, Emacs generates a down event and a click event for the first click, a double-down event when you press the button again, and finally either a double-click or a double-drag event.

If you click a button twice and then press it again, all in quick succession, Emacs generates a triple-down event, followed by either a triple-click or a triple-drag. The event types of these events contain `triple' instead of `double'. If any triple event has no binding, Emacs uses the binding that it would use for the corresponding double event.

If you click a button three or more times and then press it again, the events for the presses beyond the third are all triple events. Emacs does not have separate event types for quadruple, quintuple, etc. events. However, you can look at the event list to find out precisely how many times the button was pressed.

Function: event-click-count event
This function returns the number of consecutive button presses that led up to event. If event is a double-down, double-click or double-drag event, the value is 2. If event is a triple event, the value is 3 or greater. If event is an ordinary mouse event (not a repeat event), the value is 1.

Variable: double-click-time
To generate repeat events, successive mouse button presses must be at the same screen position, and the number of milliseconds between successive button presses must be less than the value of double-click-time. Setting double-click-time to nil disables multi-click detection entirely. Setting it to t removes the time limit; Emacs then detects multi-clicks by position only.

Motion Events

Emacs sometimes generates mouse motion events to describe motion of the mouse without any button activity. Mouse motion events are represented by lists that look like this:

(mouse-movement (window buffer-pos (x . y) timestamp))

The second element of the list describes the current position of the mouse, just as in a click event (see section Click Events).

The special form track-mouse enables generation of motion events within its body. Outside of track-mouse forms, Emacs does not generate events for mere motion of the mouse, and these events do not appear. See section Mouse Tracking.

Focus Events

Window systems provide general ways for the user to control which window gets keyboard input. This choice of window is called the focus. When the user does something to switch between Emacs frames, that generates a focus event. The normal definition of a focus event, in the global keymap, is to select a new frame within Emacs, as the user would expect. See section Input Focus.

Focus events are represented in Lisp as lists that look like this:

(switch-frame new-frame)

where new-frame is the frame switched to.

Most X window managers are set up so that just moving the mouse into a window is enough to set the focus there. Emacs appears to do this, because it changes the cursor to solid in the new frame. However, there is no need for the Lisp program to know about the focus change until some other kind of input arrives. So Emacs generates a focus event only when the user actually types a keyboard key or presses a mouse button in the new frame; just moving the mouse between frames does not generate a focus event.

A focus event in the middle of a key sequence would garble the sequence. So Emacs never generates a focus event in the middle of a key sequence. If the user changes focus in the middle of a key sequence--that is, after a prefix key--then Emacs reorders the events so that the focus event comes either before or after the multi-event key sequence, and not within it.

Miscellaneous Window System Events

A few other event types represent occurrences within the window system.

(delete-frame (frame))
This kind of event indicates that the user gave the window manager a command to delete a particular window, which happens to be an Emacs frame. The standard definition of the delete-frame event is to delete frame.
(iconify-frame (frame))
This kind of event indicates that the user iconified frame using the window manager. Its standard definition is ignore; since the frame has already been iconified, Emacs has no work to do. The purpose of this event type is so that you can keep track of such events if you want to.
(make-frame-visible (frame))
This kind of event indicates that the user deiconified frame using the window manager. Its standard definition is ignore; since the frame has already been made visible, Emacs has no work to do.
(mouse-wheel position delta)
This kind of event is generated by moving a wheel on a mouse (such as the MS Intellimouse). Its effect is typically a kind of scroll or zoom. The element delta describes the amount and direction of the wheel rotation. Its absolute value is the number of increments by which the wheel was rotated. A negative delta indicates that the wheel was rotated backwards, towards the user, and a positive delta indicates that the wheel was rotated forward, away from the user. The element position is a list describing the position of the event, in the same format as used in a mouse-click event. This kind of event is generated only on some kinds of systems.
(drag-n-drop position files)
This kind of event is generated when a group of files is selected in an application outside of Emacs, and then dragged and dropped onto an Emacs frame. The element position is a list describing the position of the event, in the same format as used in a mouse-click event, and files is the list of file names that were dragged and dropped. The usual way to handle this event is by visiting these files. This kind of event is generated, at present, only on some kinds of systems.

If one of these events arrives in the middle of a key sequence--that is, after a prefix key--then Emacs reorders the events so that this event comes either before or after the multi-event key sequence, not within it.

Event Examples

If the user presses and releases the left mouse button over the same location, that generates a sequence of events like this:

(down-mouse-1 (#<window 18 on NEWS> 2613 (0 . 38) -864320))
(mouse-1      (#<window 18 on NEWS> 2613 (0 . 38) -864180))

While holding the control key down, the user might hold down the second mouse button, and drag the mouse from one line to the next. That produces two events, as shown here:

(C-down-mouse-2 (#<window 18 on NEWS> 3440 (0 . 27) -731219))
(C-drag-mouse-2 (#<window 18 on NEWS> 3440 (0 . 27) -731219)
                (#<window 18 on NEWS> 3510 (0 . 28) -729648))

While holding down the meta and shift keys, the user might press the second mouse button on the window's mode line, and then drag the mouse into another window. That produces a pair of events like these:

(M-S-down-mouse-2 (#<window 18 on NEWS> mode-line (33 . 31) -457844))
(M-S-drag-mouse-2 (#<window 18 on NEWS> mode-line (33 . 31) -457844)
                  (#<window 20 on carlton-sanskrit.tex> 161 (33 . 3)
                   -453816))

Classifying Events

Every event has an event type, which classifies the event for key binding purposes. For a keyboard event, the event type equals the event value; thus, the event type for a character is the character, and the event type for a function key symbol is the symbol itself. For events that are lists, the event type is the symbol in the CAR of the list. Thus, the event type is always a symbol or a character.

Two events of the same type are equivalent where key bindings are concerned; thus, they always run the same command. That does not necessarily mean they do the same things, however, as some commands look at the whole event to decide what to do. For example, some commands use the location of a mouse event to decide where in the buffer to act.

Sometimes broader classifications of events are useful. For example, you might want to ask whether an event involved the META key, regardless of which other key or mouse button was used.

The functions event-modifiers and event-basic-type are provided to get such information conveniently.

Function: event-modifiers event
This function returns a list of the modifiers that event has. The modifiers are symbols; they include shift, control, meta, alt, hyper and super. In addition, the modifiers list of a mouse event symbol always contains one of click, drag, and down.

The argument event may be an entire event object, or just an event type.

Here are some examples:

(event-modifiers ?a)
     => nil
(event-modifiers ?\C-a)
     => (control)
(event-modifiers ?\C-%)
     => (control)
(event-modifiers ?\C-\S-a)
     => (control shift)
(event-modifiers 'f5)
     => nil
(event-modifiers 's-f5)
     => (super)
(event-modifiers 'M-S-f5)
     => (meta shift)
(event-modifiers 'mouse-1)
     => (click)
(event-modifiers 'down-mouse-1)
     => (down)

The modifiers list for a click event explicitly contains click, but the event symbol name itself does not contain `click'.

Function: event-basic-type event
This function returns the key or mouse button that event describes, with all modifiers removed. For example:

(event-basic-type ?a)
     => 97
(event-basic-type ?A)
     => 97
(event-basic-type ?\C-a)
     => 97
(event-basic-type ?\C-\S-a)
     => 97
(event-basic-type 'f5)
     => f5
(event-basic-type 's-f5)
     => f5
(event-basic-type 'M-S-f5)
     => f5
(event-basic-type 'down-mouse-1)
     => mouse-1

Function: mouse-movement-p object
This function returns non-nil if object is a mouse movement event.

Function: event-convert-list list
This function converts a list of modifier names and a basic event type to an event type which specifies all of them. For example,

(event-convert-list '(control ?a))
     => 1
(event-convert-list '(control meta ?a))
     => -134217727
(event-convert-list '(control super f1))
     => C-s-f1

Accessing Events

This section describes convenient functions for accessing the data in a mouse button or motion event.

These two functions return the starting or ending position of a mouse-button event, as a list of this form:

(window buffer-position (x . y) timestamp)

Function: event-start event
This returns the starting position of event.

If event is a click or button-down event, this returns the location of the event. If event is a drag event, this returns the drag's starting position.

Function: event-end event
This returns the ending position of event.

If event is a drag event, this returns the position where the user released the mouse button. If event is a click or button-down event, the value is actually the starting position, which is the only position such events have.

These five functions take a position list as described above, and return various parts of it.

Function: posn-window position
Return the window that position is in.

Function: posn-point position
Return the buffer position in position. This is an integer.

Function: posn-x-y position
Return the pixel-based x and y coordinates in position, as a cons cell (x . y).

Function: posn-col-row position
Return the row and column (in units of characters) of position, as a cons cell (col . row). These are computed from the x and y values actually found in position.

Function: posn-timestamp position
Return the timestamp in position.

These functions are useful for decoding scroll bar events.

Function: scroll-bar-event-ratio event
This function returns the fractional vertical position of a scroll bar event within the scroll bar. The value is a cons cell (portion . whole) containing two integers whose ratio is the fractional position.

Function: scroll-bar-scale ratio total
This function multiplies (in effect) ratio by total, rounding the result to an integer. The argument ratio is not a number, but rather a pair (num . denom)---typically a value returned by scroll-bar-event-ratio.

This function is handy for scaling a position on a scroll bar into a buffer position. Here's how to do that:

(+ (point-min)
   (scroll-bar-scale
      (posn-x-y (event-start event))
      (- (point-max) (point-min))))

Recall that scroll bar events have two integers forming a ratio, in place of a pair of x and y coordinates.

Putting Keyboard Events in Strings

In most of the places where strings are used, we conceptualize the string as containing text characters--the same kind of characters found in buffers or files. Occasionally Lisp programs use strings that conceptually contain keyboard characters; for example, they may be key sequences or keyboard macro definitions. However, storing keyboard characters in a string is a complex matter, for reasons of historical compatibility, and it is not always possible.

We recommend that new programs avoid dealing with these complexities by not storing keyboard events in strings. Here is how to do that:

The complexities stem from the modifier bits that keyboard input characters can include. Aside from the Meta modifier, none of these modifier bits can be included in a string, and the Meta modifier is allowed only in special cases.

The earliest GNU Emacs versions represented meta characters as codes in the range of 128 to 255. At that time, the basic character codes ranged from 0 to 127, so all keyboard character codes did fit in a string. Many Lisp programs used `\M-' in string constants to stand for meta characters, especially in arguments to define-key and similar functions, and key sequences and sequences of events were always represented as strings.

When we added support for larger basic character codes beyond 127, and additional modifier bits, we had to change the representation of meta characters. Now the flag that represents the Meta modifier in a character is and such numbers cannot be included in a string.

To support programs with `\M-' in string constants, there are special rules for including certain meta characters in a string. Here are the rules for interpreting a string as a sequence of input characters:

Functions such as read-key-sequence that construct strings of keyboard input characters follow these rules: they construct vectors instead of strings, when the events won't fit in a string.

When you use the read syntax `\M-' in a string, it produces a code in the range of 128 to 255--the same code that you get if you modify the corresponding keyboard event to put it in the string. Thus, meta events in strings work consistently regardless of how they get into the strings.

However, most programs would do well to avoid these issues by following the recommendations at the beginning of this section.

Reading Input

The editor command loop reads key sequences using the function read-key-sequence, which uses read-event. These and other functions for event input are also available for use in Lisp programs. See also momentary-string-display in section Temporary Displays, and sit-for in section Waiting for Elapsed Time or Input. See section Terminal Input, for functions and variables for controlling terminal input modes and debugging terminal input. See section Translating Input Events, for features you can use for translating or modifying input events while reading them.

For higher-level input facilities, see section Minibuffers.

Key Sequence Input

The command loop reads input a key sequence at a time, by calling read-key-sequence. Lisp programs can also call this function; for example, describe-key uses it to read the key to describe.

Function: read-key-sequence prompt
This function reads a key sequence and returns it as a string or vector. It keeps reading events until it has accumulated a complete key sequence; that is, enough to specify a non-prefix command using the currently active keymaps.

If the events are all characters and all can fit in a string, then read-key-sequence returns a string (see section Putting Keyboard Events in Strings). Otherwise, it returns a vector, since a vector can hold all kinds of events--characters, symbols, and lists. The elements of the string or vector are the events in the key sequence.

The argument prompt is either a string to be displayed in the echo area as a prompt, or nil, meaning not to display a prompt.

In the example below, the prompt `?' is displayed in the echo area, and the user types C-x C-f.

(read-key-sequence "?")

---------- Echo Area ----------
?C-x C-f
---------- Echo Area ----------

     => "^X^F"

The function read-key-sequence suppresses quitting: C-g typed while reading with this function works like any other character, and does not set quit-flag. See section Quitting.

Function: read-key-sequence-vector prompt
This is like read-key-sequence except that it always returns the key sequence as a vector, never as a string. See section Putting Keyboard Events in Strings.

If an input character is an upper-case letter and has no key binding, but its lower-case equivalent has one, then read-key-sequence converts the character to lower case. Note that lookup-key does not perform case conversion in this way.

The function read-key-sequence also transforms some mouse events. It converts unbound drag events into click events, and discards unbound button-down events entirely. It also reshuffles focus events and miscellaneous window events so that they never appear in a key sequence with any other events.

When mouse events occur in special parts of a window, such as a mode line or a scroll bar, the event type shows nothing special--it is the same symbol that would normally represent that combination of mouse button and modifier keys. The information about the window part is kept elsewhere in the event--in the coordinates. But read-key-sequence translates this information into imaginary "prefix keys", all of which are symbols: mode-line, vertical-line, horizontal-scroll-bar and vertical-scroll-bar. You can define meanings for mouse clicks in special window parts by defining key sequences using these imaginary prefix keys.

For example, if you call read-key-sequence and then click the mouse on the window's mode line, you get two events, like this:

(read-key-sequence "Click on the mode line: ")
     => [mode-line
         (mouse-1
          (#<window 6 on NEWS> mode-line
           (40 . 63) 5959987))]

Variable: num-input-keys
This variable's value is the number of key sequences processed so far in this Emacs session. This includes key sequences read from the terminal and key sequences read from keyboard macros being executed.

Variable: num-nonmacro-input-events
This variable holds the total number of input events received so far from the terminal--not counting those generated by keyboard macros.

Reading One Event

The lowest level functions for command input are those that read a single event.

Function: read-event &optional prompt suppress-input-method
This function reads and returns the next event of command input, waiting if necessary until an event is available. Events can come directly from the user or from a keyboard macro.

If prompt is non-nil, it should be a string to display in the echo area as a prompt. Otherwise, read-event does not display any message to indicate it is waiting for input; instead, it prompts by echoing: it displays descriptions of the events that led to or were read by the current command. See section The Echo Area.

If suppress-input-method is non-nil, then the current input method is disabled for reading this event. If you want to read an event without input-method processing, always do it this way; don't try binding input-method-function (see below).

If cursor-in-echo-area is non-nil, then read-event moves the cursor temporarily to the echo area, to the end of any message displayed there. Otherwise read-event does not move the cursor.

If read-event gets an event that is defined as a help character, in some cases read-event processes the event directly without returning. See section Help Functions. Certain other events, called special events, are also processed directly within read-event (see section Special Events).

Here is what happens if you call read-event and then press the right-arrow function key:

(read-event)
     => right

Function: read-char
This function reads and returns a character of command input. It discards any events that are not characters, until it gets a character.

In the first example, the user types the character 1 (ASCII code 49). The second example shows a keyboard macro definition that calls read-char from the minibuffer using eval-expression. read-char reads the keyboard macro's very next character, which is 1. Then eval-expression displays its return value in the echo area.

(read-char)
     => 49

;; We assume here you use M-: to evaluate this.
(symbol-function 'foo)
     => "^[:(read-char)^M1"
(execute-kbd-macro 'foo)
     -| 49
     => nil

read-event also invokes the current input method, if any. If the value of input-method-function is non-nil, it should be a function; when read-event reads a printing character (including SPC) with no modifier bits, it calls that function, passing the event as an argument.

Variable: input-method-function
If this is non-nil, its value specifies the current input method function.

Note: Don't bind this variable with let. It is often buffer-local, and if you bind it around reading input (which is exactly when you would bind it), switching buffers asynchronously while Emacs is waiting will cause the value to be restored in the wrong buffer.

The input method function should return a list of events which should be used as input. (If the list is nil, that means there is no input, so read-event waits for another event.) These events are processed before the events in unread-command-events. Events returned by the input method function are not passed to the input method function again, even if they are printing characters with no modifier bits.

If the input method function calls read-event or read-key-sequence, it should bind input-method-function to nil first, to prevent recursion.

The input method function is not called when reading the second and subsequent event of a key sequence. Thus, these characters are not subject to input method processing. It is usually a good idea for the input method processing to test the values of overriding-local-map and overriding-terminal-local-map; if either of these variables is non-nil, the input method should put its argument into a list and return that list with no further processing.

Quoted Character Input

You can use the function read-quoted-char to ask the user to specify a character, and allow the user to specify a control or meta character conveniently, either literally or as an octal character code. The command quoted-insert uses this function.

Function: read-quoted-char &optional prompt
This function is like read-char, except that if the first character read is an octal digit (0-7), it reads any number of octal digits (but stopping if a non-octal digit is found), and returns the character represented by that numeric character code.

Quitting is suppressed when the first character is read, so that the user can enter a C-g. See section Quitting.

If prompt is supplied, it specifies a string for prompting the user. The prompt string is always displayed in the echo area, followed by a single `-'.

In the following example, the user types in the octal number 177 (which is 127 in decimal).

(read-quoted-char "What character")

---------- Echo Area ----------
What character-177
---------- Echo Area ----------

     => 127

Miscellaneous Event Input Features

This section describes how to "peek ahead" at events without using them up, how to check for pending input, and how to discard pending input. See also the function read-passwd (see section Reading a Password).

Variable: unread-command-events
This variable holds a list of events waiting to be read as command input. The events are used in the order they appear in the list, and removed one by one as they are used.

The variable is needed because in some cases a function reads an event and then decides not to use it. Storing the event in this variable causes it to be processed normally, by the command loop or by the functions to read command input.

For example, the function that implements numeric prefix arguments reads any number of digits. When it finds a non-digit event, it must unread the event so that it can be read normally by the command loop. Likewise, incremental search uses this feature to unread events with no special meaning in a search, because these events should exit the search and then execute normally.

The reliable and easy way to extract events from a key sequence so as to put them in unread-command-events is to use listify-key-sequence (see section Putting Keyboard Events in Strings).

Normally you add events to the front of this list, so that the events most recently unread will be reread first.

Function: listify-key-sequence key
This function converts the string or vector key to a list of individual events, which you can put in unread-command-events.

Variable: unread-command-char
This variable holds a character to be read as command input. A value of -1 means "empty".

This variable is mostly obsolete now that you can use unread-command-events instead; it exists only to support programs written for Emacs versions 18 and earlier.

Function: input-pending-p
This function determines whether any command input is currently available to be read. It returns immediately, with value t if there is available input, nil otherwise. On rare occasions it may return t when no input is available.

Variable: last-input-event
Variable: last-input-char
This variable records the last terminal input event read, whether as part of a command or explicitly by a Lisp program.

In the example below, the Lisp program reads the character 1, ASCII code 49. It becomes the value of last-input-event, while C-e (we assume C-x C-e command is used to evaluate this expression) remains the value of last-command-event.

(progn (print (read-char))
       (print last-command-event)
       last-input-event)
     -| 49
     -| 5
     => 49

The alias last-input-char exists for compatibility with Emacs version 18.

Function: discard-input
This function discards the contents of the terminal input buffer and cancels any keyboard macro that might be in the process of definition. It returns nil.

In the following example, the user may type a number of characters right after starting the evaluation of the form. After the sleep-for finishes sleeping, discard-input discards any characters typed during the sleep.

(progn (sleep-for 2)
       (discard-input))
     => nil

Special Events

Special events are handled at a very low level--as soon as they are read. The read-event function processes these events itself, and never returns them.

Events that are handled in this way do not echo, they are never grouped into key sequences, and they never appear in the value of last-command-event or (this-command-keys). They do not discard a numeric argument, they cannot be unread with unread-command-events, they may not appear in a keyboard macro, and they are not recorded in a keyboard macro while you are defining one.

These events do, however, appear in last-input-event immediately after they are read, and this is the way for the event's definition to find the actual event.

The events types iconify-frame, make-frame-visible and delete-frame are normally handled in this way. The keymap which defines how to handle special events--and which events are special--is in the variable special-event-map (see section Active Keymaps).

Waiting for Elapsed Time or Input

The wait functions are designed to wait for a certain amount of time to pass or until there is input. For example, you may wish to pause in the middle of a computation to allow the user time to view the display. sit-for pauses and updates the screen, and returns immediately if input comes in, while sleep-for pauses without updating the screen.

Function: sit-for seconds &optional millisec nodisp
This function performs redisplay (provided there is no pending input from the user), then waits seconds seconds, or until input is available. The value is t if sit-for waited the full time with no input arriving (see input-pending-p in section Miscellaneous Event Input Features). Otherwise, the value is nil.

The argument seconds need not be an integer. If it is a floating point number, sit-for waits for a fractional number of seconds. Some systems support only a whole number of seconds; on these systems, seconds is rounded down.

The optional argument millisec specifies an additional waiting period measured in milliseconds. This adds to the period specified by seconds. If the system doesn't support waiting fractions of a second, you get an error if you specify nonzero millisec.

Redisplay is always preempted if input arrives, and does not happen at all if input is available before it starts. Thus, there is no way to force screen updating if there is pending input; however, if there is no input pending, you can force an update with no delay by using (sit-for 0).

If nodisp is non-nil, then sit-for does not redisplay, but it still returns as soon as input is available (or when the timeout elapses).

Iconifying or deiconifying a frame makes sit-for return, because that generates an event. See section Miscellaneous Window System Events.

The usual purpose of sit-for is to give the user time to read text that you display.

Function: sleep-for seconds &optional millisec
This function simply pauses for seconds seconds without updating the display. It pays no attention to available input. It returns nil.

The argument seconds need not be an integer. If it is a floating point number, sleep-for waits for a fractional number of seconds. Some systems support only a whole number of seconds; on these systems, seconds is rounded down.

The optional argument millisec specifies an additional waiting period measured in milliseconds. This adds to the period specified by seconds. If the system doesn't support waiting fractions of a second, you get an error if you specify nonzero millisec.

Use sleep-for when you wish to guarantee a delay.

See section Time of Day, for functions to get the current time.

Quitting

Typing C-g while a Lisp function is running causes Emacs to quit whatever it is doing. This means that control returns to the innermost active command loop.

Typing C-g while the command loop is waiting for keyboard input does not cause a quit; it acts as an ordinary input character. In the simplest case, you cannot tell the difference, because C-g normally runs the command keyboard-quit, whose effect is to quit. However, when C-g follows a prefix key, they combine to form an undefined key. The effect is to cancel the prefix key as well as any prefix argument.

In the minibuffer, C-g has a different definition: it aborts out of the minibuffer. This means, in effect, that it exits the minibuffer and then quits. (Simply quitting would return to the command loop within the minibuffer.) The reason why C-g does not quit directly when the command reader is reading input is so that its meaning can be redefined in the minibuffer in this way. C-g following a prefix key is not redefined in the minibuffer, and it has its normal effect of canceling the prefix key and prefix argument. This too would not be possible if C-g always quit directly.

When C-g does directly quit, it does so by setting the variable quit-flag to t. Emacs checks this variable at appropriate times and quits if it is not nil. Setting quit-flag non-nil in any way thus causes a quit.

At the level of C code, quitting cannot happen just anywhere; only at the special places that check quit-flag. The reason for this is that quitting at other places might leave an inconsistency in Emacs's internal state. Because quitting is delayed until a safe place, quitting cannot make Emacs crash.

Certain functions such as read-key-sequence or read-quoted-char prevent quitting entirely even though they wait for input. Instead of quitting, C-g serves as the requested input. In the case of read-key-sequence, this serves to bring about the special behavior of C-g in the command loop. In the case of read-quoted-char, this is so that C-q can be used to quote a C-g.

You can prevent quitting for a portion of a Lisp function by binding the variable inhibit-quit to a non-nil value. Then, although C-g still sets quit-flag to t as usual, the usual result of this--a quit--is prevented. Eventually, inhibit-quit will become nil again, such as when its binding is unwound at the end of a let form. At that time, if quit-flag is still non-nil, the requested quit happens immediately. This behavior is ideal when you wish to make sure that quitting does not happen within a "critical section" of the program.

In some functions (such as read-quoted-char), C-g is handled in a special way that does not involve quitting. This is done by reading the input with inhibit-quit bound to t, and setting quit-flag to nil before inhibit-quit becomes nil again. This excerpt from the definition of read-quoted-char shows how this is done; it also shows that normal quitting is permitted after the first character of input.

(defun read-quoted-char (&optional prompt)
  "...documentation..."
  (let ((message-log-max nil) done (first t) (code 0) char)
    (while (not done)
      (let ((inhibit-quit first)
            ...)
	(and prompt (message "%s-" prompt))
	(setq char (read-event))
	(if inhibit-quit (setq quit-flag nil)))
      ...set the variable code...)
    code))

Variable: quit-flag
If this variable is non-nil, then Emacs quits immediately, unless inhibit-quit is non-nil. Typing C-g ordinarily sets quit-flag non-nil, regardless of inhibit-quit.

Variable: inhibit-quit
This variable determines whether Emacs should quit when quit-flag is set to a value other than nil. If inhibit-quit is non-nil, then quit-flag has no special effect.

Command: keyboard-quit
This function signals the quit condition with (signal 'quit nil). This is the same thing that quitting does. (See signal in section Errors.)

You can specify a character other than C-g to use for quitting. See the function set-input-mode in section Terminal Input.

Prefix Command Arguments

Most Emacs commands can use a prefix argument, a number specified before the command itself. (Don't confuse prefix arguments with prefix keys.) The prefix argument is at all times represented by a value, which may be nil, meaning there is currently no prefix argument. Each command may use the prefix argument or ignore it.

There are two representations of the prefix argument: raw and numeric. The editor command loop uses the raw representation internally, and so do the Lisp variables that store the information, but commands can request either representation.

Here are the possible values of a raw prefix argument:

We illustrate these possibilities by calling the following function with various prefixes:

(defun display-prefix (arg)
  "Display the value of the raw prefix arg."
  (interactive "P")
  (message "%s" arg))

Here are the results of calling display-prefix with various raw prefix arguments:

        M-x display-prefix  -| nil

C-u     M-x display-prefix  -| (4)

C-u C-u M-x display-prefix  -| (16)

C-u 3   M-x display-prefix  -| 3

M-3     M-x display-prefix  -| 3      ; (Same as C-u 3.)

C-u -   M-x display-prefix  -| -      

M--     M-x display-prefix  -| -      ; (Same as C-u -.)

C-u - 7 M-x display-prefix  -| -7     

M-- 7   M-x display-prefix  -| -7     ; (Same as C-u -7.)

Emacs uses two variables to store the prefix argument: prefix-arg and current-prefix-arg. Commands such as universal-argument that set up prefix arguments for other commands store them in prefix-arg. In contrast, current-prefix-arg conveys the prefix argument to the current command, so setting it has no effect on the prefix arguments for future commands.

Normally, commands specify which representation to use for the prefix argument, either numeric or raw, in the interactive declaration. (See section Using interactive.) Alternatively, functions may look at the value of the prefix argument directly in the variable current-prefix-arg, but this is less clean.

Function: prefix-numeric-value arg
This function returns the numeric meaning of a valid raw prefix argument value, arg. The argument may be a symbol, a number, or a list. If it is nil, the value 1 is returned; if it is -, the value -1 is returned; if it is a number, that number is returned; if it is a list, the CAR of that list (which should be a number) is returned.

Variable: current-prefix-arg
This variable holds the raw prefix argument for the current command. Commands may examine it directly, but the usual method for accessing it is with (interactive "P").

Variable: prefix-arg
The value of this variable is the raw prefix argument for the next editing command. Commands such as universal-argument that specify prefix arguments for the following command work by setting this variable.

Variable: last-prefix-arg
The raw prefix argument value used by the previous command.

The following commands exist to set up prefix arguments for the following command. Do not call them for any other reason.

Command: universal-argument
This command reads input and specifies a prefix argument for the following command. Don't call this command yourself unless you know what you are doing.

Command: digit-argument arg
This command adds to the prefix argument for the following command. The argument arg is the raw prefix argument as it was before this command; it is used to compute the updated prefix argument. Don't call this command yourself unless you know what you are doing.

Command: negative-argument arg
This command adds to the numeric argument for the next command. The argument arg is the raw prefix argument as it was before this command; its value is negated to form the new prefix argument. Don't call this command yourself unless you know what you are doing.

Recursive Editing

The Emacs command loop is entered automatically when Emacs starts up. This top-level invocation of the command loop never exits; it keeps running as long as Emacs does. Lisp programs can also invoke the command loop. Since this makes more than one activation of the command loop, we call it recursive editing. A recursive editing level has the effect of suspending whatever command invoked it and permitting the user to do arbitrary editing before resuming that command.

The commands available during recursive editing are the same ones available in the top-level editing loop and defined in the keymaps. Only a few special commands exit the recursive editing level; the others return to the recursive editing level when they finish. (The special commands for exiting are always available, but they do nothing when recursive editing is not in progress.)

All command loops, including recursive ones, set up all-purpose error handlers so that an error in a command run from the command loop will not exit the loop.

Minibuffer input is a special kind of recursive editing. It has a few special wrinkles, such as enabling display of the minibuffer and the minibuffer window, but fewer than you might suppose. Certain keys behave differently in the minibuffer, but that is only because of the minibuffer's local map; if you switch windows, you get the usual Emacs commands.

To invoke a recursive editing level, call the function recursive-edit. This function contains the command loop; it also contains a call to catch with tag exit, which makes it possible to exit the recursive editing level by throwing to exit (see section Explicit Nonlocal Exits: catch and throw). If you throw a value other than t, then recursive-edit returns normally to the function that called it. The command C-M-c (exit-recursive-edit) does this. Throwing a t value causes recursive-edit to quit, so that control returns to the command loop one level up. This is called aborting, and is done by C-] (abort-recursive-edit).

Most applications should not use recursive editing, except as part of using the minibuffer. Usually it is more convenient for the user if you change the major mode of the current buffer temporarily to a special major mode, which should have a command to go back to the previous mode. (The e command in Rmail uses this technique.) Or, if you wish to give the user different text to edit "recursively", create and select a new buffer in a special mode. In this mode, define a command to complete the processing and go back to the previous buffer. (The m command in Rmail does this.)

Recursive edits are useful in debugging. You can insert a call to debug into a function definition as a sort of breakpoint, so that you can look around when the function gets there. debug invokes a recursive edit but also provides the other features of the debugger.

Recursive editing levels are also used when you type C-r in query-replace or use C-x q (kbd-macro-query).

Function: recursive-edit
This function invokes the editor command loop. It is called automatically by the initialization of Emacs, to let the user begin editing. When called from a Lisp program, it enters a recursive editing level.

In the following example, the function simple-rec first advances point one word, then enters a recursive edit, printing out a message in the echo area. The user can then do any editing desired, and then type C-M-c to exit and continue executing simple-rec.

(defun simple-rec ()
  (forward-word 1)
  (message "Recursive edit in progress")
  (recursive-edit)
  (forward-word 1))
     => simple-rec
(simple-rec)
     => nil

Command: exit-recursive-edit
This function exits from the innermost recursive edit (including minibuffer input). Its definition is effectively (throw 'exit nil).

Command: abort-recursive-edit
This function aborts the command that requested the innermost recursive edit (including minibuffer input), by signaling quit after exiting the recursive edit. Its definition is effectively (throw 'exit t). See section Quitting.

Command: top-level
This function exits all recursive editing levels; it does not return a value, as it jumps completely out of any computation directly back to the main command loop.

Function: recursion-depth
This function returns the current depth of recursive edits. When no recursive edit is active, it returns 0.

Disabling Commands

Disabling a command marks the command as requiring user confirmation before it can be executed. Disabling is used for commands which might be confusing to beginning users, to prevent them from using the commands by accident.

The low-level mechanism for disabling a command is to put a non-nil disabled property on the Lisp symbol for the command. These properties are normally set up by the user's `.emacs' file with Lisp expressions such as this:

(put 'upcase-region 'disabled t)

For a few commands, these properties are present by default and may be removed by the `.emacs' file.

If the value of the disabled property is a string, the message saying the command is disabled includes that string. For example:

(put 'delete-region 'disabled
     "Text deleted this way cannot be yanked back!\n")

See section `Disabling' in The GNU Emacs Manual, for the details on what happens when a disabled command is invoked interactively. Disabling a command has no effect on calling it as a function from Lisp programs.

Command: enable-command command
Allow command to be executed without special confirmation from now on, and (if the user confirms) alter the user's `.emacs' file so that this will apply to future sessions.

Command: disable-command command
Require special confirmation to execute command from now on, and (if the user confirms) alter the user's `.emacs' file so that this will apply to future sessions.

Variable: disabled-command-hook
When the user invokes a disabled command interactively, this normal hook is run instead of the disabled command. The hook functions can use this-command-keys to determine what the user typed to run the command, and thus find the command itself. See section Hooks.

By default, disabled-command-hook contains a function that asks the user whether to proceed.

Command History

The command loop keeps a history of the complex commands that have been executed, to make it convenient to repeat these commands. A complex command is one for which the interactive argument reading uses the minibuffer. This includes any M-x command, any M-: command, and any command whose interactive specification reads an argument from the minibuffer. Explicit use of the minibuffer during the execution of the command itself does not cause the command to be considered complex.

Variable: command-history
This variable's value is a list of recent complex commands, each represented as a form to evaluate. It continues to accumulate all complex commands for the duration of the editing session, but when it reaches the maximum size (specified by the variable history-length), the oldest elements are deleted as new ones are added.

command-history
=> ((switch-to-buffer "chistory.texi")
    (describe-key "^X^[")
    (visit-tags-table "~/emacs/src/")
    (find-tag "repeat-complex-command"))

This history list is actually a special case of minibuffer history (see section Minibuffer History), with one special twist: the elements are expressions rather than strings.

There are a number of commands devoted to the editing and recall of previous commands. The commands repeat-complex-command, and list-command-history are described in the user manual (see section `Repetition' in The GNU Emacs Manual). Within the minibuffer, the usual minibuffer history commands are available.

Keyboard Macros

A keyboard macro is a canned sequence of input events that can be considered a command and made the definition of a key. The Lisp representation of a keyboard macro is a string or vector containing the events. Don't confuse keyboard macros with Lisp macros (see section Macros).

Function: execute-kbd-macro kbdmacro &optional count
This function executes kbdmacro as a sequence of events. If kbdmacro is a string or vector, then the events in it are executed exactly as if they had been input by the user. The sequence is not expected to be a single key sequence; normally a keyboard macro definition consists of several key sequences concatenated.

If kbdmacro is a symbol, then its function definition is used in place of kbdmacro. If that is another symbol, this process repeats. Eventually the result should be a string or vector. If the result is not a symbol, string, or vector, an error is signaled.

The argument count is a repeat count; kbdmacro is executed that many times. If count is omitted or nil, kbdmacro is executed once. If it is 0, kbdmacro is executed over and over until it encounters an error or a failing search.

See section Reading One Event, for an example of using execute-kbd-macro.

Variable: executing-macro
This variable contains the string or vector that defines the keyboard macro that is currently executing. It is nil if no macro is currently executing. A command can test this variable so as to behave differently when run from an executing macro. Do not set this variable yourself.

Variable: defining-kbd-macro
This variable indicates whether a keyboard macro is being defined. A command can test this variable so as to behave differently while a macro is being defined. The commands start-kbd-macro and end-kbd-macro set this variable--do not set it yourself.

The variable is always local to the current terminal and cannot be buffer-local. See section Multiple Displays.

Variable: last-kbd-macro
This variable is the definition of the most recently defined keyboard macro. Its value is a string or vector, or nil.

The variable is always local to the current terminal and cannot be buffer-local. See section Multiple Displays.

Keymaps

The bindings between input events and commands are recorded in data structures called keymaps. Each binding in a keymap associates (or binds) an individual event type either to another keymap or to a command. When an event type is bound to a keymap, that keymap is used to look up the next input event; this continues until a command is found. The whole process is called key lookup.

Keymap Terminology

A keymap is a table mapping event types to definitions (which can be any Lisp objects, though only certain types are meaningful for execution by the command loop). Given an event (or an event type) and a keymap, Emacs can get the event's definition. Events include characters, function keys, and mouse actions (see section Input Events).

A sequence of input events that form a unit is called a key sequence, or key for short. A sequence of one event is always a key sequence, and so are some multi-event sequences.

A keymap determines a binding or definition for any key sequence. If the key sequence is a single event, its binding is the definition of the event in the keymap. The binding of a key sequence of more than one event is found by an iterative process: the binding of the first event is found, and must be a keymap; then the second event's binding is found in that keymap, and so on until all the events in the key sequence are used up.

If the binding of a key sequence is a keymap, we call the key sequence a prefix key. Otherwise, we call it a complete key (because no more events can be added to it). If the binding is nil, we call the key undefined. Examples of prefix keys are C-c, C-x, and C-x 4. Examples of defined complete keys are X, RET, and C-x 4 C-f. Examples of undefined complete keys are C-x C-g, and C-c 3. See section Prefix Keys, for more details.

The rule for finding the binding of a key sequence assumes that the intermediate bindings (found for the events before the last) are all keymaps; if this is not so, the sequence of events does not form a unit--it is not really one key sequence. In other words, removing one or more events from the end of any valid key sequence must always yield a prefix key. For example, C-f C-n is not a key sequence; C-f is not a prefix key, so a longer sequence starting with C-f cannot be a key sequence.

The set of possible multi-event key sequences depends on the bindings for prefix keys; therefore, it can be different for different keymaps, and can change when bindings are changed. However, a one-event sequence is always a key sequence, because it does not depend on any prefix keys for its well-formedness.

At any time, several primary keymaps are active---that is, in use for finding key bindings. These are the global map, which is shared by all buffers; the local keymap, which is usually associated with a specific major mode; and zero or more minor mode keymaps, which belong to currently enabled minor modes. (Not all minor modes have keymaps.) The local keymap bindings shadow (i.e., take precedence over) the corresponding global bindings. The minor mode keymaps shadow both local and global keymaps. See section Active Keymaps, for details.

Format of Keymaps

A keymap is a list whose CAR is the symbol keymap. The remaining elements of the list define the key bindings of the keymap. Use the function keymapp (see below) to test whether an object is a keymap.

Several kinds of elements may appear in a keymap, after the symbol keymap that begins it:

(type . binding)
This specifies one binding, for events of type type. Each ordinary binding applies to events of a particular event type, which is always a character or a symbol. See section Classifying Events.
(t . binding)
This specifies a default key binding; any event not bound by other elements of the keymap is given binding as its binding. Default bindings allow a keymap to bind all possible event types without having to enumerate all of them. A keymap that has a default binding completely masks any lower-precedence keymap.
vector
If an element of a keymap is a vector, the vector counts as bindings for all the ASCII characters, codes 0 through 127; vector element n is the binding for the character with code n. This is a compact way to record lots of bindings. A keymap with such a vector is called a full keymap. Other keymaps are called sparse keymaps. When a keymap contains a vector, it always defines a binding for each ASCII character, even if the vector contains nil for that character. Such a binding of nil overrides any default key binding in the keymap, for ASCII characters. However, default bindings are still meaningful for events other than ASCII characters. A binding of nil does not override lower-precedence keymaps; thus, if the local map gives a binding of nil, Emacs uses the binding from the global map.
string
Aside from bindings, a keymap can also have a string as an element. This is called the overall prompt string and makes it possible to use the keymap as a menu. See section Menu Keymaps.

Keymaps do not directly record bindings for the meta characters. Instead, meta characters are regarded for purposes of key lookup as sequences of two characters, the first of which is ESC (or whatever is currently the value of meta-prefix-char). Thus, the key M-a is really represented as ESC a, and its global binding is found at the slot for a in esc-map (see section Prefix Keys).

Here as an example is the local keymap for Lisp mode, a sparse keymap. It defines bindings for DEL and TAB, plus C-c C-l, M-C-q, and M-C-x.

lisp-mode-map
=> 
(keymap 
 ;; TAB
 (9 . lisp-indent-line)                 
 ;; DEL
 (127 . backward-delete-char-untabify)  
 (3 keymap 
    ;; C-c C-l
    (12 . run-lisp))                    
 (27 keymap 
     ;; M-C-q, treated as ESC C-q
     (17 . indent-sexp)                 
     ;; M-C-x, treated as ESC C-x
     (24 . lisp-send-defun)))           

Function: keymapp object
This function returns t if object is a keymap, nil otherwise. More precisely, this function tests for a list whose CAR is keymap.

(keymapp '(keymap))
    => t
(keymapp (current-global-map))
    => t

Creating Keymaps

Here we describe the functions for creating keymaps.

Function: make-keymap &optional prompt
This function creates and returns a new full keymap (i.e., one containing a vector of length 128 for defining all the ASCII characters). The new keymap initially binds all ASCII characters to nil, and does not bind any other kind of event.

(make-keymap)
    => (keymap [nil nil nil ... nil nil])

If you specify prompt, that becomes the overall prompt string for the keymap. The prompt string is useful for menu keymaps (see section Menu Keymaps).

Function: make-sparse-keymap &optional prompt
This function creates and returns a new sparse keymap with no entries. The new keymap does not bind any events. The argument prompt specifies a prompt string, as in make-keymap.

(make-sparse-keymap)
    => (keymap)

Function: copy-keymap keymap
This function returns a copy of keymap. Any keymaps that appear directly as bindings in keymap are also copied recursively, and so on to any number of levels. However, recursive copying does not take place when the definition of a character is a symbol whose function definition is a keymap; the same symbol appears in the new copy.

(setq map (copy-keymap (current-local-map)))
=> (keymap
     ;; (This implements meta characters.)
     (27 keymap         
         (83 . center-paragraph)
         (115 . center-line))
     (9 . tab-to-tab-stop))

(eq map (current-local-map))
    => nil
(equal map (current-local-map))
    => t

Inheritance and Keymaps

A keymap can inherit the bindings of another keymap, which we call the parent keymap. Such a keymap looks like this:

(keymap bindings... . parent-keymap)

The effect is that this keymap inherits all the bindings of parent-keymap, whatever they may be at the time a key is looked up, but can add to them or override them with bindings.

If you change the bindings in parent-keymap using define-key or other key-binding functions, these changes are visible in the inheriting keymap unless shadowed by bindings. The converse is not true: if you use define-key to change the inheriting keymap, that affects bindings, but has no effect on parent-keymap.

The proper way to construct a keymap with a parent is to use set-keymap-parent; if you have code that directly constructs a keymap with a parent, please convert the program to use set-keymap-parent instead.

Function: keymap-parent keymap
This returns the parent keymap of keymap. If keymap has no parent, keymap-parent returns nil.

Function: set-keymap-parent keymap parent
This sets the parent keymap of keymap to parent, and returns parent. If parent is nil, this function gives keymap no parent at all.

If keymap has submaps (bindings for prefix keys), they too receive new parent keymaps that reflect what parent specifies for those prefix keys.

Here is an example showing how to make a keymap that inherits from text-mode-map:

(let ((map (make-sparse-keymap)))
  (set-keymap-parent map text-mode-map)
  map)

Prefix Keys

A prefix key is a key sequence whose binding is a keymap. The keymap defines what to do with key sequences that extend the prefix key. For example, C-x is a prefix key, and it uses a keymap that is also stored in the variable ctl-x-map. This keymap defines bindings for key sequences starting with C-x.

Some of the standard Emacs prefix keys use keymaps that are also found in Lisp variables:

The keymap binding of a prefix key is used for looking up the event that follows the prefix key. (It may instead be a symbol whose function definition is a keymap. The effect is the same, but the symbol serves as a name for the prefix key.) Thus, the binding of C-x is the symbol Control-X-prefix, whose function cell holds the keymap for C-x commands. (The same keymap is also the value of ctl-x-map.)

Prefix key definitions can appear in any active keymap. The definitions of C-c, C-x, C-h and ESC as prefix keys appear in the global map, so these prefix keys are always available. Major and minor modes can redefine a key as a prefix by putting a prefix key definition for it in the local map or the minor mode's map. See section Active Keymaps.

If a key is defined as a prefix in more than one active map, then its various definitions are in effect merged: the commands defined in the minor mode keymaps come first, followed by those in the local map's prefix definition, and then by those from the global map.

In the following example, we make C-p a prefix key in the local keymap, in such a way that C-p is identical to C-x. Then the binding for C-p C-f is the function find-file, just like C-x C-f. The key sequence C-p 6 is not found in any active keymap.

(use-local-map (make-sparse-keymap))
    => nil
(local-set-key "\C-p" ctl-x-map)
    => nil
(key-binding "\C-p\C-f")
    => find-file

(key-binding "\C-p6")
    => nil

Function: define-prefix-command symbol
This function prepares symbol for use as a prefix key's binding: it creates a full keymap and stores it as symbol's function definition. Subsequently binding a key sequence to symbol will make that key sequence into a prefix key.

This function also sets symbol as a variable, with the keymap as its value. It returns symbol.

Active Keymaps

Emacs normally contains many keymaps; at any given time, just a few of them are active in that they participate in the interpretation of user input. These are the global keymap, the current buffer's local keymap, and the keymaps of any enabled minor modes.

The global keymap holds the bindings of keys that are defined regardless of the current buffer, such as C-f. The variable global-map holds this keymap, which is always active.

Each buffer may have another keymap, its local keymap, which may contain new or overriding definitions for keys. The current buffer's local keymap is always active except when overriding-local-map overrides it. Text properties can specify an alternative local map for certain parts of the buffer; see section Properties with Special Meanings.

Each minor mode can have a keymap; if it does, the keymap is active when the minor mode is enabled.

The variable overriding-local-map, if non-nil, specifies another local keymap that overrides the buffer's local map and all the minor mode keymaps.

All the active keymaps are used together to determine what command to execute when a key is entered. Emacs searches these maps one by one, in order of decreasing precedence, until it finds a binding in one of the maps. The procedure for searching a single keymap is called key lookup; see section Key Lookup.

Normally, Emacs first searches for the key in the minor mode maps, in the order specified by minor-mode-map-alist; if they do not supply a binding for the key, Emacs searches the local map; if that too has no binding, Emacs then searches the global map. However, if overriding-local-map is non-nil, Emacs searches that map first, before the global map.

Since every buffer that uses the same major mode normally uses the same local keymap, you can think of the keymap as local to the mode. A change to the local keymap of a buffer (using local-set-key, for example) is seen also in the other buffers that share that keymap.

The local keymaps that are used for Lisp mode and some other major modes exist even if they have not yet been used. These local maps are the values of variables such as lisp-mode-map. For most major modes, which are less frequently used, the local keymap is constructed only when the mode is used for the first time in a session.

The minibuffer has local keymaps, too; they contain various completion and exit commands. See section Introduction to Minibuffers.

Emacs has other keymaps that are used in a different way--translating events within read-key-sequence. See section Translating Input Events.

See section Standard Keymaps, for a list of standard keymaps.

Variable: global-map
This variable contains the default global keymap that maps Emacs keyboard input to commands. The global keymap is normally this keymap. The default global keymap is a full keymap that binds self-insert-command to all of the printing characters.

It is normal practice to change the bindings in the global map, but you should not assign this variable any value other than the keymap it starts out with.

Function: current-global-map
This function returns the current global keymap. This is the same as the value of global-map unless you change one or the other.

(current-global-map)
=> (keymap [set-mark-command beginning-of-line ... 
            delete-backward-char])

Function: current-local-map
This function returns the current buffer's local keymap, or nil if it has none. In the following example, the keymap for the `*scratch*' buffer (using Lisp Interaction mode) is a sparse keymap in which the entry for ESC, ASCII code 27, is another sparse keymap.

(current-local-map)
=> (keymap 
    (10 . eval-print-last-sexp) 
    (9 . lisp-indent-line) 
    (127 . backward-delete-char-untabify) 
    (27 keymap 
        (24 . eval-defun) 
        (17 . indent-sexp)))

Function: current-minor-mode-maps
This function returns a list of the keymaps of currently enabled minor modes.

Function: use-global-map keymap
This function makes keymap the new current global keymap. It returns nil.

It is very unusual to change the global keymap.

Function: use-local-map keymap
This function makes keymap the new local keymap of the current buffer. If keymap is nil, then the buffer has no local keymap. use-local-map returns nil. Most major mode commands use this function.

Variable: minor-mode-map-alist
This variable is an alist describing keymaps that may or may not be active according to the values of certain variables. Its elements look like this:

(variable . keymap)

The keymap keymap is active whenever variable has a non-nil value. Typically variable is the variable that enables or disables a minor mode. See section Keymaps and Minor Modes.

Note that elements of minor-mode-map-alist do not have the same structure as elements of minor-mode-alist. The map must be the CDR of the element; a list with the map as the CADR will not do. The CADR can be either a keymap (a list) or a symbol whose function definition is a keymap.

When more than one minor mode keymap is active, their order of priority is the order of minor-mode-map-alist. But you should design minor modes so that they don't interfere with each other. If you do this properly, the order will not matter.

See section Keymaps and Minor Modes, for more information about minor modes. See also minor-mode-key-binding (see section Functions for Key Lookup).

Variable: minor-mode-overriding-map-alist
This variable allows major modes to override the key bindings for particular minor modes. The elements of this alist look like the elements of minor-mode-map-alist: (variable . keymap).

If a variable appears as an element of minor-mode-overriding-map-alist, the map specified by that element totally replaces any map specified for the same variable in minor-mode-map-alist.

minor-mode-overriding-map-alist is automatically buffer-local in all buffers.

Variable: overriding-local-map
If non-nil, this variable holds a keymap to use instead of the buffer's local keymap and instead of all the minor mode keymaps. This keymap, if any, overrides all other maps that would have been active, except for the current global map.

Variable: overriding-terminal-local-map
If non-nil, this variable holds a keymap to use instead of overriding-local-map, the buffer's local keymap and all the minor mode keymaps.

This variable is always local to the current terminal and cannot be buffer-local. See section Multiple Displays. It is used to implement incremental search mode.

Variable: overriding-local-map-menu-flag
If this variable is non-nil, the value of overriding-local-map or overriding-terminal-local-map can affect the display of the menu bar. The default value is nil, so those map variables have no effect on the menu bar.

Note that these two map variables do affect the execution of key sequences entered using the menu bar, even if they do not affect the menu bar display. So if a menu bar key sequence comes in, you should clear the variables before looking up and executing that key sequence. Modes that use the variables would typically do this anyway; normally they respond to events that they do not handle by "unreading" them and exiting.

Variable: special-event-map
This variable holds a keymap for special events. If an event type has a binding in this keymap, then it is special, and the binding for the event is run directly by read-event. See section Special Events.

Key Lookup

Key lookup is the process of finding the binding of a key sequence from a given keymap. Actual execution of the binding is not part of key lookup.

Key lookup uses just the event type of each event in the key sequence; the rest of the event is ignored. In fact, a key sequence used for key lookup may designate mouse events with just their types (symbols) instead of with entire mouse events (lists). See section Input Events. Such a "key-sequence" is insufficient for command-execute to run, but it is sufficient for looking up or rebinding a key.

When the key sequence consists of multiple events, key lookup processes the events sequentially: the binding of the first event is found, and must be a keymap; then the second event's binding is found in that keymap, and so on until all the events in the key sequence are used up. (The binding thus found for the last event may or may not be a keymap.) Thus, the process of key lookup is defined in terms of a simpler process for looking up a single event in a keymap. How that is done depends on the type of object associated with the event in that keymap.

Let's use the term keymap entry to describe the value found by looking up an event type in a keymap. (This doesn't include the item string and other extra elements in menu key bindings, because lookup-key and other key lookup functions don't include them in the returned value.) While any Lisp object may be stored in a keymap as a keymap entry, not all make sense for key lookup. Here is a table of the meaningful kinds of keymap entries:

nil
nil means that the events used so far in the lookup form an undefined key. When a keymap fails to mention an event type at all, and has no default binding, that is equivalent to a binding of nil for that event type.
command
The events used so far in the lookup form a complete key, and command is its binding. See section What Is a Function?.
array
The array (either a string or a vector) is a keyboard macro. The events used so far in the lookup form a complete key, and the array is its binding. See section Keyboard Macros, for more information.
keymap
The events used so far in the lookup form a prefix key. The next event of the key sequence is looked up in keymap.
list
The meaning of a list depends on the types of the elements of the list.
symbol
The function definition of symbol is used in place of symbol. If that too is a symbol, then this process is repeated, any number of times. Ultimately this should lead to an object that is a keymap, a command, or a keyboard macro. A list is allowed if it is a keymap or a command, but indirect entries are not understood when found via symbols. Note that keymaps and keyboard macros (strings and vectors) are not valid functions, so a symbol with a keymap, string, or vector as its function definition is invalid as a function. It is, however, valid as a key binding. If the definition is a keyboard macro, then the symbol is also valid as an argument to command-execute (see section Interactive Call). The symbol undefined is worth special mention: it means to treat the key as undefined. Strictly speaking, the key is defined, and its binding is the command undefined; but that command does the same thing that is done automatically for an undefined key: it rings the bell (by calling ding) but does not signal an error. undefined is used in local keymaps to override a global key binding and make the key "undefined" locally. A local binding of nil would fail to do this because it would not override the global binding.
anything else
If any other type of object is found, the events used so far in the lookup form a complete key, and the object is its binding, but the binding is not executable as a command.

In short, a keymap entry may be a keymap, a command, a keyboard macro, a symbol that leads to one of them, or an indirection or nil. Here is an example of a sparse keymap with two characters bound to commands and one bound to another keymap. This map is the normal value of emacs-lisp-mode-map. Note that 9 is the code for TAB, 127 for DEL, 27 for ESC, 17 for C-q and 24 for C-x.

(keymap (9 . lisp-indent-line)
        (127 . backward-delete-char-untabify)
        (27 keymap (17 . indent-sexp) (24 . eval-defun)))

Functions for Key Lookup

Here are the functions and variables pertaining to key lookup.

Function: lookup-key keymap key &optional accept-defaults
This function returns the definition of key in keymap. All the other functions described in this chapter that look up keys use lookup-key. Here are examples:

(lookup-key (current-global-map) "\C-x\C-f")
    => find-file
(lookup-key (current-global-map) "\C-x\C-f12345")
    => 2

If the string or vector key is not a valid key sequence according to the prefix keys specified in keymap, it must be "too long" and have extra events at the end that do not fit into a single key sequence. Then the value is a number, the number of events at the front of key that compose a complete key.

If accept-defaults is non-nil, then lookup-key considers default bindings as well as bindings for the specific events in key. Otherwise, lookup-key reports only bindings for the specific sequence key, ignoring default bindings except when you explicitly ask about them. (To do this, supply t as an element of key; see section Format of Keymaps.)

If key contains a meta character, that character is implicitly replaced by a two-character sequence: the value of meta-prefix-char, followed by the corresponding non-meta character. Thus, the first example below is handled by conversion into the second example.

(lookup-key (current-global-map) "\M-f")
    => forward-word
(lookup-key (current-global-map) "\ef")
    => forward-word

Unlike read-key-sequence, this function does not modify the specified events in ways that discard information (see section Key Sequence Input). In particular, it does not convert letters to lower case and it does not change drag events to clicks.

Command: undefined
Used in keymaps to undefine keys. It calls ding, but does not cause an error.

Function: key-binding key &optional accept-defaults
This function returns the binding for key in the current keymaps, trying all the active keymaps. The result is nil if key is undefined in the keymaps.

The argument accept-defaults controls checking for default bindings, as in lookup-key (above).

An error is signaled if key is not a string or a vector.

(key-binding "\C-x\C-f")
    => find-file

Function: local-key-binding key &optional accept-defaults
This function returns the binding for key in the current local keymap, or nil if it is undefined there.

The argument accept-defaults controls checking for default bindings, as in lookup-key (above).

Function: global-key-binding key &optional accept-defaults
This function returns the binding for command key in the current global keymap, or nil if it is undefined there.

The argument accept-defaults controls checking for default bindings, as in lookup-key (above).

Function: minor-mode-key-binding key &optional accept-defaults
This function returns a list of all the active minor mode bindings of key. More precisely, it returns an alist of pairs (modename . binding), where modename is the variable that enables the minor mode, and binding is key's binding in that mode. If key has no minor-mode bindings, the value is nil.

If the first binding found is not a prefix definition (a keymap or a symbol defined as a keymap), all subsequent bindings from other minor modes are omitted, since they would be completely shadowed. Similarly, the list omits non-prefix bindings that follow prefix bindings.

The argument accept-defaults controls checking for default bindings, as in lookup-key (above).

Variable: meta-prefix-char
This variable is the meta-prefix character code. It is used when translating a meta character to a two-character sequence so it can be looked up in a keymap. For useful results, the value should be a prefix event (see section Prefix Keys). The default value is 27, which is the ASCII code for ESC.

As long as the value of meta-prefix-char remains 27, key lookup translates M-b into ESC b, which is normally defined as the backward-word command. However, if you set meta-prefix-char to 24, the code for C-x, then Emacs will translate M-b into C-x b, whose standard binding is the switch-to-buffer command. Here is an illustration:

meta-prefix-char                    ; The default value.
     => 27
(key-binding "\M-b")
     => backward-word
?\C-x                               ; The print representation
     => 24                          ;   of a character.
(setq meta-prefix-char 24)
     => 24      
(key-binding "\M-b")
     => switch-to-buffer            ; Now, typing M-b is
                                    ;   like typing C-x b.

(setq meta-prefix-char 27)          ; Avoid confusion!
     => 27                          ; Restore the default value!

Changing Key Bindings

The way to rebind a key is to change its entry in a keymap. If you change a binding in the global keymap, the change is effective in all buffers (though it has no direct effect in buffers that shadow the global binding with a local one). If you change the current buffer's local map, that usually affects all buffers using the same major mode. The global-set-key and local-set-key functions are convenient interfaces for these operations (see section Commands for Binding Keys). You can also use define-key, a more general function; then you must specify explicitly the map to change.

In writing the key sequence to rebind, it is good to use the special escape sequences for control and meta characters (see section String Type). The syntax `\C-' means that the following character is a control character and `\M-' means that the following character is a meta character. Thus, the string "\M-x" is read as containing a single M-x, "\C-f" is read as containing a single C-f, and "\M-\C-x" and "\C-\M-x" are both read as containing a single C-M-x. You can also use this escape syntax in vectors, as well as others that aren't allowed in strings; one example is `[?\C-\H-x home]'. See section Character Type.

The key definition and lookup functions accept an alternate syntax for event types in a key sequence that is a vector: you can use a list containing modifier names plus one base event (a character or function key name). For example, (control ?a) is equivalent to ?\C-a and (hyper control left) is equivalent to C-H-left. One advantage of such lists is that the precise numeric codes for the modifier bits don't appear in compiled files.

For the functions below, an error is signaled if keymap is not a keymap or if key is not a string or vector representing a key sequence. You can use event types (symbols) as shorthand for events that are lists.

Function: define-key keymap key binding
This function sets the binding for key in keymap. (If key is more than one event long, the change is actually made in another keymap reached from keymap.) The argument binding can be any Lisp object, but only certain types are meaningful. (For a list of meaningful types, see section Key Lookup.) The value returned by define-key is binding.

Every prefix of key must be a prefix key (i.e., bound to a keymap) or undefined; otherwise an error is signaled. If some prefix of key is undefined, then define-key defines it as a prefix key so that the rest of key can be defined as specified.

If there was previously no binding for key in keymap, the new binding is added at the beginning of keymap. The order of bindings in a keymap makes no difference in most cases, but it does matter for menu keymaps (see section Menu Keymaps).

Here is an example that creates a sparse keymap and makes a number of bindings in it:

(setq map (make-sparse-keymap))
    => (keymap)
(define-key map "\C-f" 'forward-char)
    => forward-char
map
    => (keymap (6 . forward-char))

;; Build sparse submap for C-x and bind f in that.
(define-key map "\C-xf" 'forward-word)
    => forward-word
map
=> (keymap 
    (24 keymap                ; C-x
        (102 . forward-word)) ;      f
    (6 . forward-char))       ; C-f

;; Bind C-p to the ctl-x-map.
(define-key map "\C-p" ctl-x-map)
;; ctl-x-map
=> [nil ... find-file ... backward-kill-sentence] 

;; Bind C-f to foo in the ctl-x-map.
(define-key map "\C-p\C-f" 'foo)
=> 'foo
map
=> (keymap     ; Note foo in ctl-x-map.
    (16 keymap [nil ... foo ... backward-kill-sentence])
    (24 keymap 
        (102 . forward-word))
    (6 . forward-char))

Note that storing a new binding for C-p C-f actually works by changing an entry in ctl-x-map, and this has the effect of changing the bindings of both C-p C-f and C-x C-f in the default global map.

Function: substitute-key-definition olddef newdef keymap &optional oldmap
This function replaces olddef with newdef for any keys in keymap that were bound to olddef. In other words, olddef is replaced with newdef wherever it appears. The function returns nil.

For example, this redefines C-x C-f, if you do it in an Emacs with standard bindings:

(substitute-key-definition 
 'find-file 'find-file-read-only (current-global-map))

If oldmap is non-nil, then its bindings determine which keys to rebind. The rebindings still happen in keymap, not in oldmap. Thus, you can change one map under the control of the bindings in another. For example,

(substitute-key-definition
  'delete-backward-char 'my-funny-delete
  my-map global-map)

puts the special deletion command in my-map for whichever keys are globally bound to the standard deletion command.

Here is an example showing a keymap before and after substitution:

(setq map '(keymap 
            (?1 . olddef-1) 
            (?2 . olddef-2) 
            (?3 . olddef-1)))
=> (keymap (49 . olddef-1) (50 . olddef-2) (51 . olddef-1))

(substitute-key-definition 'olddef-1 'newdef map)
=> nil
map
=> (keymap (49 . newdef) (50 . olddef-2) (51 . newdef))

Function: suppress-keymap keymap &optional nodigits
This function changes the contents of the full keymap keymap by making all the printing characters undefined. More precisely, it binds them to the command undefined. This makes ordinary insertion of text impossible. suppress-keymap returns nil.

If nodigits is nil, then suppress-keymap defines digits to run digit-argument, and - to run negative-argument. Otherwise it makes them undefined like the rest of the printing characters.

The suppress-keymap function does not make it impossible to modify a buffer, as it does not suppress commands such as yank and quoted-insert. To prevent any modification of a buffer, make it read-only (see section Read-Only Buffers).

Since this function modifies keymap, you would normally use it on a newly created keymap. Operating on an existing keymap that is used for some other purpose is likely to cause trouble; for example, suppressing global-map would make it impossible to use most of Emacs.

Most often, suppress-keymap is used to initialize local keymaps of modes such as Rmail and Dired where insertion of text is not desirable and the buffer is read-only. Here is an example taken from the file `emacs/lisp/dired.el', showing how the local keymap for Dired mode is set up:

(setq dired-mode-map (make-keymap))
(suppress-keymap dired-mode-map)
(define-key dired-mode-map "r" 'dired-rename-file)
(define-key dired-mode-map "\C-d" 'dired-flag-file-deleted)
(define-key dired-mode-map "d" 'dired-flag-file-deleted)
(define-key dired-mode-map "v" 'dired-view-file)
(define-key dired-mode-map "e" 'dired-find-file)
(define-key dired-mode-map "f" 'dired-find-file)
...

Commands for Binding Keys

This section describes some convenient interactive interfaces for changing key bindings. They work by calling define-key.

People often use global-set-key in their `.emacs' file for simple customization. For example,

(global-set-key "\C-x\C-\\" 'next-line)

or

(global-set-key [?\C-x ?\C-\\] 'next-line)

or

(global-set-key [(control ?x) (control ?\\)] 'next-line)

redefines C-x C-\ to move down a line.

(global-set-key [M-mouse-1] 'mouse-set-point)

redefines the first (leftmost) mouse button, typed with the Meta key, to set point where you click.

Command: global-set-key key definition
This function sets the binding of key in the current global map to definition.

(global-set-key key definition)
==
(define-key (current-global-map) key definition)

Command: global-unset-key key
This function removes the binding of key from the current global map.

One use of this function is in preparation for defining a longer key that uses key as a prefix--which would not be allowed if key has a non-prefix binding. For example:

(global-unset-key "\C-l")
    => nil
(global-set-key "\C-l\C-l" 'redraw-display)
    => nil

This function is implemented simply using define-key:

(global-unset-key key)
==
(define-key (current-global-map) key nil)

Command: local-set-key key definition
This function sets the binding of key in the current local keymap to definition.

(local-set-key key definition)
==
(define-key (current-local-map) key definition)

Command: local-unset-key key
This function removes the binding of key from the current local map.

(local-unset-key key)
==
(define-key (current-local-map) key nil)

Scanning Keymaps

This section describes functions used to scan all the current keymaps for the sake of printing help information.

Function: accessible-keymaps keymap &optional prefix
This function returns a list of all the keymaps that can be reached (via zero or more prefix keys) from keymap. The value is an association list with elements of the form (key . map), where key is a prefix key whose definition in keymap is map.

The elements of the alist are ordered so that the key increases in length. The first element is always ("" . keymap), because the specified keymap is accessible from itself with a prefix of no events.

If prefix is given, it should be a prefix key sequence; then accessible-keymaps includes only the submaps whose prefixes start with prefix. These elements look just as they do in the value of (accessible-keymaps); the only difference is that some elements are omitted.

In the example below, the returned alist indicates that the key ESC, which is displayed as `^[', is a prefix key whose definition is the sparse keymap (keymap (83 . center-paragraph) (115 . foo)).

(accessible-keymaps (current-local-map))
=>(("" keymap 
      (27 keymap   ; Note this keymap for ESC is repeated below.
          (83 . center-paragraph)
          (115 . center-line))
      (9 . tab-to-tab-stop))

   ("^[" keymap 
    (83 . center-paragraph) 
    (115 . foo)))

In the following example, C-h is a prefix key that uses a sparse keymap starting with (keymap (118 . describe-variable)...). Another prefix, C-x 4, uses a keymap which is also the value of the variable ctl-x-4-map. The event mode-line is one of several dummy events used as prefixes for mouse actions in special parts of a window.

(accessible-keymaps (current-global-map))
=> (("" keymap [set-mark-command beginning-of-line ... 
                   delete-backward-char])
    ("^H" keymap (118 . describe-variable) ...
     (8 . help-for-help))
    ("^X" keymap [x-flush-mouse-queue ...
     backward-kill-sentence])
    ("^[" keymap [mark-sexp backward-sexp ...
     backward-kill-word])
    ("^X4" keymap (15 . display-buffer) ...)
    ([mode-line] keymap
     (S-mouse-2 . mouse-split-window-horizontally) ...))

These are not all the keymaps you would see in actuality.

Function: where-is-internal command &optional keymap firstonly noindirect
This function is a subroutine used by the where-is command (see section `Help' in The GNU Emacs Manual). It returns a list of key sequences (of any length) that are bound to command in a set of keymaps.

The argument command can be any object; it is compared with all keymap entries using eq.

If keymap is nil, then the maps used are the current active keymaps, disregarding overriding-local-map (that is, pretending its value is nil). If keymap is non-nil, then the maps searched are keymap and the global keymap.

Usually it's best to use overriding-local-map as the expression for keymap. Then where-is-internal searches precisely the keymaps that are active. To search only the global map, pass (keymap) (an empty keymap) as keymap.

If firstonly is non-ascii, then the value is a single string representing the first key sequence found, rather than a list of all possible key sequences. If firstonly is t, then the value is the first key sequence, except that key sequences consisting entirely of ASCII characters (or meta variants of ASCII characters) are preferred to all other key sequences.

If noindirect is non-nil, where-is-internal doesn't follow indirect keymap bindings. This makes it possible to search for an indirect definition itself.

(where-is-internal 'describe-function)
    => ("\^hf" "\^hd")

Command: describe-bindings &optional prefix
This function creates a listing of all current key bindings, and displays it in a buffer named `*Help*'. The text is grouped by modes--minor modes first, then the major mode, then global bindings.

If prefix is non-nil, it should be a prefix key; then the listing includes only keys that start with prefix.

The listing describes meta characters as ESC followed by the corresponding non-meta character.

When several characters with consecutive ASCII codes have the same definition, they are shown together, as `firstchar..lastchar'. In this instance, you need to know the ASCII codes to understand which characters this means. For example, in the default global map, the characters `SPC .. ~' are described by a single line. SPC is ASCII 32, ~ is ASCII 126, and the characters between them include all the normal printing characters, (e.g., letters, digits, punctuation, etc.); all these characters are bound to self-insert-command.

Menu Keymaps

A keymap can define a menu as well as bindings for keyboard keys and mouse button. Menus are usually actuated with the mouse, but they can work with the keyboard also.

Defining Menus

A keymap is suitable for menu use if it has an overall prompt string, which is a string that appears as an element of the keymap. (See section Format of Keymaps.) The string should describe the purpose of the menu. The easiest way to construct a keymap with a prompt string is to specify the string as an argument when you call make-keymap or make-sparse-keymap (see section Creating Keymaps).

The order of items in the menu is the same as the order of bindings in the keymap. Since define-key puts new bindings at the front, you should define the menu items starting at the bottom of the menu and moving to the top, if you care about the order. When you add an item to an existing menu, you can specify its position in the menu using define-key-after (see section Modifying Menus).

Simple Menu Items

The simpler and older way to define a menu keymap binding looks like this:

(item-string . real-binding)

The CAR, item-string, is the string to be displayed in the menu. It should be short--preferably one to three words. It should describe the action of the command it corresponds to.

You can also supply a second string, called the help string, as follows:

(item-string help-string . real-binding)

Currently Emacs does not actually use help-string; it knows only how to ignore help-string in order to extract real-binding. In the future we may use help-string as extended documentation for the menu item, available on request.

As far as define-key is concerned, item-string and help-string are part of the event's binding. However, lookup-key returns just real-binding, and only real-binding is used for executing the key.

If real-binding is nil, then item-string appears in the menu but cannot be selected.

If real-binding is a symbol and has a non-nil menu-enable property, that property is an expression that controls whether the menu item is enabled. Every time the keymap is used to display a menu, Emacs evaluates the expression, and it enables the menu item only if the expression's value is non-nil. When a menu item is disabled, it is displayed in a "fuzzy" fashion, and cannot be selected.

The menu bar does not recalculate which items are enabled every time you look at a menu. This is because the X toolkit requires the whole tree of menus in advance. To force recalculation of the menu bar, call force-mode-line-update (see section Mode Line Format).

You've probably noticed that menu items show the equivalent keyboard key sequence (if any) to invoke the same command. To save time on recalculation, menu display caches this information in a sublist in the binding, like this:

(item-string [help-string] (key-binding-data) . real-binding)

Don't put these sublists in the menu item yourself; menu display calculates them automatically. Don't mention keyboard equivalents in the item strings themselves, since that is redundant.

Extended Menu Items

An extended-format menu item is a more flexible and also cleaner alternative to the simple format. It consists of a list that starts with the symbol menu-item. To define a non-selectable string, the item looks like this:

(menu-item item-name)

where a string consisting of two or more dashes specifies a separator line.

To define a real menu item which can be selected, the extended format item looks like this:

(menu-item item-name real-binding
    . item-property-list)

Here, item-name is an expression which evaluates to the menu item string. Thus, the string need not be a constant. The third element, real-binding, is the command to execute. The tail of the list, item-property-list, has the form of a property list which contains other information. Here is a table of the properties that are supported:

:enable FORM
The result of evaluating form determines whether the item is enabled (non-nil means yes).
:visible FORM
The result of evaluating form determines whether the item should actually appear in the menu (non-nil means yes). If the item does not appear, then the menu is displayed as if this item were not defined at all.
:help help
The value of this property, help, is the extra help string (not currently used by Emacs).
:button (type . selected)
This property provides a way to define radio buttons and toggle buttons. The CAR, type, says which: is should be :toggle or :radio. The CDR, selected, should be a form; the result of evaluating it says whether this button is currently selected. A toggle is a menu item which is labeled as either "on" or "off" according to the value of selected. The command itself should toggle selected, setting it to t if it is nil, and to nil if it is t. Here is how the menu item to toggle the debug-on-error flag is defined:
(menu-item "Debug on Error" toggle-debug-on-error
           :button (:toggle
                    . (and (boundp 'debug-on-error)
                           debug-on-error))
This works because toggle-debug-on-error is defined as a command which toggles the variable debug-on-error. Radio buttons are a group of menu items, in which at any time one and only one is "selected." There should be a variable whose value says which one is selected at any time. The selected form for each radio button in the group should check whether the variable has the right value for selecting that button. Clicking on the button should set the variable so that the button you clicked on becomes selected.
:key-sequence key-sequence
This property specifies which key sequence is likely to be bound to the same command invoked by this menu item. If you specify the right key sequence, that makes preparing the menu for display run much faster. If you specify the wrong key sequence, it has no effect; before Emacs displays key-sequence in the menu, it verifies that key-sequence is really equivalent to this menu item.
:key-sequence nil
This property indicates that there is normally no key binding which is equivalent to this menu item. Using this property saves time in preparing the menu for display, because Emacs does not need to search the keymaps for a keyboard equivalent for this menu item. However, if the user has rebound this item's definition to a key sequence, Emacs ignores the :keys property and finds the keyboard equivalent anyway.
:keys string
This property specifies that string is the string to display as the keyboard equivalent for this menu item. You can use the `\\[...]' documentation construct in string.
:filter filter-fn
This property provides a way to compute the menu item dynamically. The property value filter-fn should be a function of one argument; when it is called, its argument will be real-binding. The function should return the binding to use instead.

Alias Menu Items

Sometimes it is useful to make menu items that use the "same" command but with different enable conditions. The best way to do this in Emacs now is with extended menu items; before that feature existed, it could be done by defining alias commands and using them in menu items. Here's an example that makes two aliases for toggle-read-only and gives them different enable conditions:

(defalias 'make-read-only 'toggle-read-only)
(put 'make-read-only 'menu-enable '(not buffer-read-only))
(defalias 'make-writable 'toggle-read-only)
(put 'make-writable 'menu-enable 'buffer-read-only)

When using aliases in menus, often it is useful to display the equivalent key bindings for the "real" command name, not the aliases (which typically don't have any key bindings except for the menu itself). To request this, give the alias symbol a non-nil menu-alias property. Thus,

(put 'make-read-only 'menu-alias t)
(put 'make-writable 'menu-alias t)

causes menu items for make-read-only and make-writable to show the keyboard bindings for toggle-read-only.

Menus and the Mouse

The usual way to make a menu keymap produce a menu is to make it the definition of a prefix key. (A Lisp program can explicitly pop up a menu and receive the user's choice--see section Pop-Up Menus.)

If the prefix key ends with a mouse event, Emacs handles the menu keymap by popping up a visible menu, so that the user can select a choice with the mouse. When the user clicks on a menu item, the event generated is whatever character or symbol has the binding that brought about that menu item. (A menu item may generate a series of events if the menu has multiple levels or comes from the menu bar.)

It's often best to use a button-down event to trigger the menu. Then the user can select a menu item by releasing the button.

A single keymap can appear as multiple menu panes, if you explicitly arrange for this. The way to do this is to make a keymap for each pane, then create a binding for each of those maps in the main keymap of the menu. Give each of these bindings an item string that starts with `@'. The rest of the item string becomes the name of the pane. See the file `lisp/mouse.el' for an example of this. Any ordinary bindings with `@'-less item strings are grouped into one pane, which appears along with the other panes explicitly created for the submaps.

X toolkit menus don't have panes; instead, they can have submenus. Every nested keymap becomes a submenu, whether the item string starts with `@' or not. In a toolkit version of Emacs, the only thing special about `@' at the beginning of an item string is that the `@' doesn't appear in the menu item.

You can also produce multiple panes or submenus from separate keymaps. The full definition of a prefix key always comes from merging the definitions supplied by the various active keymaps (minor mode, local, and global). When more than one of these keymaps is a menu, each of them makes a separate pane or panes (when Emacs does not use an X-toolkit) or a separate submenu (when using an X-toolkit). See section Active Keymaps.

Menus and the Keyboard

When a prefix key ending with a keyboard event (a character or function key) has a definition that is a menu keymap, the user can use the keyboard to choose a menu item.

Emacs displays the menu alternatives (the item strings of the bindings) in the echo area. If they don't all fit at once, the user can type SPC to see the next line of alternatives. Successive uses of SPC eventually get to the end of the menu and then cycle around to the beginning. (The variable menu-prompt-more-char specifies which character is used for this; SPC is the default.)

When the user has found the desired alternative from the menu, he or she should type the corresponding character--the one whose binding is that alternative.

This way of using menus in an Emacs-like editor was inspired by the Hierarkey system.

Variable: menu-prompt-more-char
This variable specifies the character to use to ask to see the next line of a menu. Its initial value is 32, the code for SPC.

Menu Example

Here is a complete example of defining a menu keymap. It is the definition of the `Print' submenu in the `Tools' menu in the menu bar, and it uses the simple menu item format (see section Simple Menu Items). First we create the keymap, and give it a name:

(defvar menu-bar-print-menu (make-sparse-keymap "Print"))

Next we define the menu items:

(define-key menu-bar-print-menu [ps-print-region]
  '("Postscript Print Region" . ps-print-region-with-faces))
(define-key menu-bar-print-menu [ps-print-buffer]
  '("Postscript Print Buffer" . ps-print-buffer-with-faces))
(define-key menu-bar-print-menu [separator-ps-print]
  '("--"))
(define-key menu-bar-print-menu [print-region]
  '("Print Region" . print-region))
(define-key menu-bar-print-menu [print-buffer]
  '("Print Buffer" . print-buffer))

Note the symbols which the bindings are "made for"; these appear inside square brackets, in the key sequence being defined. In some cases, this symbol is the same as the command name; sometimes it is different. These symbols are treated as "function keys", but they are not real function keys on the keyboard. They do not affect the functioning of the menu itself, but they are "echoed" in the echo area when the user selects from the menu, and they appear in the output of where-is and apropos.

The binding whose definition is ("--") is a separator line. Like a real menu item, the separator has a key symbol, in this case separator-ps-print. If one menu has two separators, they must have two different key symbols.

Here is code to define enable conditions for two of the commands in the menu:

(put 'print-region 'menu-enable 'mark-active)
(put 'ps-print-region-with-faces 'menu-enable 'mark-active)

Here is how we make this menu appear as an item in the parent menu:

(define-key menu-bar-tools-menu [print]
  (cons "Print" menu-bar-print-menu))

Note that this incorporates the submenu keymap, which is the value of the variable menu-bar-print-menu, rather than the symbol menu-bar-print-menu itself. Using that symbol in the parent menu item would be meaningless because menu-bar-print-menu is not a command.

If you wanted to attach the same print menu to a mouse click, you can do it this way:

(define-key global-map [C-S-down-mouse-1]
   menu-bar-print-menu)

We could equally well use an extended menu item (see section Extended Menu Items) for print-region, like this:

(define-key menu-bar-print-menu [print-region]
  '(menu-item "Print Region" print-region
              :enable (mark-active)))

With the extended menu item, the enable condition is specified inside the menu item itself. If we wanted to make this item disappear from the menu entirely when the mark is inactive, we could do it this way:

(define-key menu-bar-print-menu [print-region]
  '(menu-item "Print Region" print-region
              :visible (mark-active)))

The Menu Bar

Most window systems allow each frame to have a menu bar---a permanently displayed menu stretching horizontally across the top of the frame. The items of the menu bar are the subcommands of the fake "function key" menu-bar, as defined by all the active keymaps.

To add an item to the menu bar, invent a fake "function key" of your own (let's call it key), and make a binding for the key sequence [menu-bar key]. Most often, the binding is a menu keymap, so that pressing a button on the menu bar item leads to another menu.

When more than one active keymap defines the same fake function key for the menu bar, the item appears just once. If the user clicks on that menu bar item, it brings up a single, combined menu containing all the subcommands of that item--the global subcommands, the local subcommands, and the minor mode subcommands.

The variable overriding-local-map is normally ignored when determining the menu bar contents. That is, the menu bar is computed from the keymaps that would be active if overriding-local-map were nil. See section Active Keymaps.

In order for a frame to display a menu bar, its menu-bar-lines parameter must be greater than zero. Emacs uses just one line for the menu bar itself; if you specify more than one line, the other lines serve to separate the menu bar from the windows in the frame. We recommend 1 or 2 as the value of menu-bar-lines. See section Window Frame Parameters.

Here's an example of setting up a menu bar item:

(modify-frame-parameters (selected-frame)
                         '((menu-bar-lines . 2)))

;; Make a menu keymap (with a prompt string)
;; and make it the menu bar item's definition.
(define-key global-map [menu-bar words]
  (cons "Words" (make-sparse-keymap "Words")))

;; Define specific subcommands in this menu.
(define-key global-map
  [menu-bar words forward]
  '("Forward word" . forward-word))
(define-key global-map
  [menu-bar words backward]
  '("Backward word" . backward-word))

A local keymap can cancel a menu bar item made by the global keymap by rebinding the same fake function key with undefined as the binding. For example, this is how Dired suppresses the `Edit' menu bar item:

(define-key dired-mode-map [menu-bar edit] 'undefined)

edit is the fake function key used by the global map for the `Edit' menu bar item. The main reason to suppress a global menu bar item is to regain space for mode-specific items.

Variable: menu-bar-final-items
Normally the menu bar shows global items followed by items defined by the local maps.

This variable holds a list of fake function keys for items to display at the end of the menu bar rather than in normal sequence. The default value is (help-menu); thus, the `Help' menu item normally appears at the end of the menu bar, following local menu items.

Variable: menu-bar-update-hook
This normal hook is run whenever the user clicks on the menu bar, before displaying a submenu. You can use it to update submenus whose contents should vary.

Modifying Menus

When you insert a new item in an existing menu, you probably want to put it in a particular place among the menu's existing items. If you use define-key to add the item, it normally goes at the front of the menu. To put it elsewhere in the menu, use define-key-after:

Function: define-key-after map key binding after
Define a binding in map for key, with value binding, just like define-key, but position the binding in map after the binding for the event after. The argument key should be of length one--a vector or string with just one element. But after should be a single event type--a symbol or a character, not a sequence. The new binding goes after the binding for after. If after is t, then the new binding goes last, at the end of the keymap.

Here is an example:

(define-key-after my-menu [drink]
                  '("Drink" . drink-command) 'eat)

makes a binding for the fake function key DRINK and puts it right after the binding for EAT.

Here is how to insert an item called `Work' in the `Signals' menu of Shell mode, after the item break:

(define-key-after
  (lookup-key shell-mode-map [menu-bar signals])
  [work] '("Work" . work-command) 'break)

Major and Minor Modes

A mode is a set of definitions that customize Emacs and can be turned on and off while you edit. There are two varieties of modes: major modes, which are mutually exclusive and used for editing particular kinds of text, and minor modes, which provide features that users can enable individually.

This chapter describes how to write both major and minor modes, how to indicate them in the mode line, and how they run hooks supplied by the user. For related topics such as keymaps and syntax tables, see section Keymaps, and section Syntax Tables.

Major Modes

Major modes specialize Emacs for editing particular kinds of text. Each buffer has only one major mode at a time.

The least specialized major mode is called Fundamental mode. This mode has no mode-specific definitions or variable settings, so each Emacs command behaves in its default manner, and each option is in its default state. All other major modes redefine various keys and options. For example, Lisp Interaction mode provides special key bindings for C-j (eval-print-last-sexp), TAB (lisp-indent-line), and other keys.

When you need to write several editing commands to help you perform a specialized editing task, creating a new major mode is usually a good idea. In practice, writing a major mode is easy (in contrast to writing a minor mode, which is often difficult).

If the new mode is similar to an old one, it is often unwise to modify the old one to serve two purposes, since it may become harder to use and maintain. Instead, copy and rename an existing major mode definition and alter the copy--or define a derived mode (see section Defining Derived Modes). For example, Rmail Edit mode, which is in `emacs/lisp/rmailedit.el', is a major mode that is very similar to Text mode except that it provides three additional commands. Its definition is distinct from that of Text mode, but was derived from it.

Rmail Edit mode offers an example of changing the major mode temporarily for a buffer, so it can be edited in a different way (with ordinary Emacs commands rather than Rmail commands). In such cases, the temporary major mode usually has a command to switch back to the buffer's usual mode (Rmail mode, in this case). You might be tempted to present the temporary redefinitions inside a recursive edit and restore the usual ones when the user exits; but this is a bad idea because it constrains the user's options when it is done in more than one buffer: recursive edits must be exited most-recently-entered first. Using an alternative major mode avoids this limitation. See section Recursive Editing.

The standard GNU Emacs Lisp library directory contains the code for several major modes, in files such as `text-mode.el', `texinfo.el', `lisp-mode.el', `c-mode.el', and `rmail.el'. You can study these libraries to see how modes are written. Text mode is perhaps the simplest major mode aside from Fundamental mode. Rmail mode is a complicated and specialized mode.

Major Mode Conventions

The code for existing major modes follows various coding conventions, including conventions for local keymap and syntax table initialization, global names, and hooks. Please follow these conventions when you define a new major mode:

Major Mode Examples

Text mode is perhaps the simplest mode besides Fundamental mode. Here are excerpts from `text-mode.el' that illustrate many of the conventions listed above:

;; Create mode-specific tables.
(defvar text-mode-syntax-table nil 
  "Syntax table used while in text mode.")

(if text-mode-syntax-table
    ()              ; Do not change the table if it is already set up.
  (setq text-mode-syntax-table (make-syntax-table))
  (modify-syntax-entry ?\" ".   " text-mode-syntax-table)
  (modify-syntax-entry ?\\ ".   " text-mode-syntax-table)
  (modify-syntax-entry ?' "w   " text-mode-syntax-table))

(defvar text-mode-abbrev-table nil
  "Abbrev table used while in text mode.")
(define-abbrev-table 'text-mode-abbrev-table ())

(defvar text-mode-map nil)   ; Create a mode-specific keymap.

(if text-mode-map
    ()              ; Do not change the keymap if it is already set up.
  (setq text-mode-map (make-sparse-keymap))
  (define-key text-mode-map "\t" 'indent-relative)
  (define-key text-mode-map "\es" 'center-line)
  (define-key text-mode-map "\eS" 'center-paragraph))

Here is the complete major mode function definition for Text mode:

(defun text-mode ()
  "Major mode for editing text intended for humans to [email protected]{}
 Special commands: \\{text-mode-map}
Turning on text-mode runs the hook `text-mode-hook'."
  (interactive)
  (kill-all-local-variables)
  (use-local-map text-mode-map)
  (setq local-abbrev-table text-mode-abbrev-table)
  (set-syntax-table text-mode-syntax-table)
  (make-local-variable 'paragraph-start)
  (setq paragraph-start (concat "[ \t]*$\\|" page-delimiter))
  (make-local-variable 'paragraph-separate)
  (setq paragraph-separate paragraph-start)
  (setq mode-name "Text")
  (setq major-mode 'text-mode)
  (run-hooks 'text-mode-hook))      ; Finally, this permits the user to
                                    ;   customize the mode with a hook.

The three Lisp modes (Lisp mode, Emacs Lisp mode, and Lisp Interaction mode) have more features than Text mode and the code is correspondingly more complicated. Here are excerpts from `lisp-mode.el' that illustrate how these modes are written.

;; Create mode-specific table variables.
(defvar lisp-mode-syntax-table nil "")  
(defvar emacs-lisp-mode-syntax-table nil "")
(defvar lisp-mode-abbrev-table nil "")

(if (not emacs-lisp-mode-syntax-table) ; Do not change the table
                                       ;   if it is already set.
    (let ((i 0))
      (setq emacs-lisp-mode-syntax-table (make-syntax-table))

      ;; Set syntax of chars up to 0 to class of chars that are
      ;;   part of symbol names but not words.
      ;;   (The number 0 is 48 in the ASCII character set.)
      (while (< i ?0) 
        (modify-syntax-entry i "_   " emacs-lisp-mode-syntax-table)
        (setq i (1+ i)))
      ...
      ;; Set the syntax for other characters.
      (modify-syntax-entry ?  "    " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?\t "    " emacs-lisp-mode-syntax-table)
      ...
      (modify-syntax-entry ?\( "()  " emacs-lisp-mode-syntax-table)
      (modify-syntax-entry ?\) ")(  " emacs-lisp-mode-syntax-table)
      ...))
;; Create an abbrev table for lisp-mode.
(define-abbrev-table 'lisp-mode-abbrev-table ())

Much code is shared among the three Lisp modes. The following function sets various variables; it is called by each of the major Lisp mode functions:

(defun lisp-mode-variables (lisp-syntax)
  (cond (lisp-syntax
	  (set-syntax-table lisp-mode-syntax-table)))
  (setq local-abbrev-table lisp-mode-abbrev-table)
  ...

Functions such as forward-paragraph use the value of the paragraph-start variable. Since Lisp code is different from ordinary text, the paragraph-start variable needs to be set specially to handle Lisp. Also, comments are indented in a special fashion in Lisp and the Lisp modes need their own mode-specific comment-indent-function. The code to set these variables is the rest of lisp-mode-variables.

  (make-local-variable 'paragraph-start)
  (setq paragraph-start (concat page-delimiter "\\|$" ))
  (make-local-variable 'paragraph-separate)
  (setq paragraph-separate paragraph-start)
  ...
  (make-local-variable 'comment-indent-function)
  (setq comment-indent-function 'lisp-comment-indent))

Each of the different Lisp modes has a slightly different keymap. For example, Lisp mode binds C-c C-z to run-lisp, but the other Lisp modes do not. However, all Lisp modes have some commands in common. The following code sets up the common commands:

(defvar shared-lisp-mode-map ()
  "Keymap for commands shared by all sorts of Lisp modes.")

(if shared-lisp-mode-map
    ()
   (setq shared-lisp-mode-map (make-sparse-keymap))
   (define-key shared-lisp-mode-map "\e\C-q" 'indent-sexp)
   (define-key shared-lisp-mode-map "\177"
               'backward-delete-char-untabify))

And here is the code to set up the keymap for Lisp mode:

(defvar lisp-mode-map ()
  "Keymap for ordinary Lisp [email protected]{}")

(if lisp-mode-map
    ()
  (setq lisp-mode-map (make-sparse-keymap))
  (set-keymap-parent lisp-mode-map shared-lisp-mode-map)
  (define-key lisp-mode-map "\e\C-x" 'lisp-eval-defun)
  (define-key lisp-mode-map "\C-c\C-z" 'run-lisp))

Finally, here is the complete major mode function definition for Emacs Lisp mode.

(defun lisp-mode ()
  "Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
Commands:
Delete converts tabs to spaces as it moves back.
Blank lines separate paragraphs.  Semicolons start comments.
\\{lisp-mode-map}
Note that `run-lisp' may be used either to start an inferior Lisp job
or to switch back to an existing one.

Entry to this mode calls the value of `lisp-mode-hook'
if that value is non-nil."
  (interactive)
  (kill-all-local-variables)
  (use-local-map lisp-mode-map)          ; Select the mode's keymap.
  (setq major-mode 'lisp-mode)           ; This is how describe-mode
                                         ;   finds out what to describe.
  (setq mode-name "Lisp")                ; This goes into the mode line.
  (lisp-mode-variables t)                ; This defines various variables.
  (setq imenu-case-fold-search t)
  (set-syntax-table lisp-mode-syntax-table)
  (run-hooks 'lisp-mode-hook))           ; This permits the user to use a
                                         ;   hook to customize the mode.

How Emacs Chooses a Major Mode

Based on information in the file name or in the file itself, Emacs automatically selects a major mode for the new buffer when a file is visited. It also processes local variables specified in the file text.

Command: fundamental-mode
Fundamental mode is a major mode that is not specialized for anything in particular. Other major modes are defined in effect by comparison with this one--their definitions say what to change, starting from Fundamental mode. The fundamental-mode function does not run any hooks; you're not supposed to customize it. (If you want Emacs to behave differently in Fundamental mode, change the global state of Emacs.)

Command: normal-mode &optional find-file
This function establishes the proper major mode and buffer-local variable bindings for the current buffer. First it calls set-auto-mode, then it runs hack-local-variables to parse, and bind or evaluate as appropriate, the file's local variables.

If the find-file argument to normal-mode is non-nil, normal-mode assumes that the find-file function is calling it. In this case, it may process a local variables list at the end of the file and in the `-*-' line. The variable enable-local-variables controls whether to do so. See section `Local Variables in Files' in The GNU Emacs Manual, for the syntax of the local variables section of a file.

If you run normal-mode interactively, the argument find-file is normally nil. In this case, normal-mode unconditionally processes any local variables list.

normal-mode uses condition-case around the call to the major mode function, so errors are caught and reported as a `File mode specification error', followed by the original error message.

User Option: enable-local-variables
This variable controls processing of local variables lists in files being visited. A value of t means process the local variables lists unconditionally; nil means ignore them; anything else means ask the user what to do for each file. The default value is t.

Variable: ignored-local-variables
This variable holds a list of variables that should not be set by a file's local variables list. Any value specified for one of these variables is ignored.

In addition to this list, any variable whose name has a non-nil risky-local-variable property is also ignored.

User Option: enable-local-eval
This variable controls processing of `Eval:' in local variables lists in files being visited. A value of t means process them unconditionally; nil means ignore them; anything else means ask the user what to do for each file. The default value is maybe.

Function: set-auto-mode
This function selects the major mode that is appropriate for the current buffer. It may base its decision on the value of the `-*-' line, on the visited file name (using auto-mode-alist), on the `#!' line (using interpreter-mode-alist), or on the file's local variables list. However, this function does not look for the `mode:' local variable near the end of a file; the hack-local-variables function does that. See section `How Major Modes are Chosen' in The GNU Emacs Manual.

User Option: default-major-mode
This variable holds the default major mode for new buffers. The standard value is fundamental-mode.

If the value of default-major-mode is nil, Emacs uses the (previously) current buffer's major mode for the major mode of a new buffer. However, if that major mode symbol has a mode-class property with value special, then it is not used for new buffers; Fundamental mode is used instead. The modes that have this property are those such as Dired and Rmail that are useful only with text that has been specially prepared.

Function: set-buffer-major-mode buffer
This function sets the major mode of buffer to the value of default-major-mode. If that variable is nil, it uses the current buffer's major mode (if that is suitable).

The low-level primitives for creating buffers do not use this function, but medium-level commands such as switch-to-buffer and find-file-noselect use it whenever they create buffers.

Variable: initial-major-mode
The value of this variable determines the major mode of the initial `*scratch*' buffer. The value should be a symbol that is a major mode command. The default value is lisp-interaction-mode.

Variable: auto-mode-alist
This variable contains an association list of file name patterns (regular expressions; see section Regular Expressions) and corresponding major mode commands. Usually, the file name patterns test for suffixes, such as `.el' and `.c', but this need not be the case. An ordinary element of the alist looks like (regexp . mode-function).

For example,

(("\\`/tmp/fol/" . text-mode)
 ("\\.texinfo\\'" . texinfo-mode)
 ("\\.texi\\'" . texinfo-mode)
 ("\\.el\\'" . emacs-lisp-mode)
 ("\\.c\\'" . c-mode) 
 ("\\.h\\'" . c-mode)
 ...)

When you visit a file whose expanded file name (see section Functions that Expand Filenames) matches a regexp, set-auto-mode calls the corresponding mode-function. This feature enables Emacs to select the proper major mode for most files.

If an element of auto-mode-alist has the form (regexp function t), then after calling function, Emacs searches auto-mode-alist again for a match against the portion of the file name that did not match before. This feature is useful for uncompression packages: an entry of the form ("\\.gz\\'" function t) can uncompress the file and then put the uncompressed file in the proper mode according to the name sans `.gz'.

Here is an example of how to prepend several pattern pairs to auto-mode-alist. (You might use this sort of expression in your `.emacs' file.)

(setq auto-mode-alist
  (append 
   ;; File name (within directory) starts with a dot.
   '(("/\\.[^/]*\\'" . fundamental-mode)  
     ;; File name has no dot.
     ("[^\\./]*\\'" . fundamental-mode)   
     ;; File name ends in `.C'.
     ("\\.C\\'" . c++-mode))
   auto-mode-alist))

Variable: interpreter-mode-alist
This variable specifies major modes to use for scripts that specify a command interpreter in an `#!' line. Its value is a list of elements of the form (interpreter . mode); for example, ("perl" . perl-mode) is one element present by default. The element says to use mode mode if the file specifies an interpreter which matches interpreter. The value of interpreter is actually a regular expression.

This variable is applicable only when the auto-mode-alist does not indicate which major mode to use.

Function: hack-local-variables &optional force
This function parses, and binds or evaluates as appropriate, any local variables specified by the contents of the current buffer.

The handling of enable-local-variables documented for normal-mode actually takes place here. The argument force usually comes from the argument find-file given to normal-mode.

Getting Help about a Major Mode

The describe-mode function is used to provide information about major modes. It is normally called with C-h m. The describe-mode function uses the value of major-mode, which is why every major mode function needs to set the major-mode variable.

Command: describe-mode
This function displays the documentation of the current major mode.

The describe-mode function calls the documentation function using the value of major-mode as an argument. Thus, it displays the documentation string of the major mode function. (See section Access to Documentation Strings.)

Variable: major-mode
This variable holds the symbol for the current buffer's major mode. This symbol should have a function definition that is the command to switch to that major mode. The describe-mode function uses the documentation string of the function as the document