This is edition 2.9 of the GNU Emacs Lisp Reference Manual, corresponding to GNU Emacs version 22.1.
Appendices
--- The Detailed Node Listing --- ---------------------------------
Here are other nodes that are inferiors of those already listed, mentioned here so you can get to them in one step:
Introduction
Conventions
Format of Descriptions
Lisp Data Types
Programming Types
Character Type
Cons Cell and List Types
String Type
Editing Types
Numbers
Strings and Characters
Lists
Modifying Existing List Structure
Sequences, Arrays, and Vectors
Hash Tables
Symbols
Property Lists
Evaluation
Kinds of Forms
Control Structures
Nonlocal Exits
Errors
Variables
Scoping Rules for Variable Bindings
Buffer-Local Variables
Functions
Lambda Expressions
Macros
Common Problems Using Macros
Writing Customization Definitions
Customization Types
Loading
Byte Compilation
Advising Emacs Lisp Functions
Debugging Lisp Programs
The Lisp Debugger
Edebug
Debugging Invalid Lisp Syntax
Reading and Printing Lisp Objects
Minibuffers
Completion
Command Loop
Defining Commands
Input Events
Reading Input
Keymaps
Major and Minor Modes
Menu Keymaps
Defining Menus
Major and Minor Modes
Major Modes
Minor Modes
Mode Line Format
Font Lock Mode
Multiline Font Lock Constructs
Documentation
Files
Visiting Files
Information about Files
File Names
Backups and Auto-Saving
Backup Files
Buffers
Windows
Frames
Frame Parameters
Window Frame Parameters
Positions
Motion
Markers
Text
The Kill Ring
Indentation
Text Properties
Non-ASCII Characters
Coding Systems
Searching and Matching
Regular Expressions
Syntax of Regular Expressions
The Match Data
Syntax Tables
Syntax Descriptors
Parsing Expressions
Abbrevs And Abbrev Expansion
Processes
Receiving Output from Processes
Low-Level Network Access
Packing and Unpacking Byte Arrays
Emacs Display
The Echo Area
Reporting Warnings
Overlays
Faces
Fringes
The display Property
Images
Buttons
Abstract Display
Display Tables
Operating System Interface
Starting Up Emacs
Getting Out of Emacs
Terminal Input
Tips and Conventions
GNU Emacs Internals
Object Internals
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.9 of the GNU Emacs Lisp Reference Manual, corresponding to Emacs version 22.1.
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 this manual, we ask that you send corrections as soon as you find them. 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 node name and function or variable name, as appropriate. Also state the number of the edition you are criticizing.
Please mail comments and corrections to
bug-lisp-manual@gnu.org
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
bug-gnu-emacs@gnu.org.
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 Overview.
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.
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.
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 Printed Representation, 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 are formatted like this: (list 1 2 3).
Names that represent metasyntactic variables, or arguments to a function
being described, are formatted like this: 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 write () when we wish to emphasize that it
means the empty list, and we write 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 (setq foo-flag 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. See Constant Variables.
Return non-nil iff object is one of the two canonical boolean values:
tornil.
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)
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.
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 with
`=>'.
(progn (prin1 'foo) (princ "\n") (prin1 'bar))
-| foo
-| bar
=> bar
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
Some examples describe modifications to the contents of a buffer, by showing the “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 ----------
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—appears at the beginning of the line. The description follows on succeeding lines, sometimes with examples.
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 argument name following &rest will receive, as its
value, a list of all the remaining arguments passed to the function.
Do not write &rest when you call the function.
Here is a description of an imaginary function foo:
The function
foosubtracts 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) => 14More 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 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 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:
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
nilbefore the loop begins, and the loop exits if var is non-nilat 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 variable is a name that can hold a value. Although nearly all variables can be set by the user, certain variables exist specifically so that users can change them; these 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.
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'.
These facilities provide information about which version of Emacs is in use.
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"If here is non-
nil, it inserts the text in the buffer before point, and returnsnil. Called interactively, the function prints the same information in the echo area, but giving a prefix argument makes here non-nil.
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 Time of Day).emacs-build-time => (13623 62065 344633)
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. A value with four numeric components, such as"20.3.9.1", indicates an unreleased test version.
The following two variables have existed since Emacs version 19.23:
The major version number of Emacs, as an integer. For Emacs version 20.3, the value is 20.
The minor version number of Emacs, as an integer. For Emacs version 20.3, the value is 3.
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 Starbäck, Shinichirou Sugou, Kimmo Suominen, Edward Tharp, Bill Trost, Rickard Westman, Jean White, Matthew Wilding, Carl Witty, Dale Worley, Rusty Wright, and David D. Zuhn.
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, hash-table, subr, and byte-code function, plus several special types, such as buffer, that are related to editing. (See 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. (Actually, a small number of Emacs Lisp variables can only take on values of a certain type. See Variables with Restricted Values.)
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.
The printed representation of an object is the format of the
output generated by the Lisp printer (the function prin1) for
that object. Every data type has a unique printed representation.
The read syntax of an object is the format of the input accepted
by the Lisp reader (the function read) for that object. This
is not necessarily unique; many kinds of object have more than one
syntax. See Read and Print.
In most cases, an object's printed representation is also a read syntax for the object. However, some types have no read syntax, since it does not make sense to enter objects of these types as constants in a Lisp program. These objects are printed in hash notation, which consists of the characters `#<', a descriptive string (typically the type name followed by the name of the object), and a closing `>'. For example:
(current-buffer)
=> #<buffer objects.texi>
Hash notation cannot be read at all, so the Lisp reader signals the
error invalid-read-syntax whenever it encounters `#<'.
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.
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 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 Input Functions, for a description of
read, the basic function for reading objects.
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 Byte Compilation). It isn't meant for source files, however.
See Comment Tips, for conventions for formatting comments.
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.
The range of values for integers in Emacs Lisp is −268435456 to
268435455 (29 bits; i.e.,
-2**28
to
2**28 - 1)
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+ 268435455) is −268435456 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. 536870913 ; Also the integer 1 on a 29-bit implementation.
See Numbers, for more information.
Floating point numbers are the computer equivalent of scientific
notation; you can think of a floating point number as a fraction
together with a power of ten. The precise number of significant
figures and the range of possible exponents is machine-specific; Emacs
uses the C data type double to store the value, and internally
this records a power of 2 rather than a power of 10.
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 Numbers, for more information.
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 used occasionally in programs, but it is more common to work with strings, which are sequences composed of characters. See 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 Non-ASCII Characters). Characters that represent keyboard input have a much wider range, to encode modifier keys such as Control, Meta and Shift.
There are special functions for producing a human-readable textual description of a character for the sake of messages. See Describing Characters.
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 not clear programming. 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 open-paren 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, space, return, del, and escape as `?\a', `?\b', `?\t', `?\n', `?\v', `?\f', `?\s', `?\r', `?\d', and `?\e', respectively. (`?\s' followed by a dash has a different meaning—it applies the “super” modifier to the following character.) Thus,
?\a => 7 ; control-g, 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-[ ?\s => 32 ; space character, <SPC> ?\\ => 92 ; backslash character, \ ?\d => 127 ; delete character, <DEL>
These sequences which start with backslash are also known as escape sequences, because backslash plays the role of an “escape character”; this terminology has nothing to do with the character <ESC>. `\s' is meant for use in character constants; in string constants, just write the space.
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. You can 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' or `\s', instead of an actual whitespace character such as a tab or a space. (If you do write backslash followed by a space, you should write an extra space after the character constant to separate it from the following text.)
In addition to the specific excape sequences for special important control characters, Emacs provides general categories of escape syntax that you can use to specify non-ASCII text characters.
For instance, you can specify characters by their Unicode values.
?\unnnn represents a character that maps to the Unicode
code point `U+nnnn'. There is a slightly different syntax
for specifying characters with code points above #xFFFF;
\U00nnnnnn represents the character whose Unicode code
point is `U+nnnnnn', if such a character is supported by
Emacs. If the corresponding character is not supported, Emacs signals
an error.
This peculiar and inconvenient syntax was adopted for compatibility with other programming languages. Unlike some other languages, Emacs Lisp supports this syntax in only character literals and strings.
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 Latin-1 character
`a' with grave accent.
Control characters can 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 2**26 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 2**27 bit set. We use high bits for this and other modifiers to make possible a wide range of basic character codes.
In a string, the 2**7 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 2**25 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 Lisp syntax for the shift bit is `\S-'; thus, `?\C-\S-o' or `?\C-\S-O' represents the shifted-control-o character.
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. (Note that `\s' with no following `-' represents the space character.) Numerically, the bit values are 2**22 for alt, 2**23 for super and 2**24 for hyper.
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 Lisp use, with one single obarray (see Creating Symbols, a symbol's 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 whose name starts with a colon (`:') is called a keyword symbol. These symbols automatically act as constants, and are normally used only by comparing an unknown symbol with a few specific alternatives.
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 `_~!@$%^&:<>{}?' 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 fourth 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). +-*/_~!@$%^&=:<>{} ; A symbol named `+-*/_~!@$%^&=:<>{}'. ; These characters need not be escaped.
Normally the Lisp reader interns all symbols (see Creating Symbols). To prevent interning, you can write `#:' before the name of the symbol.
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. Char-tables are like vectors except that they are
indexed by any valid character code. The characters in a string can
have text properties like characters in a buffer (see Text Properties), but vectors do not support text properties, even when
their elements happen to be characters.
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 Sequences Arrays 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.
A cons cell is an object that consists of two slots, called the car slot and the cdr slot. Each slot can hold or refer to any Lisp object. We also say that “the car of this cons cell is” whatever object its car slot currently holds, and likewise for the cdr.
A note to C programmers: in Lisp, we do not distinguish between “holding” a value and “pointing to” the value, because pointers in Lisp are implicit.
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. The empty list is actually the symbol nil.
See 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.
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. Here are examples of lists:
(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:Aand the empty list. (A nil) ; Equivalent to the previous. ((A B C)) ; A list of one element ; (which is a list of three elements).
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 holds the element, and its cdr
slot refers 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
hold nil.
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 was named
for its purpose, the construction of cells.
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 hold or refer to any Lisp object. Each pair of boxes represents a cons cell. Each arrow represents a reference 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, refers to or “holds” rose (a symbol). The second
box, holding the cdr of the first cons cell, refers 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 is the list (A ()), or equivalently (A nil),
depicted with boxes and arrows:
--- --- --- ---
| | |--> | | |--> nil
--- --- --- ---
| |
| |
--> A --> nil
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 second 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 |
| | | | | |
-------------- ----------------
Dotted pair notation is a general 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 more general than list syntax because the cdr
does not have to be a list. However, it is more cumbersome in cases
where list syntax would work. In 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))).
It looks like this:
--- --- --- --- --- ---
| | |--> | | |--> | | |--> nil
--- --- --- --- --- ---
| | |
| | |
--> rose --> violet --> buttercup
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 Association Lists, for a further explanation of alists and for functions that work on alists. See Hash Tables, for another kind of lookup table, which is much faster for handling a large number of keys.
An array is composed of an arbitrary number of slots for holding or referring 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 nested one-dimensional arrays.) Each type of array has its own read syntax; see the following sections for details.
The array type is a subset of the sequence type, and contains the string type, the vector type, the bool-vector type, and the char-table 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 Strings and Characters, for functions that operate on 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."
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: use 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 next character in the string could be interpreted as 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.
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). If you write all such character codes in octal and the string contains no other characters forcing it to be multibyte, this produces a unibyte string. However, using any hex escape in a string (even for an ASCII character) forces the string to be multibyte.
You can also specify characters in a string by their numeric values in Unicode, using `\u' and `\U' (see Character Type).
See Text Representations, for more information about the two text representations.
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 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
2**7
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 Character Type.
Strings cannot hold characters that have the hyper, super, or alt modifiers.
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 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.)
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 Vectors, for functions that work with vectors.
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 Char-Tables, for special functions to operate on char-tables. Uses of char-tables include:
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.
(make-bool-vector 3 t)
=> #&3"^G"
(make-bool-vector 3 nil)
=> #&3"^@"
These results make sense, because the binary code for `C-g' is 111 and `C-@' is the character with code 0.
If the length is not a multiple of 8, the printed representation shows extra elements, but these extras really make no difference. For instance, in the next example, the two bool-vectors are equal, because only the first 3 bits are used:
(equal #&3"\377" #&3"\007")
=> t
A hash table is a very fast kind of lookup table, somewhat like an alist in that it maps keys to corresponding values, but much faster. Hash tables have no read syntax, and print using hash notation. See Hash Tables, for functions that operate on hash tables.
(make-hash-table)
=> #<hash-table 'eql nil 0/65 0x83af980>
Lisp functions are executable code, just like functions in other
programming languages. In Lisp, unlike most languages, functions are
also Lisp objects. A non-compiled function in Lisp is a lambda
expression: that is, a list whose first element is the symbol
lambda (see 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 can be called as a function even though it has no name; to emphasize this, we also call it an anonymous function (see Anonymous Functions). A named function in Lisp is just a symbol with a valid function in its function cell (see 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 Calling Functions.
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 Macros, for an explanation
of how to write a macro.
Warning: Lisp macros and keyboard macros (see Keyboard Macros) are entirely different things. When we use the word “macro” without qualification, we mean a Lisp macro, not a keyboard macro.
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 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 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.
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 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 `['.
An autoload object is a list whose first element is the symbol
autoload. It is stored as the function definition of a symbol,
where it serves as a placeholder for the real definition. The autoload
object says that the real definition is found in a file of Lisp code
that should be loaded when necessary. It 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 Autoload, for more details.
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.
A buffer is an object that holds text that can be edited (see Buffers). Most buffers hold the contents of a disk file (see 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 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, altering the buffer's contents, 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 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 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 Indirect Buffers.
Buffers have no read syntax. They print in hash notation, showing the buffer name.
(current-buffer)
=> #<buffer objects.texi>
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 Markers, for information on how to test, create, copy, and move markers.
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 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 Windows, for a description of the functions that work on windows.
A frame is a screen area that contains one or more Emacs windows; we also use the term “frame” to refer to the Lisp object that Emacs uses to refer to the screen area.
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 emacs@psilocin.gnu.org 0xdac80>
See Frames, for a description of the functions that work on frames.
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 Window Configurations, for a description of several functions related to window configurations.
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 Frame Configurations, for a description of several functions related to frame configurations.
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 Processes, for information about functions that create, delete, return information about, send input or signals to, and receive output from processes.
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 Minibuffers) or output in the echo area (see The Echo Area).
Streams have no special printed representation or read syntax, and print as whatever primitive type they are.
See Read and Print, for a description of functions related to streams, including parsing and printing functions.
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 Keymaps, for information about creating keymaps, handling prefix keys, local as well as global keymaps, and changing key bindings.
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 Overlays, for how to create and use overlays.
To represent shared or circular structures within a complex of Lisp objects, you can use the reader constructs `#n=' and `#n#'.
Use #n= before an object to label it for later reference;
subsequently, you can use #n# to refer the same object in
another place. Here, n is some integer. For example, here is how
to make a list in which the first element recurs as the third element:
(#1=(a) b #1#)
This differs from ordinary syntax such as this
((a) b (a))
which would result in a list whose first and third elements look alike but are not the same Lisp object. This shows the difference:
(prog1 nil
(setq x '(#1=(a) b #1#)))
(eq (nth 0 x) (nth 2 x))
=> t
(setq x '((a) b (a)))
(eq (nth 0 x) (nth 2 x))
=> nil
You can also use the same syntax to make a circular structure, which appears as an “element” within itself. Here is an example:
#1=(a #1#)
This makes a list whose second element is the list itself. Here's how you can see that it really works:
(prog1 nil
(setq x '#1=(a #1#)))
(eq x (cadr x))
=> t
The Lisp printer can produce this syntax to record circular and shared
structure in a Lisp object, if you bind the variable print-circle
to a non-nil value. See Output Variables.
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.
atomarraypbool-vector-pbufferpbyte-code-function-pcase-table-pchar-or-string-pchar-table-pcommandpconspdisplay-table-pfloatpframe-configuration-pframe-live-pframepfunctionphash-table-pinteger-or-marker-pintegerpkeymappkeywordplistpmarkerpwholenumpnlistpnumberpnumber-or-marker-poverlaypprocesspsequencepstringpsubrpsymbolpsyntax-table-puser-variable-pvectorpwindow-configuration-pwindow-live-pwindowpbooleanpstring-or-null-pThe 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 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.
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,hash-table,subr,compiled-function,marker,overlay,window,buffer,frame,process, orwindow-configuration.(type-of 1) => integer (type-of 'nil) => symbol (type-of '()) ;()isnil. => symbol (type-of '(x)) => cons
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.
This function returns
tif object1 and object2 are the same object,nilotherwise.
eqreturnstif 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 areeq. For other types (e.g., lists, vectors, strings), two arguments with the same contents or elements are not necessarilyeqto each other: they areeqonly if they are the same object, meaning that a change in the contents of one will be reflected by the same change in the contents of the other.(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)) => nilThe
make-symbolfunction 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 noteq. See Creating Symbols.(eq (make-symbol "foo") 'foo) => nil
This function returns
tif object1 and object2 have equal components,nilotherwise. Whereaseqtests if its arguments are the same object,equallooks inside nonidentical arguments to see if their elements or contents are the same. So, if two objects areeq, they areequal, 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)) => nilComparison of strings is case-sensitive, but does not take account of text properties—it compares only the characters in the strings. For technical reasons, a unibyte string and a multibyte string are
equalif and only if they contain the same sequence of character codes and all these codes are either in the range 0 through 127 (ASCII) or 160 through 255 (eight-bit-graphic). (see Text Representations).(equal "asdf" "ASDF") => nilHowever, two distinct buffers are never considered
equal, even if their textual contents are the same.
The test for equality is implemented recursively; for example, given
two cons cells x and y, (equal x y)
returns t if and only if both the expressions below return
t:
(equal (car x) (car y))
(equal (cdr x) (cdr y))
Because of this recursive method, circular lists may therefore cause infinite recursion (leading to an error).
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.
The range of values for an integer depends on the machine. The minimum range is −268435456 to 268435455 (29 bits; i.e., -2**28 to 2**28 - 1), but some machines may provide a wider range. Many examples in this chapter assume an integer has 29 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. 536870913 ; Also the integer 1, due to overflow. 0 ; The integer 0. -0 ; The integer 0.
The syntax for integers in bases other than 10 uses `#' followed by a letter that specifies the radix: `b' for binary, `o' for octal, `x' for hex, or `radixr' to specify radix radix. Case is not significant for the letter that specifies the radix. Thus, `#binteger' reads integer in binary, and `#radixrinteger' reads integer in radix radix. Allowed values of radix run from 2 to 36. For example:
#b101100 => 44
#o54 => 44
#x2c => 44
#24r1k => 44
To understand how various functions work on integers, especially the bitwise operators (see Bitwise Operations), it is often helpful to view the numbers in their binary form.
In 29-bit binary, the decimal integer 5 looks like this:
0 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:
1 1111 1111 1111 1111 1111 1111 1111
−1 is represented as 29 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:
1 1111 1111 1111 1111 1111 1111 1011
In this implementation, the largest 29-bit binary integer value is 268,435,455 in decimal. In binary, it looks like this:
0 1111 1111 1111 1111 1111 1111 1111
Since the arithmetic functions do not check whether integers go outside their range, when you add 1 to 268,435,455, the value is the negative integer −268,435,456:
(+ 1 268435455)
=> -268435456
=> 1 0000 0000 0000 0000 0000 0000 0000
Many of the functions described in this chapter accept markers for arguments in place of numbers. (See 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.
The value of this variable is the largest integer that Emacs Lisp can handle.
The value of this variable is the smallest integer that Emacs Lisp can handle. It is negative.
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, (/ 0.0 0.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 (but it does report the sign, if you
print it). Here are the read syntaxes for these special floating
point values:
To test whether a floating point value is a NaN, compare it with
itself using =. That returns nil for a NaN, and
t for any other floating point value.
The value -0.0 is distinguishable from ordinary zero in
IEEE floating point, but Emacs Lisp 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):
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
The functions in this section test for numbers, or for a specific
type of number. The functions integerp and floatp can
take any type of Lisp object as argument (they 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 Predicates on Markers.
This predicate tests whether its argument is a floating point number and returns
tif so,nilotherwise.
floatpdoes not exist in Emacs versions 18 and earlier.
This predicate tests whether its argument is an integer, and returns
tif so,nilotherwise.
This predicate tests whether its argument is a number (either integer or floating point), and returns
tif so,nilotherwise.
The
wholenumppredicate (whose name comes from the phrase “whole-number-p”) tests to see whether its argument is a nonnegative integer, and returnstif so,nilotherwise. 0 is considered non-negative.
This predicate tests whether its argument is zero, and returns
tif so,nilotherwise. The argument must be a number.
(zerop x)is equivalent to(= x 0).
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.
See Equality Predicates.
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.
This function tests whether its arguments are numerically equal, and returns
tif so,nilotherwise.
This function acts like
eqexcept when both arguments are numbers. It compares numbers by type and numeric value, so that(eql 1.0 1)returnsnil, but(eql 1.0 1.0)and(eql 1 1)both returnt.
This function tests whether its arguments are numerically equal, and returns
tif they are not, andnilif they are.
This function tests whether its first argument is strictly less than its second argument. It returns
tif so,nilotherwise.
This function tests whether its first argument is less than or equal to its second argument. It returns
tif so,nilotherwise.
This function tests whether its first argument is strictly greater than its second argument. It returns
tif so,nilotherwise.
This function tests whether its first argument is greater than or equal to its second argument. It returns
tif so,nilotherwise.
This function returns the largest of its arguments. If any of the arguments is floating-point, the value is returned as floating point, even if it was given as an integer.
(max 20) => 20 (max 1 2.5) => 2.5 (max 1 3 2.5) => 3.0
This function returns the smallest of its arguments. If any of the arguments is floating-point, the value is returned as floating point, even if it was given as an integer.
(min -4 1) => -4
To convert an integer to floating point, use the function float.
This returns number converted to floating point. If number is already a floating point number,
floatreturns it unchanged.
There are four functions to convert floating point numbers to integers;
they differ in how they round. All accept an argument number
and an optional argument divisor. Both arguments may be
integers or floating point numbers. divisor may also be
nil. If divisor is nil or omitted, these
functions convert number to an integer, or return it unchanged
if it already is an integer. If divisor is non-nil, they
divide number by divisor and convert the result to an
integer. An arith-error results if divisor is 0.
This returns number, converted to an integer by rounding towards zero.
(truncate 1.2) => 1 (truncate 1.7) => 1 (truncate -1.2) => -1 (truncate -1.7) => -1
This returns number, converted to an integer by rounding downward (towards negative infinity).
If divisor is specified, this uses the kind of division operation that corresponds to
mod, rounding downward.(floor 1.2) => 1 (floor 1.7) => 1 (floor -1.2) => -2 (floor -1.7) => -2 (floor 5.99 3) => 1
This returns number, converted to an integer by rounding upward (towards positive infinity).
(ceiling 1.2) => 2 (ceiling 1.7) => 2 (ceiling -1.2) => -1 (ceiling -1.7) => -1
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.
(round 1.2) => 1 (round 1.7) => 2 (round -1.2) => -1 (round -1.7) => -2
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+ 268435455) may evaluate to
−268435456, depending on your hardware.
This function returns number-or-marker plus 1. For example,
(setq foo 4) => 4 (1+ foo) => 5This function is not analogous to the C operator
++—it does not increment a variable. It just computes a sum. Thus, if we continue,foo => 4If you want to increment the variable, you must use
setq, like this:(setq foo (1+ foo)) => 5
This function adds its arguments together. When given no arguments,
+returns 0.(+) => 0 (+ 1) => 1 (+ 1 2 3 4) => 10
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
This function multiplies its arguments together, and returns the product. When given no arguments,
*returns 1.(*) => 1 (* 1) => 1 (* 1 2 3 4) => 24
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-errorerror is signaled. (See Errors.) Floating point division by zero returns either infinity or a NaN if your machine supports IEEE floating point; otherwise, it signals anarith-errorerror.(/ 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 (could in theory be −3 on some machines)
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-errorresults if divisor is 0.(% 9 4) => 1 (% -9 4) => -1 (% 9 -4) => 1 (% -9 -4) => -1For any two integers dividend and divisor,
(+ (% dividend divisor) (* (/ dividend divisor) divisor))always equals dividend.
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
%,modreturns 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-errorresults 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) => .5For 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 Numeric Conversions.
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.
This function rounds float to the next lower integral value, and returns that value as a floating point number.
This function rounds float to the next higher integral value, and returns that value as a floating point number.
This function rounds float towards zero to an integral value, and returns that value as a floating point number.
This function rounds float to the nearest integral value, and returns that value as a floating point number.
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.
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,lshshifts zeros into the leftmost (most-significant) bit, producing a positive result even if integer1 is negative. Contrast this withash, 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 => 00001110As 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 => 00001100On 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 => 00000010As 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 268,435,455 produces −2 on a 29-bit machine:(lsh 268435455 1) ; left shift => -2In binary, in the 29-bit implementation, the argument looks like this:
;; Decimal 268,435,455 0 1111 1111 1111 1111 1111 1111 1111which becomes the following when left shifted:
;; Decimal −2 1 1111 1111 1111 1111 1111 1111 1110
ash(arithmetic shift) shifts the bits in integer1 to the left count places, or to the right if count is negative.
ashgives the same results aslshexcept when integer1 and count are both negative. In that case,ashputs ones in the empty bit positions on the left, whilelshputs 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. 1 1111 1111 1111 1111 1111 1111 1010 => 1 1111 1111 1111 1111 1111 1111 1101In contrast, shifting the pattern of bits one place to the right with
lshlooks like this:(lsh -6 -1) => 268435453 ;; Decimal −6 becomes decimal 268,435,453. 1 1111 1111 1111 1111 1111 1111 1010 => 0 1111 1111 1111 1111 1111 1111 1101Here are other examples:
; 29-bit binary values (lsh 5 2) ; 5 = 0 0000 0000 0000 0000 0000 0000 0101 => 20 ; = 0 0000 0000 0000 0000 0000 0001 0100 (ash 5 2) => 20 (lsh -5 2) ; -5 = 1 1111 1111 1111 1111 1111 1111 1011 => -20 ; = 1 1111 1111 1111 1111 1111 1110 1100 (ash -5 2) => -20 (lsh 5 -2) ; 5 = 0 0000 0000 0000 0000 0000 0000 0101 => 1 ; = 0 0000 0000 0000 0000 0000 0000 0001 (ash 5 -2) => 1 (lsh -5 -2) ; -5 = 1 1111 1111 1111 1111 1111 1111 1011 => 134217726 ; = 0 0111 1111 1111 1111 1111 1111 1110 (ash -5 -2) ; -5 = 1 1111 1111 1111 1111 1111 1111 1011 => -2 ; = 1 1111 1111 1111 1111 1111 1111 1110
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) => 12If
logandis not passed any argument, it returns a value of −1. This number is an identity element forlogandbecause its binary representation consists entirely of ones. Iflogandis passed just one argument, it returns that argument.; 29-bit binary values (logand 14 13) ; 14 = 0 0000 0000 0000 0000 0000 0000 1110 ; 13 = 0 0000 0000 0000 0000 0000 0000 1101 => 12 ; 12 = 0 0000 0000 0000 0000 0000 0000 1100 (logand 14 13 4) ; 14 = 0 0000 0000 0000 0000 0000 0000 1110 ; 13 = 0 0000 0000 0000 0000 0000 0000 1101 ; 4 = 0 0000 0000 0000 0000 0000 0000 0100 => 4 ; 4 = 0 0000 0000 0000 0000 0000 0000 0100 (logand) => -1 ; -1 = 1 1111 1111 1111 1111 1111 1111 1111
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
logioris passed just one argument, it returns that argument.; 29-bit binary values (logior 12 5) ; 12 = 0 0000 0000 0000 0000 0000 0000 1100 ; 5 = 0 0000 0000 0000 0000 0000 0000 0101 => 13 ; 13 = 0 0000 0000 0000 0000 0000 0000 1101 (logior 12 5 7) ; 12 = 0 0000 0000 0000 0000 0000 0000 1100 ; 5 = 0 0000 0000 0000 0000 0000 0000 0101 ; 7 = 0 0000 0000 0000 0000 0000 0000 0111 => 15 ; 15 = 0 0000 0000 0000 0000 0000 0000 1111
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
logxoris passed just one argument, it returns that argument.; 29-bit binary values (logxor 12 5) ; 12 = 0 0000 0000 0000 0000 0000 0000 1100 ; 5 = 0 0000 0000 0000 0000 0000 0000 0101 => 9 ; 9 = 0 0000 0000 0000 0000 0000 0000 1001 (logxor 12 5 7) ; 12 = 0 0000 0000 0000 0000 0000 0000 1100 ; 5 = 0 0000 0000 0000 0000 0000 0000 0101 ; 7 = 0 0000 0000 0000 0000 0000 0000 0111 => 14 ; 14 = 0 0000 0000 0000 0000 0000 0000 1110
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 = 0 0000 0000 0000 0000 0000 0000 0101 ;; becomes ;; -6 = 1 1111 1111 1111 1111 1111 1111 1010
These mathematical functions allow integers as well as floating point numbers as arguments.
These are the ordinary trigonometric functions, with argument measured in radians.
The value of
(asinarg)is a number between −pi/2 and pi/2 (inclusive) whose sine is arg; if, however, arg is out of range (outside [−1, 1]), it signals adomain-errorerror.
The value of
(acosarg)is a number between 0 and pi (inclusive) whose cosine is arg; if, however, arg is out of range (outside [−1, 1]), it signals adomain-errorerror.
The value of
(atany)is a number between −pi/2 and pi/2 (exclusive) whose tangent is y. If the optional second argument x is given, the value of(atan y x)is the angle in radians between the vector[x,y]and theXaxis.
This is the exponential function; it returns e to the power arg. e is a fundamental mathematical constant also called the base of natural logarithms.
This function returns the logarithm of arg, with base base. If you don't specify base, the base e is used. If arg is negative, it signals a
domain-errorerror.
This function returns the logarithm of arg, with base 10. If arg is negative, it signals a
domain-errorerror.(log10x)==(logx10), at least approximately.
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, overflow causes truncation, so watch out.
This returns the square root of arg. If arg is negative, it signals a
domain-errorerror.
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 random numbers that don't always come out the same, execute
(random t). This chooses a new seed based on the current time of
day and on Emacs's process ID number.
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.
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 Strings of Events, for special considerations for strings of keyboard character events.
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 Sequences Arrays Vectors.) For example, you can access or
change individual characters in a string using the functions aref
and aset (see Array Functions).
There are two text representations for non-ASCII characters in Emacs strings (and in buffers): unibyte and multibyte (see Text Representations). An ASCII character always occupies one byte in a string; in fact, when a string is all ASCII, there is no real difference between the unibyte and multibyte representations. 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 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 Character Type, for more information about the 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 with string-match
(see Regexp Search). The functions match-string
(see Simple Match Data) and replace-match (see Replacing Match) are useful for decomposing and modifying strings after
matching regular expressions against them.
Like a buffer, a string can contain text properties for the characters in it, as well as the characters themselves. See 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 Text, for information about functions that display strings or copy them into buffers. See Character Type, and String Type, for information about the syntax of characters and strings. See Non-ASCII Characters, for functions to convert between text representations and to encode and decode character codes.
For more information about general sequence and array predicates, see Sequences Arrays Vectors, and Arrays.
This function returns
tif object is a string or nil,nilotherwise.
This function returns
tif object is a string or a character (i.e., an integer),nilotherwise.
The following functions create strings, either from scratch, or by putting strings together, or by taking them apart.
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 String Conversion),make-vector(see Vectors), andmake-list(see Building Lists).
This returns a string containing the characters characters.
(string ?a ?b ?c) => "abc"
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
nilis used for end, 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(substringstring0)returns a copy of all of string.(substring "abcdefg" 0) => "abcdefg"But we recommend
copy-sequencefor this purpose (see Sequence Functions).If the characters copied from string have text properties, the properties are copied into the new string also. See Text Properties.
substringalso accepts a vector for the first argument. For example:(substring [a b (c) "d"] 1 3) => [b (c)]A
wrong-type-argumenterror is signaled if start is not an integer or if end is neither an integer nornil. Anargs-out-of-rangeerror 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 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.
This works like
substringbut discards all text properties from the value. Also, start may be omitted ornil, which is equivalent to 0. Thus,(substring-no-propertiesstring)returns a copy of string, with all text properties removed.
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
concatreceives no arguments, it returns an empty string.(concat "abc" "-def") => "abc-def" (concat "abc" (list 120 121) [122]) => "abcxyz" ;;nilis an empty sequence. (concat "abc" nil "-def") => "abc-def" (concat "The " "quick brown " "fox.") => "The quick brown fox." (concat) => ""The
concatfunction always constructs a new string that is noteqto any existing string.In Emacs versions before 21, when an argument was an integer (not a sequence of integers), it was converted to a string of digits making up the decimal printed representation of the integer. This obsolete usage no longer works. The proper way to convert an integer to its decimal printed form is with
format(see Formatting Strings) ornumber-to-string(see String Conversion).For information about other concatenation functions, see the description of
mapconcatin Mapping Functions,vconcatin Vector Functions, andappendin Building Lists.
This function splits string into substrings at 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 returned by
split-string.If omit-nulls is
nil, the result contains null strings whenever there are two consecutive matches for separators, or a match is adjacent to the beginning or end of string. If omit-nulls ist, these null strings are omitted from the result.If separators is
nil(or omitted), the default is the value ofsplit-string-default-separators.As a special case, when separators is
nil(or omitted), null strings are always omitted from the result. Thus:(split-string " two words ") => ("two" "words")The result is not
("" "two" "words" ""), which would rarely be useful. If you need such a result, use an explicit value for separators:(split-string " two words " split-string-default-separators) => ("" "two" "words" "")More examples:
(split-string "Soup is good food" "o") => ("S" "up is g" "" "d f" "" "d") (split-string "Soup is good food" "o" t) => ("S" "up is g" "d f" "d") (split-string "Soup is good food" "o+") => ("S" "up is g" "d f" "d")Empty matches do count, except that
split-stringwill not look for a final empty match when it already reached the end of the string using a non-empty match or when string is empty:(split-string "aooob" "o*") => ("" "a" "" "b" "") (split-string "ooaboo" "o*") => ("" "" "a" "b" "") (split-string "" "") => ("")However, when separators can match the empty string, omit-nulls is usually
t, so that the subtleties in the three previous examples are rarely relevant:(split-string "Soup is good food" "o*" t) => ("S" "u" "p" " " "i" "s" " " "g" "d" " " "f" "d") (split-string "Nice doggy!" "" t) => ("N" "i" "c" "e" " " "d" "o" "g" "g" "y" "!") (split-string "" "" t) => nilSomewhat odd, but predictable, behavior can occur for certain “non-greedy” values of separators that can prefer empty matches over non-empty matches. Again, such values rarely occur in practice:
(split-string "ooo" "o*" t) => nil (split-string "ooo" "\\|o+" t) => ("o" "o" "o")
The default value of separators for
split-string. Its usual value is"[ \f\t\n\r\v]+".
The most basic way to alter the contents of an existing string is with
aset (see Array Functions). (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:
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, or if any new character requires a different number of bytes from the character currently present at that point in string.
To clear out a string that contained a password, use
clear-string:
This makes string a unibyte string and clears its contents to zeros. It may also change string's length.
This function returns
tif the arguments represent the same character,nilotherwise. This function ignores differences in case ifcase-fold-searchis non-nil.(char-equal ?x ?x) => t (let ((case-fold-search nil)) (char-equal ?x ?X)) => nil
This function returns
tif the characters of the two strings match exactly. Symbols are also allowed as arguments, in which case their print names are used. Case is always significant, regardless ofcase-fold-search.(string= "abc" "abc") => t (string= "abc" "ABC") => nil (string= "ab" "ABC") => nilThe function
string=ignores the text properties of the two strings. Whenequal(see Equality Predicates) compares two strings, it usesstring=.For technical reasons, a unibyte and a multibyte string are
equalif and only if they contain the same sequence of character codes and all these codes are either in the range 0 through 127 (ASCII) or 160 through 255 (eight-bit-graphic). However, when a unibyte string gets converted to a multibyte string, all characters with codes in the range 160 through 255 get converted to characters with higher codes, whereas ASCII characters remain unchanged. Thus, a unibyte string and its conversion to multibyte are onlyequalif the string is all ASCII. Character codes 160 through 255 are not entirely proper in multibyte text, even though they can occur. As a consequence, the situation where a unibyte and a multibyte string areequalwithout both being all ASCII is a technical oddity that very few Emacs Lisp programmers ever get confronted with. See Text Representations.
This function compares two strings a character at a time. It scans both the strings at the same time to find the first pair of corresponding characters that do not match. If the lesser character of these 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 returnsnil. If the two strings match entirely, the value isnil.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 Text Representations).
(string< "abc" "abd") => t (string< "abd" "abc") => nil (string< "123" "abc") => tWhen 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 isnil. 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< "" "") => nilSymbols are also allowed as arguments, in which case their print names are used.
This function compares the specified part of string1 with the specified part of string2. The specified part of string1 runs from index start1 up to index end1 (
nilmeans the end of the string). The specified part of string2 runs from index start2 up to index end2 (nilmeans the end of the string).The strings are both converted to multibyte for the comparison (see Text Representations) so that a unibyte string and its conversion to multibyte are always regarded as equal. 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.
This function works like
assoc, except that key must be a string or symbol, and comparison is done usingcompare-strings. Symbols are converted to strings before testing. If case-fold is non-nil, it ignores case differences. Unlikeassoc, this function can also match elements of the alist that are strings or symbols rather than conses. In particular, alist can be a list of strings or symbols rather than an actual alist. See Association Lists.
See also the compare-buffer-substrings function in
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
Regexp Search.
This section describes functions for conversions between characters,
strings and integers. format (see Formatting Strings)
and prin1-to-string
(see Output Functions) can also convert Lisp objects into strings.
read-from-string (see 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 Converting Representations).
See Documentation, for functions that produce textual descriptions
of text characters and general input events
(single-key-description and text-char-description). These
are used primarily for making help messages.
This function returns a new string containing one character, character. This function is semi-obsolete because the function
stringis more general. See Creating Strings.
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") => 0This function may be eliminated in the future if it does not seem useful enough to retain.
This function returns a string consisting of the printed base-ten representation of number, which may be an integer or a floating point number. The returned value starts with a minus 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-stringis a semi-obsolete alias for this function.See also the function
formatin Formatting Strings.
This function returns the numeric value of the characters in string. If base is non-
nil, it must be an integer between 2 and 16 (inclusive), and integers are converted in that base. If base isnil, then base ten is used. Floating point conversion only works in base ten; we have not implemented other radices for floating point numbers, because that would be much more work and does not seem useful. If string looks like an integer but its value is too large to fit into a Lisp integer,string-to-numberreturns a floating point result.The parsing skips spaces and tabs at the beginning of string, then reads as much of string as it can interpret as a number in the given base. (On some systems it ignores other whitespace at the beginning, not just spaces and tabs.) If the first character after the ignored whitespace is neither a digit in the given base, nor a plus or minus sign, nor the leading dot of a floating point number, 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-number "1e5") => 100000.0
Here are some other functions that can convert to or from a string:
concatconcat can convert a vector or a list into a string.
See Creating Strings.
vconcatvconcat can convert a string into a vector. See Vector Functions.
appendappend can convert a string into a list. See Building Lists.
Formatting means constructing a string by substitution of computed values at various places in a constant string. This constant 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.
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.
The characters in string, other than the format specifications, are copied directly into the output, including their text properties, if any.
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."
Since format interprets `%' characters as format
specifications, you should never pass an arbitrary string as
the first argument. This is particularly true when the string is
generated by some Lisp code. Unless the string is known to
never include any `%' characters, pass "%s", described
below, as the first argument, and the string as the second, like this:
(format "%s" arbitrary-string)
If string contains more than one format specification, the format specifications correspond to 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 an error. 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:
princ, not
prin1—see Output Functions). Thus, strings are represented
by their contents alone, with no `"' characters, and symbols appear
without `\' characters.
If the object is a string, its text properties are
copied into the output. The text properties of the `%s' itself
are also copied, but those of the object take priority.
prin1—see Output Functions). Thus, strings are enclosed in `"' characters, and
`\' characters appear where necessary before special characters.
(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."
A specification can have a width, which is a signed decimal
number between the `%' and the specification character. If the
printed representation of the object contains fewer characters than
this width, format extends it with padding. The padding goes
on the left if the width is positive (or starts with zero) and on the
right if the width is negative. The padding character is normally a
space, but it's `0' if the width starts with a zero.
Some of these conventions are ignored for specification characters for which they do not make sense. That is, `%s', `%S' and `%c' accept a width starting with 0, but still pad with spaces on the left. Also, `%%' accepts a width, but ignores it. 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"
If the width is too small, format does not truncate the
object's printed representation. Thus, you can use a width 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, it needs 4 blank spaces as 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."
All the specification characters allow an optional precision before the character (after the width, if present). The precision is a decimal-point `.' followed by a digit-string. For the floating-point specifications (`%e', `%f', `%g'), the precision specifies how many decimal places to show; if zero, the decimal-point itself is also omitted. For `%s' and `%S', the precision truncates the string to the given width, so `%.3s' shows only the first three characters of the representation for object. Precision has no effect for other specification characters.
Immediately after the `%' and before the optional width and precision, you can put certain “flag” characters.
`+' as a flag inserts a plus sign before a positive number, so that it always has a sign. A space character as flag inserts a space before a positive number. (Otherwise, positive numbers start with the first digit.) Either of these two flags ensures that positive numbers and negative numbers use the same number of columns. These flags are ignored except for `%d', `%e', `%f', `%g', and if both flags are used, the `+' takes precedence.
The flag `#' specifies an “alternate form” which depends on the format in use. For `%o' it ensures that the result begins with a `0'. For `%x' and `%X', it prefixes the result with `0x' or `0X'. For `%e', `%f', and `%g', the `#' flag means include a decimal point even if the precision is zero.
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 Case Tables).
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.
This function converts a character or a string to lower case.
When the argument to
downcaseis 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 todowncaseis a character,downcasereturns 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
This function converts a character or a string to upper case.
When the argument to
upcaseis 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
upcaseis a character,upcasereturns 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 returned equals the original character.(upcase "The cat in the hat") => "THE CAT IN THE HAT" (upcase ?x) => 88
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 Syntax Class Table).
When the argument to
capitalizeis a character,capitalizehas the same result asupcase.(capitalize "The cat in the hat") => "The Cat In The Hat" (capitalize "THE 77TH-HATTED CAT") => "The 77th-Hatted Cat" (capitalize ?x) => 88
If string-or-char is a string, this function capitalizes the initials of the words in string-or-char, without altering any letters other than the initials. It returns a new string whose contents are a copy of string-or-char, in which each word has had its initial letter 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 Syntax Class Table).
When the argument to
upcase-initialsis a character,upcase-initialshas the same result asupcase.(upcase-initials "The CAT in the hAt") => "The CAT In The HAt"
See Text Comparison, for functions that compare strings; some of them ignore case differences, or can optionally ignore case differences.
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 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 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:
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 cyclically 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:
This function makes table the standard case table, so that it will be used in any buffers created subsequently.
The
with-case-tablemacro saves the current case table, makes table the current case table, evaluates the body forms, and finally restores the case table. The return value is the value of the last form in body. The case table is restored even in case of an abnormal exit viathrowor error (see Nonlocal Exits).
Some language environments may modify the case conversions of
ASCII characters; for example, in the Turkish language
environment, the ASCII character `I' is downcased into
a Turkish “dotless i”. This can interfere with code that requires
ordinary ASCII case conversion, such as implementations of
ASCII-based network protocols. In that case, use the
with-case-table macro with the variable ascii-case-table,
which stores the unmodified case table for the ASCII
character set.
The case table for the ASCII character set. This should not be modified by any language environment settings.
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 Syntax Tables. Normally you would use these functions to change the standard case table.
This function specifies a pair of corresponding letters, one upper case and one lower case.
This function makes characters l and r a matching pair of case-invariant delimiters.
This function makes char case-invariant, with syntax syntax.
This command displays a description of the contents of the current buffer's case table.
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 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. That is, it has two slots, and each slot holds, or refers to, some Lisp object. One slot is known as the car, and the other is known as the cdr. (These names are traditional; see Cons Cell Type.) cdr is pronounced “could-er.”
We say that “the car of this cons cell is” whatever object its car slot currently holds, and likewise for the cdr.
A list is a series of cons cells “chained together,” so that each
cell refers to the next one. There is one cons cell for each element of
the list. By convention, the cars of the cons cells hold the
elements of the list, and the cdrs are used to chain the list: the
cdr slot of each cons cell refers to 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.
Since nil is the conventional value to put in the cdr of
the last cons cell in the list, we call that case a true list.
In Lisp, we consider the symbol nil 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). Therefore, the cdr of a true list is always a
true list.
If the cdr of a list's last cons cell is some other value,
neither nil nor another cons cell, we call the structure a
dotted list, since its printed representation would use
`.'. There is one other possibility: some cons cell's cdr
could point to one of the previous cons cells in the list. We call
that structure a circular list.
For some purposes, it does not matter whether a list is true, circular or dotted. If the program doesn't look far enough down the list to see the cdr of the final cons cell, it won't care. However, some functions that operate on lists demand true lists and signal errors if given a dotted list. Most functions that try to find the end of a list enter infinite loops if given a circular list.
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 cdr of any nonempty true list l is a list containing all the elements of l except the first.
See Cons Cell Type, for the read and print syntax of cons cells and lists, and for “box and arrow” illustrations of lists.
The following predicates test whether a Lisp object is an atom,
whether it 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.)
This function returns
tif object is a cons cell,nilotherwise.nilis not a cons cell, although it is a list.
This function returns
tif object is an atom,nilotherwise. All objects except cons cells are atoms. The symbolnilis an atom and is also a list; it is the only Lisp object that is both.(atom object) == (not (consp object))
This function returns
tif object is a cons cell ornil. Otherwise, it returnsnil.(listp '(1)) => t (listp '()) => t
This function is the opposite of
listp: it returnstif object is not a list. Otherwise, it returnsnil.(listp object) == (not (nlistp object))
This function returns
tif object isnil, and returnsnilotherwise. This function is identical tonot, but as a matter of clarity we usenullwhen object is considered a list andnotwhen it is considered a truth value (seenotin Combining Conditions).(null '(1)) => nil (null '()) => t
This function returns the value referred to by the first slot 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, thencaris defined to returnnil; therefore, any list is a valid argument forcar. An error is signaled if the argument is not a cons cell ornil.(car '(a b c)) => a (car '()) => nil
This function returns the value referred to by the second slot 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, thencdris defined to returnnil; therefore, any list is a valid argument forcdr. An error is signaled if the argument is not a cons cell ornil.(cdr '(a b c)) => (b c) (cdr '()) => nil
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,
nilotherwise. This is in contrast tocar, which signals an error if object is not a list.(car-safe object) == (let ((x object)) (if (consp x) (car x) nil))
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,
nilotherwise. This is in contrast tocdr, which signals an error if object is not a list.(cdr-safe object) == (let ((x object)) (if (consp x) (cdr x) nil))
This macro is a way of examining the car of a list, and taking it off the list, all at once.
It operates on the list which is stored in the symbol listname. It removes this element from the list by setting listname to the cdr of its old value—but it also returns the car of that list, which is the element being removed.
x => (a b c) (pop x) => a x => (b c)
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,
nthreturns 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
eltis similar, but applies to any kind of sequence. For historical reasons, it takes its arguments in the opposite order. See Sequence Functions.
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,
nthcdrreturns all of list. If the length of list is n or less,nthcdrreturnsnil.(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)
This function returns the last link of list. The
carof this link is the list's last element. If list is null,nilis returned. If n is non-nil, the nth-to-last link is returned instead, or the whole of list if n is bigger than list's length.
This function returns the length of list, with no risk of either an error or an infinite loop. It generally returns the number of distinct cons cells in the list. However, for circular lists, the value is just an upper bound; it is often too large.
If list is not
nilor a cons cell,safe-lengthreturns 0.
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 Sequence Functions.
This function returns the list x with the last element, or the last n elements, removed. If n is greater than zero it makes a copy of the list so as not to damage the original list. In general,
(append (butlastx n) (lastx n))will return a list equal to x.
This is a version of
butlastthat works by destructively modifying thecdrof the appropriate element, rather than making a copy of the list.
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.
This function is the most basic function for building 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)
consis often used to add a single element to the front of a list. This is called consing the element onto the list. 1 For example:(setq list (cons newelt list))Note that there is no conflict between the variable named
listused in this example and the function namedlistdescribed below; any symbol can serve both purposes.
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
This function creates a list of length elements, in which each element is object. Compare
make-listwithmake-string(see Creating Strings).(make-list 3 'pigs) => (pigs pigs pigs) (make-list 0 'pigs) => nil (setq l (make-list 3 '(a b)) => ((a b) (a b) (a b)) (eq (car l) (cadr l)) => t
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
nconcin Rearrangement, for a way to join lists with no copying.)More generally, the final argument to
appendmay 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 notnilas required in a true list.In Emacs 20 and before, the
appendfunction also allowed integers as (non last) arguments. It converted them to strings of digits, making up the decimal print representation of the integer, and then used the strings instead of the original integers. This obsolete usage no longer works. The proper way to convert an integer to a decimal number in this way is withformat(see Formatting Strings) ornumber-to-string(see String Conversion).
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 Sequences Arrays 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 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.
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)
This function returns a copy of the tree
tree. If tree is a cons cell, this makes a new cons cell with the same car and cdr, then recursively copies the car and cdr in the same way.Normally, when tree is anything other than a cons cell,
copy-treesimply returns tree. However, if vecp is non-nil, it copies vectors too (and operates recursively on their elements).
This returns a list of numbers starting with from and incrementing by separation, and ending at or just before to. separation can be positive or negative and defaults to 1. If to is
nilor numerically equal to from, the value is the one-element list(from). If to is less than from with a positive separation, or greater than from with a negative separation, the value isnilbecause those arguments specify an empty sequence.If separation is 0 and to is neither
nilnor numerically equal to from,number-sequencesignals an error, since those arguments specify an infinite sequence.All arguments can be integers or floating point numbers. However, floating point arguments can be tricky, because floating point arithmetic is inexact. For instance, depending on the machine, it may quite well happen that
(number-sequence 0.4 0.6 0.2)returns the one element list(0.4), whereas(number-sequence 0.4 0.8 0.2)returns a list with three elements. The nth element of the list is computed by the exact formula(+from(*n separation)). Thus, if one wants to make sure that to is included in the list, one can pass an expression of this exact type for to. Alternatively, one can replace to with a slightly larger value (or a slightly more negative value if separation is negative).Some examples:
(number-sequence 4 9) => (4 5 6 7 8 9) (number-sequence 9 4 -1) => (9 8 7 6 5 4) (number-sequence 9 4 -2) => (9 7 5) (number-sequence 8) => (8) (number-sequence 8 5) => nil (number-sequence 5 8 -1) => nil (number-sequence 1.5 6 2) => (1.5 3.5 5.5)
These functions, and one macro, provide convenient ways to modify a list which is stored in a variable.
This macro provides an alternative way to write
(setqlistname(consnewelt listname)).(setq l '(a b)) => (a b) (push 'c l) => (c a b) l => (c a b)
Two functions modify lists that are the values of variables.
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.
add-to-listuses compare-fn to compare element against existing list members; if compare-fn isnil, it usesequal.Normally, if element is added, it is added to the front of symbol, but if the optional argument append is non-
nil, it is added at the end.The argument symbol is not implicitly quoted;
add-to-listis an ordinary function, likesetand unlikesetq. 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)))
This function sets the variable symbol by inserting element into the old value, which must be a list, at the position specified by order. If element is already a member of the list, its position in the list is adjusted according to order. Membership is tested using
eq. This function returns the resulting list, whether updated or not.The order is typically a number (integer or float), and the elements of the list are sorted in non-decreasing numerical order.
order may also be omitted or
nil. Then the numeric order of element stays unchanged if it already has one; otherwise, element has no numeric order. Elements without a numeric list order are placed at the end of the list, in no particular order.Any other value for order removes the numeric order of element if it already has one; otherwise, it is equivalent to
nil.The argument symbol is not implicitly quoted;
add-to-ordered-listis an ordinary function, likesetand unlikesetq. Quote the argument yourself if that is what you want.The ordering information is stored in a hash table on symbol's
list-orderproperty.
Here's a scenario showing how to use add-to-ordered-list:
(setq foo '())
=> nil
(add-to-ordered-list 'foo 'a 1) ;; Add a.
=> (a)
(add-to-ordered-list 'foo 'c 3) ;; Add c.
=> (a c)
(add-to-ordered-list 'foo 'b 2) ;; Add b.
=> (a b c)
(add-to-ordered-list 'foo 'b 4) ;; Move b.
=> (a c b)
(add-to-ordered-list 'foo 'd) ;; Append d.
=> (a c b d)
(add-to-ordered-list 'foo 'e) ;; Add e.
=> (a c b e d)
foo ;; foo was changed.
=> (a c b e d)
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 functionsrplacaandrplacdto alter list structure; they change structure the same way assetcarandsetcdr, but the Common Lisp functions return the cons cell whilesetcarandsetcdrreturn the new car or cdr.
setcarChanging 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.
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 refer 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----
| | |
--------------
The lowest-level primitive for modifying a cdr is setcdr:
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 refer 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------
| | |
---------------
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.
See delq, in Sets And Lists, for another function
that modifies cons cells.
This function returns a list containing all the elements of lists. Unlike
append(see Building 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
nconcis 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)) ;footo 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)))
This function reverses the order of the elements of list. Unlike
reverse,nreversealters 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 '(a b c)) => (a b c) x => (a b c) (nreverse x) => (c b a) ;; The cons cell that was first is now last. x => (a)To avoid confusion, we usually store the result of
nreverseback in the same variable which held the original list:(setq x (nreverse x))Here is the
nreverseof 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 | | | | | | | | | | | | | | ------------- | --------- | - | -------- | - | | | | ------------- ------------
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 non-
nilif the first element is “less than” the second, ornilif 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 ofsortis unpredictable.The destructive aspect of
sortis 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 withcopy-sequenceand then sort.Sorting does not change the cars of the cons cells in list; the cons cell that originally contained the element
ain list still hasain 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
numsno 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 ofsortand use that. Most often we store the result back into the variable that held the original list:(setq nums (sort nums '<))See Sorting, for more functions that perform sorting. See
documentationin Accessing Documentation, for a useful example ofsort.
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). You can remove
equal duplicates using delete-dups. Other useful
functions for sets include memq and delq, and their
equal versions, member and delete.
Common Lisp note: Common Lisp has functionsunion(which avoids duplicate elements) andintersectionfor set operations, but GNU Emacs Lisp does not have them. You can write them in Lisp if you wish.
This function tests to see whether object is a member of list. If it is,
memqreturns a list starting with the first occurrence of object. Otherwise, it returnsnil. The letter `q' inmemqsays that it useseqto 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 noteq. => nil
This function destructively removes all elements
eqto object from list. The letter `q' indelqsays that it useseqto compare object against the elements of the list, likememqandremq.
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 Setcdr).
(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))
If you want to delete elements that are equal to a given value,
use delete (see below).
This function returns a copy of list, with all elements removed which are
eqto object. The letter `q' inremqsays that it useseqto compare object against the elements oflist.(setq sample-list '(a b c a b c)) => (a b c a b c) (remq 'a sample-list) => (b c b c) sample-list => (a b c a b c)
The function
memqltests to see whether object is a member of list, comparing members with object usingeql, so floating point elements are compared by value. If object is a member,memqlreturns a list starting with its first occurrence in list. Otherwise, it returnsnil.Compare this with
memq:(memql 1.2 '(1.1 1.2 1.3)) ;1.2and1.2areeql. => (1.2 1.3) (memq 1.2 '(1.1 1.2 1.3)) ;1.2and1.2are noteq. => nil
The following three functions are like memq, delq and
remq, but use equal rather than eq to compare
elements. See Equality Predicates.
The function
membertests to see whether object is a member of list, comparing members with object usingequal. If object is a member,memberreturns a list starting with its first occurrence in list. Otherwise, it returnsnil.Compare this with
memq:(member '(2) '((1) (2))) ;(2)and(2)areequal. => ((2)) (memq '(2) '((1) (2))) ;(2)and(2)are noteq. => nil ;; Two strings with the same contents areequal. (member "foo" '("foo" "bar")) => ("foo" "bar")
If
sequenceis a list, this function destructively removes all elementsequalto object from sequence. For lists,deleteis todelqasmemberis tomemq: it usesequalto compare elements with object, likemember; when it finds an element that matches, it cuts the element out just asdelqwould.If
sequenceis a vector or string,deletereturns a copy ofsequencewith all elementsequaltoobjectremoved.For example:
(setq l '((2) (1) (2))) (delete '(2) l) => ((1)) l => ((2) (1)) ;; If you want to changelreliably, ;; write(setq l (delete elt l)). (setq l '((2) (1) (2))) (delete '(1) l) => ((2) (2)) l => ((2) (2)) ;; In this case, it makes no difference whether you setl, ;; but you should do so for the sake of the other case. (delete '(2) [(2) (1) (2)]) => [(1)]
This function is the non-destructive counterpart of
delete. It returns a copy ofsequence, a list, vector, or string, with elementsequaltoobjectremoved. For example:(remove '(2) '((2) (1) (2))) => ((1)) (remove '(2) [(2) (1) (2)]) => [(1)]
Common Lisp note: The functionsmember,deleteandremovein GNU Emacs Lisp are derived from Maclisp, not Common Lisp. The Common Lisp versions do not useequalto compare elements.
This function is like
member, except that object should be a string and that it ignores differences in letter-case and text representation: upper-case and lower-case letters are treated as equal, and unibyte strings are converted to multibyte prior to comparison.
This function destructively removes all
equalduplicates from list, stores the result in list and returns it. Of severalequaloccurrences of an element in list,delete-dupskeeps the first one.
See also the function add-to-list, in List Variables,
for a way to add an element to a list stored in a variable and used as a
set.
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.2
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))
Both the values and the keys in an alist may be any Lisp objects.
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 of such an alist:
((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.
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 Property Lists, for a comparison of property lists and association lists.
This function returns the first association for key in alist, comparing key against the alist elements using
equal(see Equality Predicates). It returnsnilif no association in alist has a carequalto 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) => nilHere 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 function assoc-string is much like assoc except
that it ignores certain differences between strings. See Text Comparison.
This function returns the first association with value value in alist. It returns
nilif no association in alist has a cdrequalto value.
rassocis likeassocexcept that it compares the cdr of each alist association instead of the car. You can think of this as “reverseassoc,” finding the key for a given value.
This function is like
associn that it returns the first association for key in alist, but it makes the comparison usingeqinstead ofequal.assqreturnsnilif no association in alist has a careqto key. This function is used more often thanassoc, sinceeqis faster thanequaland most alists use symbols as keys. See 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,
assqis 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)
This function returns the first association with value value in alist. It returns
nilif no association in alist has a cdreqto value.
rassqis likeassqexcept that it compares the cdr of each alist association instead of the car. You can think of this as “reverseassq,” 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
rassqcannot 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) => nilIn this case, the cdr of the association
(lily white)is not the symbolwhite, but rather the list(white). This becomes clearer if the association is written in dotted pair notation:(lily white) == (lily . (white))
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-matchwith an alist that contains regular expressions (see Regexp Search). If test is omitted ornil,equalis used for comparison.If an alist element matches key by this criterion, then
assoc-defaultreturns 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-defaultreturnsnil.
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)))) => tThis example shows how
copy-alistmakes 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")
This function deletes from alist all the elements whose car is
eqto key, much as if you useddelqto delete each such element one by one. It returns the shortened alist, and often modifies the original list structure of alist. For correct results, use the return value ofassq-delete-allrather than looking at the saved value of alist.(setq alist '((foo 1) (bar 2) (foo 3) (lose 4))) => ((foo 1) (bar 2) (foo 3) (lose 4)) (assq-delete-all 'foo alist) => ((bar 2) (lose 4)) alist => ((foo 1) (bar 2) (lose 4))
This function deletes from alist all the elements whose cdr is
eqto value. It returns the shortened alist, and often modifies the original list structure of alist.rassq-delete-allis likeassq-delete-allexcept that it compares the cdr of each alist association instead of the car.
This section describes functions for operating on rings. A ring is a fixed-size data structure that supports insertion, deletion, rotation, and modulo-indexed reference and traversal.
This returns a new ring capable of holding size objects. size should be an integer.
This returns the number of objects that ring currently contains. The value will never exceed that returned by
ring-size.
This returns a new ring which is a copy of ring. The new ring contains the same (
eq) objects as ring.
The newest element in the ring always has index 0. Higher indices correspond to older elements. Indices are computed modulo the ring length. Index −1 corresponds to the oldest element, −2 to the next-oldest, and so forth.
This returns the object in ring found at index index. index may be negative or greater than the ring length. If ring is empty,
ring-refsignals an error.
This inserts object into ring, making it the newest element, and returns object.
If the ring is full, insertion removes the oldest element to make room for the new element.
Remove an object from ring, and return that object. The argument index specifies which item to remove; if it is
nil, that means to remove the oldest item. If ring is empty,ring-removesignals an error.
This inserts object into ring, treating it as the oldest element. The return value is not significant.
If the ring is full, this function removes the newest element to make room for the inserted element.
If you are careful not to exceed the ring size, you can use the ring as a first-in-first-out queue. For example:
(let ((fifo (make-ring 5)))
(mapc (lambda (obj) (ring-insert fifo obj))
'(0 one "two"))
(list (ring-remove fifo) t
(ring-remove fifo) t
(ring-remove fifo)))
=> (0 t one t "two")
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.
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.
Returns
tif object is a list, vector, string, bool-vector, or char-table,nilotherwise.
This function returns the number of elements in sequence. If sequence is a dotted list, a
wrong-type-argumenterror is signaled. Circular lists may cause an infinite loop. For a char-table, the value returned is always one more than the maximum Emacs character code.See Definition of safe-length, 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
See also string-bytes, in Text Representations.
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, out-of-range values behave as for
nth. See Definition of nth. Otherwise, out-of-range values trigger anargs-out-of-rangeerror.(elt [1 2 3 4] 2) => 3 (elt '(1 2 3 4) 2) => 3 ;; We usestringto show clearly which charactereltreturns. (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], -1This function generalizes
aref(see Array Functions) andnth(see Definition of nth).
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 Text Properties.
This function does not work for dotted lists. Trying to copy a circular list may cause an infinite loop.
See also
appendin Building Lists,concatin Creating Strings, andvconcatin Vector Functions, for other 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)]
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. Each type of array has its own read syntax. See String Type, and Vector Type.
All four kinds of array share these characteristics:
aref and aset, respectively (see Array Functions).
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 Key Sequence Input.
In this section, we describe the functions that accept all types of arrays.
This function returns
tif 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
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 Sequence Functions.
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-argumenterror results. The function converts a unibyte string to multibyte if necessary to insert a character.
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-argumenterror results.
The general sequence functions copy-sequence and length
are often useful for objects known to be arrays. See Sequence Functions.
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 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
Here are some functions that relate to vectors:
This function returns
tif object is a vector.(vectorp [a]) => t (vectorp "asdf") => nil
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) => []
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]
This function returns a new vector containing all the elements of the sequences. The arguments sequences may be true lists, vectors, strings or bool-vectors. If no sequences are given, an empty vector is returned.
The value is a newly constructed vector that is not
eqto 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
vconcatfunction 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 Byte-Code Objects.In Emacs versions before 21, the
vconcatfunction allowed integers as arguments, converting them to strings of digits, but that feature has been eliminated. The proper way to convert an integer to a decimal number in this way is withformat(see Formatting Strings) ornumber-to-string(see String Conversion).For other concatenation functions, see
mapconcatin Mapping Functions,concatin Creating Strings, andappendin Building Lists.
The append function also provides a way to convert a vector into a
list with the same elements:
(setq avector [1 two (quote (three)) "four" [five]])
=> [1 two (quote (three)) "four" [five]]
(append avector nil)
=> (1 two (quote (three)) "four" [five])
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.
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.
This function sets the default value of generic character char in char-table to new-default.
There is no special function to access default values in a char-table. To do that, use
char-table-range(see below).
This function returns the parent of char-table. The parent is always either
nilor another char-table.
This function sets the parent of char-table to new-parent.
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.
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.
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 Character Sets).
- generic-char
- A generic character stands for a character set, or a row of a character set; specifying the generic character as argument is equivalent to specifying the character set name. See Splitting Characters, for a description of generic characters.
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 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 Splitting Characters, for a description of generic characters.
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-rangechar-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)))
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.
Return a new bool-vector of length elements, each one initialized to initial.
Here is an example of creating, examining, and updating a bool-vector. Note that the printed form represents up to 8 boolean values as a single character.
(setq bv (make-bool-vector 5 t))
=> #&5"^_"
(aref bv 1)
=> t
(aset bv 3 nil)
=> nil
bv
=> #&5"^W"
These results make sense because the binary codes for control-_ and control-W are 11111 and 10111, respectively.
A hash table is a very fast kind of lookup table, somewhat like an alist (see Association Lists) in that it maps keys to corresponding values. It differs from an alist in these ways:
Emacs Lisp provides a general-purpose hash table data type, along with a series of functions for operating on them. Hash tables have no read syntax, and print in hash notation, like this:
(make-hash-table)
=> #<hash-table 'eql nil 0/65 0x83af980>
(The term “hash notation” refers to the initial `#' character—see Printed Representation—and has nothing to do with the term “hash table.”)
Obarrays are also a kind of hash table, but they are a different type of object and are used only for recording interned symbols (see Creating Symbols).
The principal function for creating a hash table is
make-hash-table.
This function creates a new hash table according to the specified arguments. The arguments should consist of alternating keywords (particular symbols recognized specially) and values corresponding to them.
Several keywords make sense in
make-hash-table, but the only two that you really need to know about are:testand:weakness.
:testtest- This specifies the method of key lookup for this hash table. The default is
eql;eqandequalare other alternatives:
eql- Keys which are numbers are “the same” if they are
equal, that is, if they are equal in value and either both are integers or both are floating point numbers; otherwise, two distinct objects are never “the same.”eq- Any two distinct Lisp objects are “different” as keys.
equal- Two Lisp objects are “the same,” as keys, if they are equal according to
equal.You can use
define-hash-table-test(see Defining Hash) to define additional possibilities for test.:weaknessweak- The weakness of a hash table specifies whether the presence of a key or value in the hash table preserves it from garbage collection.
The value, weak, must be one of
nil,key,value,key-or-value,key-and-value, ortwhich is an alias forkey-and-value. If weak iskeythen the hash table does not prevent its keys from being collected as garbage (if they are not referenced anywhere else); if a particular key does get collected, the corresponding association is removed from the hash table.If weak is
value, then the hash table does not prevent values from being collected as garbage (if they are not referenced anywhere else); if a particular value does get collected, the corresponding association is removed from the hash table.If weak is
key-and-valueort, both the key and the value must be live in order to preserve the association. Thus, the hash table does not protect either keys or values from garbage collection; if either one is collected as garbage, that removes the association.If weak is
key-or-value, either the key or the value can preserve the association. Thus, associations are removed from the hash table when both their key and value would be collected as garbage (if not for references from weak hash tables).The default for weak is
nil, so that all keys and values referenced in the hash table are preserved from garbage collection.:sizesize- This specifies a hint for how many associations you plan to store in the hash table. If you know the approximate number, you can make things a little more efficient by specifying it this way. If you specify too small a size, the hash table will grow automatically when necessary, but doing that takes some extra time.
The default size is 65.
:rehash-sizerehash-size- When you add an association to a hash table and the table is “full,” it grows automatically. This value specifies how to make the hash table larger, at that time.
If rehash-size is an integer, it should be positive, and the hash table grows by adding that much to the nominal size. If rehash-size is a floating point number, it had better be greater than 1, and the hash table grows by multiplying the old size by that number.
The default value is 1.5.
:rehash-thresholdthreshold- This specifies the criterion for when the hash table is “full” (so it should be made larger). The value, threshold, should be a positive floating point number, no greater than 1. The hash table is “full” whenever the actual number of entries exceeds this fraction of the nominal size. The default for threshold is 0.8.
This is equivalent to
make-hash-table, but with a different style argument list. The argument test specifies the method of key lookup.This function is obsolete. Use
make-hash-tableinstead.
This section describes the functions for accessing and storing associations in a hash table. In general, any Lisp object can be used as a hash key, unless the comparison method imposes limits. Any Lisp object can also be used as the value.
This function looks up key in table, and returns its associated value—or default, if key has no association in table.
This function enters an association for key in table, with value value. If key already has an association in table, value replaces the old associated value.
This function removes the association for key from table, if there is one. If key has no association,
remhashdoes nothing.Common Lisp note: In Common Lisp,
remhashreturns non-nilif it actually removed an association andnilotherwise. In Emacs Lisp,remhashalways returnsnil.
This function removes all the associations from hash table table, so that it becomes empty. This is also called clearing the hash table.
Common Lisp note: In Common Lisp,
clrhashreturns the empty table. In Emacs Lisp, it returnsnil.
This function calls function once for each of the associations in table. The function function should accept two arguments—a key listed in table, and its associated value.
maphashreturnsnil.
You can define new methods of key lookup by means of
define-hash-table-test. In order to use this feature, you need
to understand how hash tables work, and what a hash code means.
You can think of a hash table conceptually as a large array of many
slots, each capable of holding one association. To look up a key,
gethash first computes an integer, the hash code, from the key.
It reduces this integer modulo the length of the array, to produce an
index in the array. Then it looks in that slot, and if necessary in
other nearby slots, to see if it has found the key being sought.
Thus, to define a new method of key lookup, you need to specify both a function to compute the hash code from a key, and a function to compare two keys directly.
This function defines a new hash table test, named name.
After defining name in this way, you can use it as the test argument in
make-hash-table. When you do that, the hash table will use test-fn to compare key values, and hash-fn to compute a “hash code” from a key value.The function test-fn should accept two arguments, two keys, and return non-
nilif they are considered “the same.”The function hash-fn should accept one argument, a key, and return an integer that is the “hash code” of that key. For good results, the function should use the whole range of integer values for hash codes, including negative integers.
The specified functions are stored in the property list of name under the property
hash-table-test; the property value's form is(test-fn hash-fn).
This function returns a hash code for Lisp object obj. This is an integer which reflects the contents of obj and the other Lisp objects it points to.
If two objects obj1 and obj2 are equal, then
(sxhashobj1)and(sxhashobj2)are the same integer.If the two objects are not equal, the values returned by
sxhashare usually different, but not always; once in a rare while, by luck, you will encounter two distinct-looking objects that give the same result fromsxhash.
This example creates a hash table whose keys are strings that are compared case-insensitively.
(defun case-fold-string= (a b)
(compare-strings a nil nil b nil nil t))
(defun case-fold-string-hash (a)
(sxhash (upcase a)))
(define-hash-table-test 'case-fold
'case-fold-string= 'case-fold-string-hash)
(make-hash-table :test 'case-fold)
Here is how you could define a hash table test equivalent to the
predefined test value equal. The keys can be any Lisp object,
and equal-looking objects are considered the same key.
(define-hash-table-test 'contents-hash 'equal 'sxhash)
(make-hash-table :test 'contents-hash)
Here are some other functions for working with hash tables.
This function creates and returns a copy of table. Only the table itself is copied—the keys and values are shared.
This returns the test value that was given when table was created, to specify how to hash and compare keys. See
make-hash-table(see Creating Hash).
This function returns the weak value that was specified for hash table table.
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 Variables, and Functions. For the precise read syntax for symbols, see Symbol Type.
You can test whether an arbitrary Lisp object is a symbol
with symbolp:
Each symbol has four components (or “cells”), each of which references another object:
symbol-name in Creating Symbols.
symbol-value in
Accessing Variables.
symbol-function in Function Cells.
symbol-plist in 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 Creating Symbols.)
The value cell holds the symbol's value as a variable
(see Variables). That is what you get if you evaluate the symbol as
a Lisp expression (see Evaluation). Any Lisp object is a legitimate
value. Certain symbols have values that cannot be changed; these
include nil and t, and any symbol whose name starts with
`:' (those are called keywords). See Constant Variables.
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 explicit only when necessary. In normal
usage, the function cell usually contains a function
(see Functions) or a macro (see Macros), as that is what the
Lisp interpreter expects to see there (see Evaluation). Keyboard
macros (see Keyboard Macros), keymaps (see Keymaps) and
autoload objects (see Autoloading) are also sometimes stored in
the function cells of symbols.
The property list cell normally should hold a correctly formatted property list (see 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-function 'buffer-file-name)
=> #<subr buffer-file-name>
(symbol-plist 'buffer-file-name)
=> (variable-documentation 29529)
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 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 Primitive Function Type). A
symbol naming a function written in Lisp would have a lambda expression
(or a byte-code object) in this cell.
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
Defining Variables. For defining user option variables that can
be customized, use defcustom (see Customization).
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 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 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 Accessing Documentation.
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. (The same idea is used for general Emacs hash tables, but they are a different data type; see Hash Tables.)
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.
Interning usually happens automatically in the reader, but sometimes other programs need to do it. For example, after the M-x command obtains the command name as a string using the minibuffer, it then interns the string, to get the interned symbol with that name.
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.
Creating an uninterned symbol is useful in generating Lisp code, because an uninterned symbol used as a variable in the code you generate cannot clash with any variables used in other Lisp programs.
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, so 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.
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!
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 ofsymis noteqtofoobecause it is a distinct uninterned symbol whose name is also `foo'.(setq sym (make-symbol "foo")) => foo (eq sym 'foo) => nil
This function returns the interned symbol whose name is name. If there is no such symbol in the obarray obarray,
interncreates a new one, adds it to the obarray, and returns it. If obarray is omitted, the value of the global variableobarrayis used.(setq sym (intern "foo")) => foo (eq sym 'foo) => t (setq sym1 (intern "foo" other-obarray)) => foo (eq sym1 '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.
This function returns the symbol in obarray whose name is name, or
nilif obarray has no symbol with that name. Therefore, you can useintern-softto test whether a symbol with a given name is already interned. If obarray is omitted, the value of the global variableobarrayis used.The argument name may also be a symbol; in that case, the function returns name if name is interned in the specified obarray, and otherwise
nil.(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
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 ofobarray, 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 => 1871See
documentationin Accessing Documentation, for another example usingmapatoms.
This function deletes symbol from the obarray obarray. If
symbolis not actually in the obarray,uninterndoes nothing. If obarray isnil, the current obarray is used.If you provide a string instead of a symbol as symbol, it stands for a symbol name. Then
uninterndeletes the symbol (if any) in the obarray which has that name. If there is no such symbol,uninterndoes nothing.If
uninterndoes delete a symbol, it returnst. Otherwise it returnsnil.
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 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.
Association lists (see 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.
This function sets symbol's property list to plist. Normally, plist should be a well-formed property list, but this is not enforced. The return value is plist.
(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 Abbrevs).
This function finds the value of the property named property in symbol's property list. If there is no such property,
nilis returned. Thus, there is no distinction between a value ofniland 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
putfor an example.
This function puts value onto symbol's property list under the property name property, replacing any previous property value. The
putfunction 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))
These functions are useful for manipulating property lists that are stored in places other than symbols:
This returns the value of the property property stored in the property list plist. For example,
(plist-get '(foo 4) 'foo) => 4 (plist-get '(foo 4 bad) 'foo) => 4 (plist-get '(foo 4 bad) 'bar) =>wrong-type-argumenterrorIt accepts a malformed plist argument and always returns
nilif property is not found in the plist. For example,(plist-get '(foo 4 bad) 'bar) => nil
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)))
Like
plist-getexcept that it compares properties usingequalinstead ofeq.
Like
plist-putexcept that it compares properties usingequalinstead ofeq.
This returns non-
nilif plist contains the given property. Unlikeplist-get, this allows you to distinguish between a missing property and a property with the valuenil. The value is actually the tail of plist whosecaris property.
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.
The Lisp interpreter, or evaluator, is the program that computes the value of an expression that is given to it. When a function written in Lisp is called, the evaluator computes the value of the function by evaluating the expressions in the function body. Thus, running any Lisp program really means running the Lisp interpreter.
How the evaluator handles an object depends primarily on the data type of the object.
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 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 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 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 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.3 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 Variables.
Evaluation of a form may create new environments for recursive
evaluation by binding variables (see 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 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.
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>
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 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 Constant Variables.
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.
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 Function Names, 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 Function Cells). 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