GNU Emacs Lisp Manual

Emacs Version 18 for Unix Users September 1988

Bil Lewis

and the gnu.emacs.lisp.manual list Copyright \begin{matrix}c \\ ◯ \end{matrix} 1988 Richard M. Stallman.

Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.

Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.

Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.

GNU EMACS LISP REFERENCE MANUAL — 2nd DRAFT

CAVEATS

This is the 2nd draft version of this manual. It is, by no means, complete or flawless. There are a couple specific sections which are not included (either they haven’t been written yet All primitive functions are at least mentioned, even if the mention is that they aren’t yet documented.

There are several pieces which are intentionally left out because we are not able to deal with them completely. This includes any reference to VMS and all the suntools stuff and X.

This should, however, be fully correct in what it does say, and it is therefore open to criticsm on anything it does include — 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 source or experiment to learn something not covered in the manual, then perhaps the manual should be fixed. Please let us know.

There will be a few sections with “..prose..” in them, indicating that we need to write some more. There are occasional sentences with "!!" and "??" indicating unresolved issues or questions. Please look at these and try to come up with answers.

With a few exceptions, we have not included anything in the way of concept index pointers and the node hierarchy for texinfo. That is the next big job. The manual is not presently texinfo-able.

As you use the manual, I recommend you mark pages with corrections so you can later look them up. If you think of a simple, real life example for a function or group of functions, please make an effort to write it up and send it in.

Please reference any comments to the chapter name, section name, and function name, as appropriate, since the chapter and section numbers will change.

Mail comments and corrections to: gnu-manual@cs.uiuc.edu or uiucdcs!gnu-manual. The gnumanual mailing list is composed of volunteers who wish to help create this manual. Mail to gnumanual-request to be added to the list.

-Bil Lewis 31-Oct-87 -Dan LaLiberte 12-Sept-88 2 GNU Emacs Lisp Reference Manual

1. Introduction

1.1 Lisp History

Lisp (LISt Processing language) was first developed in the late ’50s at MIT for use in Artificial Intelligence. Much later, programmers discovered that the great power of the Lisp language made it superior for other purposes as well, such as writing editor 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 60’s at MIT’s Project MAC. Eventually the implementors of the descendents of Maclisp got together and developed a standard for Lisp systems, called Common Lisp.

GNU Emacs Lisp is largely inspired by Maclisp, and a little by Common Lisp. If you know Common Lisp, you will notice many similarities. But many of the 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.

1.2 Conventions

This chapter explains notational conventions used in this manual. Beginners should skip this chapter and refer back to it later.

1.3 The Lisp Reader and Printer

Throughout this manual, the phrases “the Lisp reader” and “the Lisp printer” will be used to refer to those routines in Lisp that read expressions and print text. You, the person reading this manual, are assumed to be “the programmer” but you will be refered to as “you”. “The user” is the person who will use the code you write.

1.4 Nil, False, and the Empty List

In GNU Emacs Lisp, the symbol nil is overloaded with three meanings: It is a symbol with the name ‘nil’, it is the logical value false, and it is the empty list — the list of zero elements. The Lisp reader interprets the empty list notation ‘()’ to be identical to nil. Once read, there is no way to determine which representation was actually written by the programmer.

Throughout this manual, we will use () when we wish to emphasize the fact that it is the empty list, we will use nil when we wish to emphasize the fact that it is the truth value false, and we will use 'nil when we wish to emphasize the fact that it is a symbol.

(cons 'FOO ()) ; Emphasize it as the empty list (not nil) ; Emphasize it as false (symbol-name 'nil) ; Emphasize it as a symbol

1.5 Evaluation, Expansion, and Equivalence

When a piece of Lisp code is evaluated, it produces a result. In the examples in this manual, this will be indicated with ‘=>’:

(car '(1 2))
=> 1

When a form is a macro call, it will expand into a new form for Lisp to evaluate. We will show the result of the expansion with ‘==>’. We may or may not show the the actual result of the evaluation of the expanded form.

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

In some instances, one form will be described by showing another form which produces identical results. Exact equivalency of two forms will be indicated with ‘==’

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

1.6 Printing

Many of the examples will print some text. If the example is executed from a Lisp Interaction buffer (typically the buffer *scratch*), then the text that is printed will be inserted into the buffer. If the example is executed by other means (such as by evaluating the function eval-region), then the text will be printed in the echo area. You should be aware that text printed in the echo area will not all be visible if more than one line is required.

In all examples that involve printing text, the text printed will be indicated with ‘->’, irrespective of how the form is executed. The result returned by the execution of the form will follow on the next line (here bar).

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

1.7 Errors

Some of the examples will cause errors to be signaled. In those cases, the error messages (which always appear in the echo area) will be shown on a line following ‘-> ERROR:’. Note that ‘-> ERROR:’ itself does not appear in the echo area.

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

1.8 Inserting Text

Some of the examples will insert text into a buffer. This will be shown by displaying the entire contents of a buffer, often as before and after versions. In such cases, the entire contents of the buffer in question will be included between two lines of dashes containing the buffer name.

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

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

1.9 The Format of Descriptions

We will describe functions, commands, variables, user options, macros, and special forms with a uniform format. The first line of the description contains the name of the item followed by arguments, if appropriate. A written description will follow on succeeding lines, sometimes with examples.

Commands are simply functions that may be called interactively. Macros and special forms process their arguments in a different way from functions, but otherwise appear the same. The descriptions of commands, macros, and special forms will share the same attributes as the descriptions of functions.

Although all variables and constants are modifiable, options are variables that have been declared as options so that users can change their values more conveniently. Constants are variables that have been declared to be changed by the execution of a program. This use of the term constant should be distinguished from the concept of a self-evaluating form. The latter is sometimes referred to as a literal. Descriptions of options and constants will share the attributes of variable descriptions.

Actual examples (and fragments) of code will appear in this font or form: (list 1 2 3). Names that represent arguments will appear in this font or form: variable-1.

1.9.1 A Sample Function Description

In function, macro, and special form descriptions, the appearence of the keyword &optional in the parameter list indicates that the arguments for the parameters following it may be left out (in which case the parameter will default to nil if the description does not specifically mention a different value).

The keyword &rest (which will always be followed by a single parameter) indicates that any number of arguments can follow the required and optional ones. The additional arguments will be made into a list to which the last parameter will be bound.

Any parameter whose name contains that of a type (e.g., integer, integer1, buffers), are expect to be of that type. Parameters with other names (e.g., name) will be specifically included in the description. Parameters named object may be of any type. Before a set of descriptions, some sections will also include a description of a set of parameters that the functions share.

The following description is of the imaginary foo function. Command, macro, and special form descriptions have the same form, but ‘[Function]’ on the right edge of the page is replaced by ‘[Command]’, ‘[Macro]’, or ‘[Special Form]’, respectively. Additionally, macros and special forms may use ‘[optional-arg]’ to mean optional-arg is optional and ‘repeated-arg*’ to mean that repeated-arg may be repeated zero or more times.

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

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

More generally,

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

1.9.2 A Sample Variable, Option, or Constant Description

The following description is of the imaginary electiric-future-map variable. Option and Constant descriptions have the same form, but ‘[Variable]’ on the right edge of the page is

replaced by ‘[Option]’ or ‘[Constant]’.

Variable electric-future-map

The value of this variable is a full keymap used by electric command future mode. The functions in this map will allow you to edit commands you have not yet thought about executing.

8 GNU Emacs Lisp Reference Manual

2. Types of Lisp Objects

A Lisp object is data used and manipulated by Lisp programs. Data objects such as the number ‘1’ and the list ‘(this is a list)’ are said to have a type.

One way to define a type is as a set of Lisp objects. Objects of the same type have a similar structure and may often be used in the same contexts. An object may be in more than one type simultaneously so it doesn’t make sense to ask what the type of an object is; rather, we ask whether an object belongs to a particular type.

There are several types in GNU Emacs Lisp, and the types themselves may be catagorized. A primitive type, such as number, list, or string, is specially recognized by Emacs and is not “divisible” into any other type. (need better definition!!)

While an object may be a member of more than one type, every object is a member of exactly one primitive type. The primitive type of an object is stored along with the object’s data and Lisp functions are provided to check whether an object is a member of each primitive type.

A supertype is a collection of other subtypes that have some common property. For example, the vector and string types are subtypes of the array supertype.

A derived (compound?? special-case??) type is a special case use of some other type. For example, a Lisp function type is a list where the first element is lambda.

In addition to the standard types recognized by Emacs, you may create your own types out of any existing types. To do so you may want to provide the supporting functions to create objects and to check whether an object is a member of your type.

This chapter describes the purpose of each of the standard types in GNU Emacs Lisp along with their print representation and read syntax.

2.1 Print Representation and Read Syntax

The print representation of an object is the format of the output generated by the Lisp printer. All types have a print representation. The read syntax of an object, if it has one, is the format of input accepted by the Lisp reader. Anything which may be printed may also be read except for the unreadable types. However, not every read syntax has a corresponding print syntax (see Characters and Lists).

Some types do not have a read syntax defined for them. Normally this is because it would not be particularly useful to have one. These objects are represented in hash notation, which is the characters ‘#<’ followed by a descriptive string (typically the type name followed by the name of the object), and closed with another ‘>’.

The Lisp reader will signal an invalid-read-syntax error if it encounters the character ‘#’. The buffer type is an example of a type with no read syntax.

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

2.2 Number Type

There is only one kind of number in GNU Emacs Lisp, an integer. The range of values for a small integer is -8388608 to 8388607 (24 bits) on many machines, although it is 25 or 26 bits on some. It is important to note that in GNU Emacs Lisp, arithmetic functions do not check for overflow. Thus (1+ 8388607) == -8388608 (on 24 bit implementations).

The Lisp reader accepts numbers as a sequence of digits with an optional sign.

     -1               ;The integer -1.
     1                ;The integer 1.
     +1               ;Also the integer 1.
     16777217         ;Also the integer 1! (on a 24 bit implementation)

2.3 Character Type

Characters in GNU Emacs Lisp are represented internally with their ASCII values. For example, the character A is represented internally as the integer 65. If an arbitrary integer is used as a character, only the lower 8 bits is significant, but this behavior is not guarenteed (or is it??).

There are a variety of read syntax formats for characters. The normal syntax for reading individual characters is a question mark followed by the character (e.g., ‘?A’ for the character A). For non-printing characters, one possible format is a question mark, then a backslash followed by the ASCII value of the character in octal (e.g., ‘?\001’ for C-a). This syntax may be used for any character and it is preferred when the precise octal value is more important than the ASCII representation.

For control characters, the sequence question mark, backslash, caret, and the corresponding non-control character is also valid (e.g., ‘?\^I’ for the character C-i). Similarly, the syntax ‘?\C-i’ is valid for C-i.

Meta characters are defined to be the set of ASCII characters which have their eighth bit set. These characters can be written as ‘?\M-a’ (the character Meta-A, the ‘A’ is upper case), ‘?\M-a’ (the character Meta-a, the ‘a’ is lower case). Emacs does not consider meta characters as primitive in key sequences. That is, key sequences defined using the meta key are actually translated into a sequence using the meta-prefix-char instead. See chapter 18 [Keymaps], page 155 and see section 18.3 [meta-prefix-char], page 160.

Backspace, newline, formfeed, tab, and return can be abbreviated: ?\b ?\n ?\f ?\t ?\r.

The characters ‘()\|;'`"#.,’ must be preceeded by a backslash character ‘\’ to work reliably in all contexts. The space character, tab, newline, formfeed and any explicit control characters must also be preceeded by backslash. But rather than entering these invisible characters explicitly, it is better to use one of the other formats.

Characters always print as numbers. Thus, the following list of characters which are specified with a variety of read formats is printed as a list of numbers.

     '(?A ?\000 ?\t ?\n ?\f ?\r ?\( ?\) ?\\
       ?\| ?\011 ?\^I ?\C-i ?\M-i)
          => (65 0 9 10 12 13 40 41 92 124 9 9 9 201)

It is unusual for a programmer to work with individual characters. It is far more common to work with strings, which are composed of characters.

2.4 Sequence Type

The sequence type is a supertype of three other Lisp types: lists, vectors, and strings. That is to say, lists, vectors, and strings are sequences. Common between all sequences is that each is composed of an ordered collection of elements.

Some Lisp functions can accept any kind of sequence as an argument; only the elements of the sequence are significant.

2.5 List Type

A list is a series of cons cells, linked together. A cons cell is a Lisp object comprised of two pointers known as the car and the cdr, each of which in turn can point to any Lisp object. Normal use of cons cells is that the cdr point to another cons cell or the empty list (aka nil).

To enter a list in a program, begin with an open parenthesis ‘(’, follow it with the list of elements of the list, and end with a close parenthesis ‘)’. Any objects (symbols, numbers, vectors, strings, or other lists) that are read between such a pair of parentheses are made into the elements of the list. The use of the escape character (‘\’) nullifies this special meaning of open/close parenthesis, but it is advisable to avoid this use. (Also, unbalanced parentheses in strings and comments can confuse some of the functions for moving between lists.)

A list without any elements in it is called the empty list; it is identical to the symbol nil. In other words, nil is recognized to be both a list (listp nil) => t and a symbol (symbolp nil)

=> t.

The single character period ‘.’ is also significant in lists. It is means the single following object is taken as the cdr of the final cons cell of the list. These unusual lists are therefore not terminated with nil.

     (A 2 "A")                ; A list of three elements
     ()                       ; A list of no elements (the empty list)
     nil                      ; A list of no elements (the empty list)
     ("A ()")                 ; A list of one element: the string "A ()"
     (A ())                   ; A list of two elements: A and the empty list
     (A . B)                  ; A list of one element and a non-nil cdr
     (A . B . C)              ; Invalid syntax
     ((A B C))                ; A list of one element (which is a list of 3)

2.6 Array Type

An array is a Lisp object composed of other Lisp objects any of which may be accessed in equal time. The term array has a more general meaning in other contexts, but in GNU Emacs Lisp, there are only two types of arrays, both one-dimensional. A string is an array of characters and a vector is an array of any type.

All arrays have a fixed length and are indexed zero-origin. For example, an array of four elements allows indices 0, 1, 2, and 3. The elements or any array may be referenced or changed with the functions aref and aset.

Arrays are a subtype of sequences and there is a collection of more general functions which operate on sequences.

2.6.1 String Type

A string is an array of characters; strings share all the attributes of vectors except that their elements are restricted to being characters (i.e. integers between 0 and 255). See section 2.3 [Character Type], page 10 for more details about characters. Strings, however, are not vectors.

A string may be entered in a program as a list of characters between double quotes. The Lisp reader will accept a number of alternatives for reading those characters. A backslash (‘\’) has special meaning inside of double quotes. This escape character behaves identically to the backslash escape in characters

"\001" An octal integer: read as the ASCII equivalent (ASCII 1, CTL-A) "\C-a" "C-" and a character: read as that control character (ASCII 1, CTL-A) "\M-a" "M-" and a character: read as that meta character (ASCII 301, Meta-A) "\b" a backspace (ASCII 8, BS, C-h) "\n" a newline (ASCII 10, LFD, C-j) "\r" a carriage return (ASCII 13, RET, C-m) "\t" a tab character (ASCII 9, TAB, C-i) "\f" a formfeed character (ASCII 12, C-l)

A backslash followed by anything else reads as that character. In particular, ‘"\\"’ reads as a string consisting of one backslash character and, ‘"\""’ reads as the string consisting of one double quote character.

The ‘\C-a’ syntax will work for either upper or lower case A (but the ‘C’ must be upper case); the ‘\n’, ‘\r’, etc. syntax requires lower case.

For control characters in strings, the Lisp printer will print out the string with the actual control characters in it. However, they will be displayed on the screen according to how Emacs is set up to display control characters see section 26.8 [ctl-arrow], page 255. The other two characters requiring special syntax (backslash and double-quote) print out with a leading backslash:

"\\"
     => "\\"
"\""
     => "\""

(Who handles strings like:

"test\
ing"

that are turned into "testing"??)

2.6.2 Vector Type

A vector is a one-dimensional array of elements of any type. Unlike a list, any element of a vector may be accessed in equal time.

The print representation and read syntax of vectors are identical: the list of elements is preceeded by a left square bracket ‘[’ and followed by a right square bracket ‘]’. It should be noted that two vectors created with the same elements will not be the same vector. Indeed, there is no way in which to read the same vector twice.

(setq v1 (vector 1 2 'foo))
     => [1 2 foo]                    ;Create a vector of three elements.
(setq v2 (vector 1 2 'foo))
     => [1 2 foo]                    ;Create another vector of three elements.
(eq v1 v2)
     => nil                          ;They are not the same vector.
[1 2 3]
     => [1 2 3]
(eq [a b c] [a b c])                 ;NB: the elements are not evaluated.
     => nil                          ;They are not the same vector.
(equal [a b c] [a b c])
     => t                            ;But they have the same structure.

2.7 Symbol Type

A symbol in GNU Emacs Lisp is an object that serves several purposes. Symbols have four attributes or cells: a print name cell, a value cell, a function cell, and a property list cell. Each of these is a reference to some other Lisp object, and all but the first may be empty. Since symbols have these four independent cells, a symbol may be used in programs to refer simultaneously to a global variable value, a function, a property list, and the symbol itself.

The term void will be used to indicate that a cell has no valid data in it, e.g., ‘The symbol's value is void’. This should not be confused with the symbol void.

The print name cell is described here. The other cells of symbols are described in the chapter on Symbols (see chapter 8 [Symbols], page 65).

The print name is the most obvious thing about a symbol: it is what the printer prints when handed a symbol, and it is what distinguishes symbols from one another when the Lisp reader reads them. The print name cell references a string which is the print name, hence the name can consist of any string of characters whatsoever. You use a symbol in a program by typing its print name (without double quotes).

The rules for reading a symbol are similar to those for reading a string: all alphanumeric characters are read as part of the symbol’s name. Other characters may be included in a symbol’s name by escaping them with a backslash. Unlike the use in strings, the meaning of backslash is limited to quoting the single character that follows. Hence to have a symbol with a tab character (TAB) in its name, ‘\t’ will not work; rather you must actually type a tab. Putting unusual characters in a symbol’s name is a very poor idea.

   ________________________________

CN: In Common Lisp, lower case letters are always “folded” to upper case, unless they are explicitly “escaped”. This is not the case in GNU Emacs Lisp.

   ____________________

Each line below shows the printed representation of a single symbol.

     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+"
     +1                      ; An integer, not a symbol
     \+1                     ; A symbol named "+1" (a poor name to choose)
     \(*\ 1\ 2\)             ; A symbol named "(* 1 2)" (a worse name)
     +-*/_~!@$%^&=:<>{}   ; A symbol named "+-*/_~!@$%^&=:<>{}"
                             ;    (the normal characters (and + and -))

2.8 Primitive Function Type

A primitive function is a function callable from Lisp that is written in C. Primitives are also called subrs (subroutines), built-in functions, or compiled functions. They print in hash notation with the symbol name of the function.

See section 2.15.2 [Lisp Function Type], page 18 for the related Lisp function.

(symbol-function 'car) ; Access the function cell of the symbol.

=> #<subr car> ; A compiled function

     (subrp (symbol-function 'car))  ; Is this a subr?
          => t

2.9 Buffer Type

A buffer is an object containing characters. Buffers are used to hold the contents of files when they are visited and buffers may be displayed in windows. But buffers need not have an associated file or window. While several buffers may exist at one time, only one buffer is designated the current buffer. Most editing commands act on the contents of the current buffer.

Buffers can be treated rather like simple strings, but they are, in fact, complex objects which allow for inexpensive modification. A large set of functions is available to insert, delete, copy, or otherwise manipulate the characters in the buffer.

Several other data structures may be associated with buffers: a buffer may have a local syntax table, a local keymap, and a local variable binding list. Each of these overrides its global counterpart. The effect is that editing commands may have a different behavior in each buffer.

Buffers cannot be read by the Lisp reader. They print in hash notation with the buffer name.

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

2.10 Marker Type

A marker is an object which denotes a position in a specific buffer. They have two cells, one for the buffer, and one for the position in that buffer. The position value is changed as text is inserted or deleted so that the marker always points to the same place in the text.

Makers cannot be read directly. They print in hash notation giving the character position and the name of the buffer.

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

2.11 Window Type

A window is an object that describes the portion of the terminal screen that Emacs uses to display a buffer. Every window has an associated buffer, but not all buffers must be displayed in a window. Windows cannot be read in. They print out in hash notation giving the window number and buffer name.

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

2.12 Window Configuration Type

A window configuration stores information about the positions and sizes of windows at some particular time so that the configuration may be recreated later. Window configurations have no read syntax and always print as ‘#<window-configuration>’. See section 25.11 [Window Configurations], page 247 for the details.

2.13 Process Type

A process is a complex data structure which references the subprocess that Emacs has spawned off to perform some task. Text and signals can be communicated between Emacs and the subprocess. Processes have no read syntax. They print out in hash notation giving the name of the process.

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

2.14 Stream Type

A stream is a type of object that Emacs can use as a source (input) or sink (output) for characters. Many different objects fulfill this requirement: markers, buffers, strings, functions, and function names. The object nil is used as a stream to mean that the value of the variable standard-input or standard-output should be used. Similarly, the object t is used as a stream to represent input or output in the minibuffer. See chapter 16 [Streams], page 127 for the details.

2.15 Derived Types

GNU Emacs Lisp uses several other types built out of the types described previously. A derived type is a special-case use of some other type.

2.15.1 Association List Type

An association list is a list of pairs (cons cells), where the car of each sublist is the key, and the cdr is the associated value. Association lists are often used to record information that one might otherwise keep on a stack since new pairs may be simply added to the front of the list.

See section 6.6 [Association Lists], page 56 for the details.

2.15.2 Lisp Function Type

Lisp functions are the principal means by which Emacs may be extended. A Lisp function is a list where the first element is the symbol lambda.

Lisp function objects are normally created with defun. But lists that begin with lambda may be read in and used as functions. See chapter 10 [Functions], page 83 for the details.

     (defun foo (n) (print n))
          => foo
     (symbol-function 'foo)
          => (lambda (n) (print n))    ;An interpreted function.

2.15.3 Lisp Macro Type

Lisp macros are similar to Lisp functions. A Lisp a macro is a list where the first element is the symbol macro.

Lisp macro objects are normally created with defmacro. But lists that begin with macro may be read in and used as macros. See chapter 11 [Macros], page 91 for the details.

2.15.4 Autoload Type

Related to Lisp functions and macros is the autoload list which is a list where the first element is the symbol autoload.

An autoload object is normally created with the autoload function. The purpose of using autoload is to avoid loading a file of definitions unless they are needed. See section 13.1 [autoload], page 114 for the details.

2.15.5 Byte Code Type

Byte code is generated by byte-compile from Lisp function and macro objects. It is a list where the first element is the symbol byte-code. Evaluation of byte code is much faster than evaluation of non byte code. See chapter 14 [Byte Compilation], page 117 for the details.

2.15.6 Syntax Table Type

A syntax table is a vector of 256 integers. The elements define how the corresponding characters will be interpreted when they appear in a buffer. For example, in C mode, the character ‘+’ is punctuation, while in Lisp mode it can be a character in a symbol.

Syntax tables are only used for text in buffers, not for reading Lisp expressions. The table which Lisp uses to read expressions is built into the C code and cannot be changed. See section 37.3 [Syntax Tables], page 354 for the details.

2.15.7 Keymap Type

A keymap maps from keys typed by the user to functions which they call. There are two kinds of keymaps: full keymaps, which are implemented as vectors of 128 elements, and sparse keymaps, which are implemented as association lists with a preceeding keymap symbol. See chapter 18 [Keymaps], page 155 for the details.

2.16 Predicates

A predicate tests to see if some relation is met by its arguments. It returns a truth value which, in Lisp, is nil for false, and anything else for true. Most predicates return either the value t or their argument for true.

2.16.1 Type Predicates

The GNU Emacs Lisp interpreter does not perform any type checking on the actual arguments of function calls. It is up to each function to test whether each actual argument is a member of the correct type. All primitive functions do test the type of the actual arguments.

Many functions are provided to test whether an object is a member of a type. Here is a table of all of them and where they are described.

integerp see section 4.1 [integerp], page 33 natnump see section 4.1 [natnump], page 34 markerp see section 28.1 [markerp], page 268

integer-or-marker-p

see section 28.1 [integer-or-marker-p], page 268

sequencep

see section 7.1 [sequencep], page 59 stringp see section 5.1 [stringp], page 41

char-or-string-p

see section 5.1 [char-or-string-p], page 41

arrayp see section 7.2.1 [arrayp], page 61 vectorp see section 7.3 [vectorp], page 63 consp see section 6.1 [consp], page 49 listp see section 6.1 [listp], page 49 nlistp see section 6.1 [nlistp], page 49 bufferp see chapter 24 [bufferp], page 223 windowp see section 25.1 [windowp], page 236 processp see section 32.1 [processp], page 313 symbolp see section 8.3 [symbolp], page 66

user-variable-p

see section 9.2 [user-variable-p], page 75

subrp see section 10.3 [subrp], page 88 featurep see section 13.2 [featurep], page 116 keymapp see chapter 18 [keymapp], page 155

syntax-table-p

see section 31.2 [syntax-table-p], page 309

2.16.2 Equality Predicates

There are two functions to test equality between any two objects. These are described here. There are also functions to test equality between objects of specific types. See the appropriate chapter on the type for these predicates.

Function eq object1 object2 This function returns t if the two objects are the same object, nil otherwise. Symbols with the same print name are always eq (what about uninterned symbols??). Numbers with the same value are eq. Other objects (e.g., lists, vectors, strings) with the same elements may or may not be.

Also, if two objects are eq to each other, a change in one will be reflected in the same change in the other.

(eq 'foo 'foo)
     => t
(eq 456 456)
     => t
(eq "asdf" "asdf")
     => nil
(eq '(1 (2 (3))) '(1 (2 (3))))
     => nil
(eq [(1 2) 3] [(1 2) 3])
     => nil
(eq (point-marker) (point-marker))
     => nil

Function equal object1 object2 This function returns t if the two objects are structurally “the same”, nil otherwise. Objects (in particular, primitive objects) which are eq are also equal. Lists, vectors, markers, and strings are equal if the corresponding elements are equal.

      (equal "asdf" "asdf")
           => t
      (equal "asdf" "ASDF")
           => nil
      (equal '(1 (2 (3))) '(1 (2 (3))))
           => t
      (equal [(1 2) 3] [(1 2) 3])
           => t
      (equal (point-marker) (point-marker))
           => t

3. Evaluation

This chapter discusses how forms are evaluated. A form is any lisp object. The evaluation of forms is how Lisp performs manipulations of the Emacs Lisp environment. The Emacs Lisp environment is the set of global symbols, the run-time stack with local bindings, and a number of internal data structures used to maintain the environment. (correct??)

3.1 Eval

Evaluation is the means by which Lisp evaluates all forms. The details of how evaluation is accomplished for each kind of form is described in see section 3.2 [Forms], page 24. The functions and variables described here call the evaluator and define limits on it so that it does not enter infinite recursions.

Function eval form

This function evaluates its argument in the current environment (i.e., using the bindings on the stack (need a better definition of the environment!!)) and returns that as its result. Note that eval is not a special form, hence its argument gets evaluated twice.

     (setq foo 'bar)
     => bar
     (setq bar 'baz)
     => baz
     (eval foo)
     => baz

Command eval-current-buffer &optional printflag

This function evaluates the contents of the current buffer as Lisp code. The evaluator is called repeatedly on each of the forms in the buffer until either the end of the buffer is reached, or an error is signaled (and not handled??). If printflag is supplied, then it becomes the value for standard-output during the evaluation.

This function is normally called interactively where printflag defaults to nil. It returns

nil.

Command eval-region start end &optional printflag This function executes the contents of the current buffer in the region defined by start and end as Lisp code. The evaluator is called repeatedly on each of the forms in the region until either the end of the region is reached, or an error is signaled (and not handled). If printflag is supplied, then it becomes the value for standard-output during the evaluation.

When called interactively, start and end are the positions of the mark and the point, and printflag defaults to nil. It returns nil.

Variable max-specpdl-size

The value of this variable is the limit on the number of Lisp variable bindings and unwindprotects that are allowed before an error is signaled. This is one of the means by which Lisp avoids infinite recursion on an ill-defined function.

Variable max-lisp-eval-depth

The value of this variable is the limit on the depth allowed in calls to eval, apply, and funcall before an error is signaled. This is one of the means by which Lisp avoids infinite recursion on an ill-defined function. The default value is 200.

3.2 Forms

A form is any lisp object, but the term is normally used in the context of something that is to be evaluated rather than something that is used in an evaluation. (correct??) It is important to distingish between the input text representation (the read syntax) of some collection of forms and the forms which result from reading the text. The read syntax of lisp objects is described in an earlier chapter (see chapter 2 [Types of Lisp Objects], page 9). The read function itself is described in a later chapter (see section 16.1.1 [read], page 129). Here we are concerned with the evaluation of forms after they have been read.

A program in GNU Emacs Lisp consists of a set of forms that are evaluated in a well-defined fashion. Normally, a form is handed to the evaluator which proceeds to evaluate it in the current environment. Each form is a single Lisp object, and how it is evaluated depends on its type.

There are three kinds of forms to consider. A form can be a symbol, a list, or any other type, called a self-evaluating form. A form which is a list can, in turn, be one of three things: a function call, a macro call, or a primitive function call.

3.2.1 Self-Evaluating Forms

All forms that are not lists or symbols (i.e., numbers, characters, strings, vectors, buffers, etc.) evaluate to their internal representation. A special case is the empty list ‘()’ which evaluates to the symbol nil.

In the following examples, we use eval to explicitly evaluate a form that has been read in but not evaluated using quote. See section 3.1 [eval], page 23 and see section 3.3 [quote], page 30.

123
=> 123
(eval '123)
=> 123
(eval (eval '123))
=> 123
(eval '[1 2 3])
=> [1 2 3]

If you are new to Lisp, skip the rest of this subsection. It is normal to evaluate numbers, characters, strings, and occasionally vectors, by including them in Lisp code, but it is possible, though quite unusual, to evaluate any other Lisp object. For example, since buffers do not have a read syntax, the only way to evaluate them would be to build a form with a reference to a buffer in it and then evaluate the form.

(setq buf (list 'print (current-buffer)))   ; create a list with a buffer
in it
     => (print #<buffer evaluation.texinfo>)
(eval buf)
     -> #<buffer evaluation.texinfo>)
     => #<buffer evaluation.texinfo>)
(eval (eval buf))
     -> #<buffer evaluation.texinfo>)
     => #<buffer evaluation.texinfo>)

3.2.2 Symbol Forms

Symbols may be used to name variables. When a symbol is evaluated, the value of the symbol is looked up. First the stack is examined for any binding of the symbol. If one is found, the value it is bound to is returned as the result of the evaluation. There may be multiple bindings of the same symbol on the stack, but it is the most local binding that is returned.

If there is no binding on the stack and no specific unbinding created by makunbound, then if the value cell of the symbol is non-void, it is returned. If that cell is void (i.e., it does not contain a value), then a void-variable error is signaled. See chapter 9 [Variables], page 71 for more information on the binding of variables.

     (setq a 123)
     => 123
     (eval 'a)
     => 123

3.2.3 List Forms

When a list is evaluated, it is expected to be a primitive function call, a function call, or macro call. To determine which, the first element of the list is examined.

If the first element is a symbol, as it normally is, then the symbol’s function cell is examined. If the object referenced by the function cell is another symbol, the function cell of that symbol is examined, and used exactly as if it had been the original symbol. There is no limit to the number of levels of symbol indirection. If a function cell is void, the void-function error is signaled.

When an object is found that is not a symbol, it should be a primitive function, function, or macro which is used in a primitive function call, function call, or macro call respectively. If it is a list where the first element is the symbol autoload, then autoloading is attempted and, if successful, the newly loaded function object is used instead. See section 13.1 [autoload], page 114 to find out how autoloading is done. If the function cell is any other object, the invalid-function error is signaled.

In the unusual situation where the first element of the list is itself be a primitive function, function, macro, or autoload object, then that object is used in the same way.

If a list is recognized as a function or macro object because it begins with lambda or macro, and if the function or macro object is malformed, you are likely to get either a wrong-type-argument

error or wrong-number-of-arguments error.

(need better examples!!) In the example below, the symbol car is entered in to the function cell of first, and the symbol first is entered in to the function cell of erste.

     (fset 'first 'car)

     => car
     (fset 'erste 'first)
     => first
     (erste '(1 2 3))
     => 1

3.2.3.1 Function Calls

If a form is a list and the first element of the list is a function (directly or indirectly), then that form is called a function call. See section 10.1 [Lambda Expressions], page 84 for the definition of functions.

When a Function Call is evaluated, the elements of the rest of the list are first evaluated in the order they appear, then they are bound to the formal arguments of the function, and the function body is evaluated.

Although the arguments are always evaluated in order, it is poor programming style to rely on this fact to produce side effects. The two examples below will produce the exact same results. The second one is far superior.

     (list (setq x 1) (nth x '(cat rat mat)))
     => (1 rat)
     (progn (setq x 1)
            (list x (nth x '(cat rat mat))))
     => (1 rat)

3.2.3.2 Macro Calls

If a form is a list, and the first element of the list is a macro (directly or indirectly), then that form is called a macro call.

When a macro call is evaluated, the unevaluated elements of the rest of the list are bound to the formal arguments of the macro, and the body of the macro is evaluated. The macro then returns a new form as its result (called the macro expansion), and that form is then evaluated. Note that because the macro expansion is evaluated, if the macro expansion is a list and the first element of the list is a macro, evaluation of the list will result in another macro expansion. This recursive macro expansion will continue until max-lisp-eval-depth is exceeded.

It is important to note that the arguments are not evaluated when the macro is called, and a macro may or may not evaluate its arguments as it creates the form to be evaluated. See chapter 11 [Macros], page 91.

3.2.3.3 Primitive Function Calls

If a form is a list, and the first element of the list is a primitive function (directly or indirectly), then that form is called a primitive function call.

When a primitive function call is evaluated, the elements of the rest of the list are bound to the arguments of the primitive function and the primitive is executed. It is important to note that the arguments are not evaluated when the primitive function is called, although the primitive function itself may choose to evaluate some or all of them. Any primitive function which is not designated as a special form does, in fact, evaluate all its arguments.

3.2.3.4

Several primitive function calls are known as special forms since they define control structures or perform variable bindings which could not be defined via functions or macros. In order to be consistent with the usual concept of special form, most primitives will be described as “functions”, reserving the term “special form” for those few which are special forms by necessity.

quote See section 3.3 [quote], page 30 function See section 10.3 [function], page 89 defvar See section 9.2 [defvar], page 73 defconst See section 9.2 [defconst], page 75 defun See section 10.2 [defun], page 87 defmacro See section 11.2 [defmacro], page 93 let See section 9.3 [let], page 76 let* See section 9.3 [let*], page 77 setq See section 9.4 [setq], page 78

setq-default

See section 9.5 [setq-default], page 81

interactive

See chapter 17 [interactive], page 138 progn See section 12.3 [progn], page 99 prog1 See section 12.3 [prog1], page 99 prog2 See section 12.3 [prog2], page 100 while See section 12.4 [while], page 100 if See section 12.5 [if], page 101 cond See section 12.5 [cond], page 101 and See section 12.5 [and], page 102 or See section 12.5 [or], page 103 catch See section 12.6 [catch], page 103

unwind-protect

See section 12.6 [unwind-protect], page 105

condition-case

See section 12.7 [condition-case], page 108

with-output-to-temp-buffer

See section 26.7 [with-output-to-temp-buffer], page 253

save-excursion

See section 27.4 [save-excursion], page 265

save-window-excursion

See section 25.11 [save-window-excursion], page 248

save-restriction

See section 24.7 [save-restriction], page 233

   ________________

CN: setq, if, and catch are special forms in GNU Emacs Lisp and Common Lisp. defun is a special form in GNU Emacs Lisp, but a macro in Common Lisp. save-excursion is a special form in GNU Emacs Lisp, but doesn’t exist in Common Lisp. throw is a special form in Common Lisp (because it must be able to throw multiple values), but a function in GNU Emacs Lisp (which doesn’t have multiple values).

   ________________

3.2.3.5 Definitions and Declarations

A definition is a special form that establishes a relationship between a symbol and some value. There are four definition constructs in GNU Emacs Lisp.

defvar and defconst definitions both establish a symbol as a global variable. As declarations, they serve only to inform the person reading the code of the intended use of a symbol, and do not in any way affect whether the global value may be changed. defvar and defconst are documented in see chapter 9 [Variables], page 71.

defun and defmacro definitions create lambda and macro expressions respectively and bind them to the function cell value of the symbol being defined. defun and defmacro are documented in separate chapters (see chapter 10 [Functions], page 83 and see chapter 11 [Macros], page 91).

In GNU Emacs Lisp, declarations serve several purposes. First, they inform the user who reads the code that certain constructs (typically variables or functions) are intended to be used in the specified ways. Utilities such as etags and make-docfile can recognize these declarations also and add the appropriate information to tag tables and the ‘etc/DOC’ file. Second, they inform Lisp of the same thing, allowing it to ensure that the desired uses are made possible.

   __________

CN: In most Lisp systems, declarations supply information to the compiler, allowing it to output more optimal code than would otherwise be possible. The GNU Emacs Lisp compiler does not presently make use of any declarations to optimize code.

   __________

3.3 Identity and Quotes

Three functions are very similar to each other in that they all return the single argument unchanged. They differ in whether they evaluate their argument. Also, the byte compiler treats function specially. See section 10.3 [function], page 89 for the description of function.

Function identity object

This function returns object unchanged. Unlike quote, however, the argument is evaluated.

Special form quote object This special form simply returns object, without evaluating it. This allows symbols and lists, which would normally be evaluated, to be included in a program.

Because quote is used so often in programs, there is a special read syntax to reduce the amount of typing required. A single quote character ' followed by any form (white space is OK) is expanded to a quoted form. Thus 'foo is identical to (quote foo) as far as Lisp is concerned; indeed, it is stored as (quote foo) after it is read.

(quote (+ 1 2))  => (+ 1 2)
(quote foo)  => foo
'foo  => foo
(quote (quote foo))  => (quote foo)
''foo  => (quote foo)
['foo]  => [(quote foo)]
'[foo]  => [foo]
"'foo"  => "'foo"
'(\'foo)  => (\'foo)

32 GNU Emacs Lisp Reference Manual

4. Numbers

There is one kind of number in version 18 GNU Emacs Lisp, a small integer. In version 19, there is a compile time option to support floating point numbers (called floats) which are represented internally as double.

The range of values for a small integer depends on the machine. The range is -8388608 to 8388607 (24 bits) on many machines, but on others it is -16777216 to 16777215 (25 bits), or -33554432 to 33554431 (26 bits). All of the examples shown below will assume an integer has 24 bits. It is important to note that in GNU Emacs Lisp, arithmetic functions do not check for overflow. Thus (1+ 8388607) may equal -8388608 depending on your hardware.

The Lisp reader accepts numbers as a sequence of digits with an optional sign.

     1                ;The integer 1.
     +1               ;Also the integer 1.
     -1               ;The integer -1.
     16777217         ;Also the integer 1! (overflow)
     0                ;The number 0
     -0               ;The number 0
     1.               ;Invalid syntax

Many of the following functions on numbers will also accept markers as arguments (see chapter 28 [Markers], page 267). For a marker argument (named m-integer), the position value of the marker is used and the buffer of the marker is ignored. All of the functions for integers work for floats except where integers are specified.

4.1 Predicates on Numbers

Function integerp object

This predicate tests to see if its argument is an integer (number) and returns t if so, nil otherwise.

Version 19 has a floatp predicate.

Function zerop integer This predicate tests to see if its argument is zero, and returns t if so, nil otherwise. These two forms are equivalent: (zerop x) == (= x 0).

Function natnump object

This predicate (pronounced “Natural number-p”) tests to see if its argument is a nonnegative (i.e., natural) number, and returns t if so, nil otherwise. 0 is non-negative.

Markers are not converted, hence natnump of a marker is always nil.

4.2 Comparison on Numbers

Integers are implemented by storing the value in the “pointer part” of a Lisp object pointer (which has 24 bits of pointer, 7 bits of type and 1 bit for the garbage collector). Because of this fact, the function eq will return t for two numbers with the same value. See section 2.16.2 [eq], page 21.

________________

CN: In Common Lisp, there are many different types of numbers, many of which must be boxed; separate storage must be allocated for them. Because GNU Emacs Lisp does not need very large integers, and does not need any other types of numbers at all, it is possible to restrict them to the size of a single word, allowing eq to be used, where in Common Lisp = would be required.

________________

Function = m-integer1 m-integer2 This function tests to see if its arguments are the same number, and returns t if so, nil otherwise.

Function /= m-integer1 m-integer2 This function tests to see if its arguments are not the same number, and returns t if so, nil otherwise.

Function < m-integer1 m-integer2 This function tests to see if its first argument is strictly less than its second argument. It returns t if so, nil otherwise.

Function <= m-integer1 m-integer2 This function tests to see if its first argument is less than or equal to its second argument. It returns t if so, nil otherwise.

Function > m-integer1 m-integer2 This function tests to see if its first argument is strictly greater than its second argument. It returns t if so, nil otherwise.

Function >= m-integer1 m-integer2 This function tests to see if its first argument is greater than or equal to its second argument. It returns t if so, nil otherwise.

Function max m-integer &rest m-integers This function returns the maximum of its arguments.

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

Function min m-integer &rest m-integers This function returns the minimum of its arguments.

4.3 Arithmetic Operations

Function 1+ m-integer This function adds one to m-integer.

Function 1- m-integer This function subtracts one from m-integer.

Function + &rest integers This function adds its arguments together. When given no arguments, + returns 0. It does not check for overflow.

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

Function - &optional integer &rest other-integers 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, all the other-integers are subtracted from integer, cummulatively. If there are no arguments, the result is 0.

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

Function * &rest integers This function multiplies its arguments together. When given no arguments, * returns 1. It does not check for overflow.

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

Function / integer1 integer2 &rest other-integers This function divides integer1 by integer2. If there are more arguments, then they are each used to divide the previous result. The result is always rounded down after each division.

(/ 6 2)
     => 3
(/ 5 2)
     => 2
(/ 25 3 2)

          => 4

Function % integer1 integer2 This function returns the value of the integer1 modulo integer2. The sign of the result is the sign of integer1. The sign of integer2 is ignored.

It is an error if integer2 = 0.

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

4.4 Bitwise Operations on Integers

The following bitwise operations apply only to integers.

Function lsh integer1 integer2 lsh (logical shift) shifts the bits in integer1 to the left integer2 places, or to the right if integer2 is negative. If both arguments are negative, lsh shifts in zeros. See section 4.4 [ash], page 37

Function ash integer1 integer2 ash (arithmetic shift) shifts the bits in integer1 to the left integer2 places, or to the right integer2 is negative. This gives the same results as lsh except when integer1 and integer2 are both negative. In that case, ash shifts in the sign bit from the left, while lsh shifts in zeros.

                       ;         24-bit binary values
     (lsh 5 2)         ;For 5:   00000000 00000000 00000101
          => 20        ;For 20:  00000000 00000000 00010100
     (ash 5 2)
          => 20
     (lsh -5 2)        ;For -5:  11111111 11111111 11111011
          => -20       ;For -20: 11111111 11111111 11101100

(ash -5 2)
     => -20
(lsh 5 -2)        ;For 5:   00000000 00000000 00000101
     => 1         ;For 1:   00000000 00000000 00000001
(ash 5 -2)
     => 1
(lsh -5 -2)       ;For -5:  11111111 11111111 11111011
     => 4194302   ;For <-:  00111111 11111111 11111110
(ash -5 -2)       ;For -5:  11111111 11111111 11111011
     => -2        ;For -2:  11111111 11111111 11111110

Function logand &rest m-integers This function returns the “logical and” of the arguments: the nth bit is set in the result iff the nth bit is set in all the arguments.

If there is no argument, the result is -1.

For logand, logior, and logxor, if there is only one argument, that argument is the result. For two or more arguments, the operation is performed cummulatively with each additional argument.

                          ;       24-bit binary values
(logand 14 13)            ;14   = 00000000 00000000 00001110
                          ;13   = 00000000 00000000 00001101
     => 12                ;12   = 00000000 00000000 00001100
(logand 14 13 4)          ;14   = 00000000 00000000 00001110
                          ;13   = 00000000 00000000 00001101
     => 4                 ;4    = 00000000 00000000 00000100
(logand)
-1                        ;-1   = 11111111 11111111 11111111

Function logior &rest m-integers This function returns the “inclusive or” of it arguments: the nth bit is set in the result iff the nth bit is set in at least one of the arguments. If there is no argument, the result is 0.

                          ;       24-bit binary values
(logior 12 5)             ;12   = 00000000 00000000 00001100
                          ;5    = 00000000 00000000 00000101
     => 13                ;13   = 00000000 00000000 00001101
(logior 12 5 7)           ;12   = 00000000 00000000 00001100

                               ;5    = 00000000 00000000 00000101
                               ;7    = 00000000 00000000 00000111
          => 15                ;15   = 00000000 00000000 00001111

Function logxor &rest m-integers This function returns the “exclusive or” of its arguments: the nth bit is set in the result iff the nth bit is set in an odd number of the arguments. If there is no argument, the result is

0.

                               ;       24-bit binary values
     (logxor 12 5)             ;12   = 00000000 00000000 00001100
                               ;5    = 00000000 00000000 00000101
          => 9                 ;9    = 00000000 00000000 00001001
     (logxor 12 5 7)           ;12   = 00000000 00000000 00001100
                               ;5    = 00000000 00000000 00000101
                               ;7    = 00000000 00000000 00000111
          => 14                ;14   = 00000000 00000000 00001110

Function lognot integer This function returns the logical complement of its argument: the nth bit is set in the result iff the nth bit is not set in integer.

     (lognot 5)                ;5    = 00000000 00000000 00000101
          => -6                ;-6   = 11111111 11111111 11111010

4.5 Random Numbers

Function random &optional flag This function returns a pseudo-random 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.

All the possible values are equally likely.

If you want random numbers that are different each time you run Emacs, use (random t) at least once. This reinitializes the pseudo-random number seed based on the current time of day and on Emacs’ process ID number.

The sequence of numbers returned by random is the same in each Emacs run, unless you use (random t). For example, on one version of Sun Microsystems’ operating system, the first call to (random) after you start Emacs always returns -1457731, and the second one always returns -7692030. Therefore, programs that use random are repeatable, unless you call (random t). This is helpful when you are debugging.

5. Strings and Characters

Strings are implemented as arrays of characters, which in turn are eight-bit bytes. In addition to a big savings in space (8 bits per element vs. 32), strings are very convenient because of the way the Lisp reader and printer treat them, and because a large number of functions are written expressely for manipulating them.

The length of a string (like any array) is fixed, and cannot be altered. In particular, strings in Lisp are not nil-terminated as they are in C. Thus, the character ASCII 0 is a perfectly valid element of a string.

All of the array functions work for strings (see section 7.2 [Arrays], page 61), as do the sequence functions (see section 7.1 [Sequences], page 59). Functions that copy strings into buffers or display them are in the chapters on text. The syntax of characters and strings is described in the chapter on Data Types (see section 2.3 [Character Type], page 10 and see section 2.6.1 [String Type], page 13.

5.1 Predicates for Strings

See section 7.2.1 [arrayp], page 61 and see section 7.1 [sequencep], page 59.

Function stringp object

This function returns t if the object is a string, nil otherwise.

Function char-or-string-p object

This function returns t if the object is a string or character (i.e., an integer), nil otherwise.

5.2 Creating Strings

Many functions create a string as a result. Also see section 30.3 [string-match], page 297 which creates a string from the previous matched string.

Function make-string integer character This function returns a string made up of integer characters, all character.

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

Function substring string start &optional end This function returns a new string which consists of the characters from string, starting with character start (inclusive) and ending with character end (exclusive). A negative number counts from the end of the string, with -1 being the last character of the string.

It is an error unless both start and end are integers, or if start indicates a character following end, or if either integer is out of range for the string.

     (substring "abcdefg" 0)
     => "abcdefg"
     (substring "abcdefg" 0 2)
     => "ab"
     (substring "abcdefg" 5 nil)
     => "fg"
     (substring "abcdefg" -1 nil)
     => "g"

Function concat &rest sequences This function returns a new string consisting of the characters in the argument sequences. The arguments are not changed. The sequences may be lists, vectors, or strings.

A new string is always constructed which is not eq to any existing string. If no sequences are given, an empty string is returned.

It is a (wrong-type-argument) error unless all the elements of the sequences are characters or integers.

As a feature, in the special case where one of the sequences is an integer (not a sequence of integers), it is first converted to a string of digits making up the decimal print representation of the integer.

For other concatenation functions, see section 12.2 [mapconcat], page 99, see section 7.3 [vconcat], page 63, and see section 6.2 [append], page 51. copy-sequence

     (concat "abc" "-def")

=> "abc-def"
(concat "abc" -123 (list 120 (+ 256 121)) [122])
=> "abc-123xyz"
(concat)
=> ""

Function char-equal character1 character2 This function returns t if the arguments represent the same character, nil otherwise. The comparison is done modulo 256.

(char-equal ?x ?x)
=> t
(char-to-string (+ 256 ?x))
=> "x"
(char-equal ?x  (+ 256 ?x))
=> t

Function string= string1 string2 This function returns t if the characters of the two strings match exactly. Case is significent. See section 30.3 [string-match], page 297 for another way to compare strings. string= is

the same as string-equal.

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

Function string-lessp string1 string2 (@findex string< causes problems for permuted index) This function returns t if the first character of the two strings which is not identical has a lower ASCII value in string1 than string2. The string of no characters is the smallest string. (Lower case letters have higher ASCII values than their upper case counterparts.) This function is the same as string-

lessp.

(string-lessp "ABCC" "ABCD")
=> t
(string-lessp "ABCC" "ABCC")
=> nil
(string-lessp "ABC" "ABCC")
=> t

(string-lessp "abcc" "ABCD")
=> nil

5.3 Character and String Conversion

Characters and strings may be converted into each other and into integers. format (see section 5.3 [format], page 45) and prin1-to-string (see section 16.2.1 [prin1-to-string], page 134) may also be used to convert lisp objects into strings. read-from-string (see section 16.1.1 [read-from-string], page 129) may be used to convert a print representation of a lisp object into an object."

See chapter 21 [Documentation], page 193 for a description of the functions single-key-description and text-char-description which return a string representing the Emacs standard notation of the argument character. These functions are used primarily for on-line documentation.

Function char-to-string character

This function returns a new string of one character. The value of character modulo 256 is used.

(char-to-string ?x)
=> "x"
(char-to-string (+ 256 ?x))
=> "x"

Function string-to-char string

This function returns the first character in the string. If the string is empty, it returns 0, which is identical to the result if the string begins with the character ASCII 0.

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

Function int-to-string integer

This function returns a string consisting of the digits of integer, base ten. Positive integers will return strings that are unsigned, negative integers will return strings with a leading minus sign.

     (int-to-string 256)
     "256"
     (int-to-string -23)
     => "-23"

Function string-to-int string

This function returns the integer value of the characters in string, read as a number, base ten.

The string is read starting from the first character, and it is read until a non-digit is encountered. If the first character is not a digit, it returns 0.

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

Function format string &rest objects This function returns a new string that is made up from the characters in string with any conversion specification sequences replaced by the print representations for objects. Each of the conversion specifications is used in the order they are found with the corresponding object. Any extra conversion specifications will have unpredictable behaviour. Any extra objects will be ignored.

The character % begins a conversion specification. The characters following it indicate how the object should be represented.

‘s’ Replace the specification with the print representation of the object. If there is

no corresponding object, the empty string is used.

‘b’ Replace the specification with the base two representation of an integer. (But

it always looks like "b" to me!!)

‘o’ Replace the specification with the base eight representation of an integer. ‘d’ Replace the specification with the base ten representation of an integer. ‘x’ Replace the specification with the base sixteen representation of an integer. ‘c’ Replace the specification with the print representation of the character that the

object maps to. (what is this mapping??)

‘%’ A single % is placed in the string.

Any other conversion character results in an ‘Invalid format operation’ error.

All of these specification characters allow an optional numeric prefix (before the character) which defines the minimum number of characters that must be printed for the object. If the print representation of the object contains fewer characters than this, then it will be padded with spaces. The padding will be on the left if the prefix is positive and on the right if the prefix is negative. No matter what the prefix, nothing will be truncated. This allows the programmer to specify spacing exactly without knowing how many characters there are in the object’s print representation.

     (format "The length of %s is: %d" '(a b c) (length '(a b c)))
     "The length of (a b c) is: 3"
     (format "The %% character %c has value %d" ?x ?x)
     => "The % character x has value 120"
     (format "
     The numbers: %5d and %9d enjoy %9s good %6s, while
     the numbers: %5d and %9d enjoy %9s good %6s."
        1 97 'drinking 'wines -564 12399876 'eating 'food)
     => "
     The numbers:     1 and        97 enjoy  drinking good  wines, while
     the numbers:  -564 and  12399876 enjoy    eating good   food."

5.4 Character Case

The following three functions deal with changing the case of characters. They deal only with alphabetic characters (‘A-Z’ and ‘a-z’); any other characters are not converted. The argument is always copied.

The character examples below use the characters ‘X’ and ‘x’ which have ASCII values 88 and 120 respectively.

Function downcase string-or-char This function makes characters lower case. If string-or-char is a string, it creates a new string with each character in string-or-char, converted to lower case.

When string-or-char is a character, downcase returns the lower case of that character if it is a letter, or the character itself if not.

(downcase "The cat in the hat")
=> "the cat in the hat"
(downcase ?X)
=> 120

Function upcase string-or-char This function makes things upper case. If string-or-char is a string, it creates a new string with each character in string-or-char, converted to upper case.

When string-or-char is a character, upcase returns the upper case of that character if it is a letter, or the character itself if not.

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

Function capitalize string-or-char This function capitalizes things. If string-or-char is a string, it creates a new string with each word in string-or-char, capitalized. This means that the first character of each word is upper case and the rest are lower case.

The definition of a word is any sequence of consecutive characters that are assigned to the word category in the current syntax table (See section 37.3 [Syntax Tables], page 354). (is this relevant??)

When string-or-char is a character, capitalize returns the capital of that character if it is a letter, or the character itself if not.

(capitalize "The cat in the hat")
=> "The Cat In The Hat"
(capitalize "THE 77TH-HATTED CAT")
=> "The 77th-Hatted Cat"
(capitalize ?x)
=> 88

48 GNU Emacs Lisp Reference Manual

6. Lists

A cons cell in Lisp is a data object containing two pointers, a car pointer and a cdr pointer. A list is either the distinguished symbol nil (which denotes the empty list), or one or more cons cells linked together.

6.1 Predicates

Function consp object This function returns t if the object is a cons cell, nil otherwise. nil is not a cons cell.

Function atom object This function returns t if object is an atom, nil otherwise. Everything except cons cells are atoms.

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

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

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

Function nlistp object

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

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

Function null object This function returns t if object is nil. It returns nil otherwise. This function is identical to not, but by convention, null is used when object refers to a list, and not is used when it refers to a truth value.

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

6.2 Building Cons Cells and Lists

Many functions implicitely build lists, but they ultimately build lists from cons cells with cons (true??).

Function cons object1 object2 This function is the primary function used to build new lists. It creates a new cons cell, making object1 the car, and object2 the cdr. It then returns a pointer to the new cons cell. There is no requirement for object2 to be of any particular type, although it is normally a list.

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

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

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

Function make-list integer object This function creates a list of length integer, with each element being object.

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

Function append &rest sequences This function returns a list containing all the elements of sequences. All argments except the last one are copied, so none of them are altered. Note that an empty sequence contributes nothing to the result, but a final nil argument forces a copy of the previous argument.

As a feature, in the special case where one of the sequences is an integer (not a sequence of integers), it is first converted to a string of digits making up the decimal print representation of the integer.

The final argument may be any object but it is typically a list; it is not copied or converted. If no sequences are given, nil is returned.

See section 6.4 [nconc], page 54 for another way to join lists. And see section 7.1 [copy-sequence], page 59 for another way to copy sequences.

(setq x '(1 2 3))  => (1 2 3)
(append x '(4 5))  => (1 2 3 4 5)
x  => (1 2 3)
(eq x (append x nil))  => nil
(append nil x [4 5] "67" nil) => (1 2 3 4 5 54 55)
(append)  => nil

6.3 Accessing Elements of Lists

Function car list This function returns the first pointer of the cons cell, list. If list is nil, then car is defined to return nil. It is an error if the argument is not a list.

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

Function cdr list This function returns the second pointer of the cons cell, list. If list is nil, then cdr is defined to return nil. It is an error if the argument is not a list.

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

Function car-safe object

This function allows the programmer to call it on any argument without worrying about its type. It returns the car of object if object is a cons cell, nil otherwise.

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

Function cdr-safe object

This function allows the programmer to call it on any argument without worrying about its type. It returns the cdr of object if object is a cons cell, nil otherwise.

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

Function nth integer list This function returns the element of list indexed by integer, where the index of the first element is zero. If list has fewer than integer elements, nil is returned. If integer is less than zero, then the first element is returned.

(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))

Function nthcdr integer list This function returns the interger’th cdr of list. If integer is less than or equal to zero, then all of list is returned. If list has fewer than integer elements, nil is returned.

(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)

6.4 Alteration of List Structure

The car and cdr pointers of a cons cell are ultimately modified by setcar and setcdr. (true?? should we list them all.) See section 6.5 [delq], page 56 for another useful primitive that modifies cons cells.

Function setcar cons object This function replaces the car pointer of the cons cell with object. The result is object not cons.

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

Function setcdr cons object This function replaces the cdr pointer of the cons cell with object. The result is object not cons.

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

x
=> (1 4)

________________

CN: In Common Lisp, the functions rplaca and rplacd are similar to setcar and setcdr, but the Common Lisp functions return the cons cell while setcar and setcdr return the car or cdr.

________________

Function nconc &rest lists This function returns a list containing all the elements of lists. Unlike append, the lists are not copied; the last cdr pointer of each of the lists is changed to point to the next list. The final argument may be any object. See section 6.2 [append], page 51.

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

Function reverse list

This function creates a new list with the elements of list in reverse order. 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)

Function nreverse list

This function returns the elements of list in reverse order. Unlike reverse, however, list is destructively altered by changing its cdr pointers. The result is a pointer to the last cons cell of list, and thus list is not generally eq to its own nreverse.

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

=> (1 2 3 4)
(nreverse x)
=> (4 3 2 1)
x
=> (1)

Function sort list predicate This function sorts list, stably, comparing elements using predicate. It returns the sorted list.

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

sort maintains the original order of any two elements if the predicate indicates they are already in order.

sort alters list by changing cdr pointers. (If it only altered car pointers, the sorted list would eq the original list because only the elements (i.e. car pointers) would have changed.)

(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)

6.5 Using Lists as Sets

Lists may be used as mathematical sets by making use of memq and delq. But union, intersection, and other set related functions are not defined in GNU Emacs Lisp.

Function memq object list This function tests to see if object is a member of list. If it is, memq returns the tail of the list starting with the first occurence of object. Otherwise, it returns nil. memq tests with eq, hence the “q”.

(memq 2 '(1 2 3 2 1))
=> (2 3 2 1)

(memq '(2) '((1) (2)))
=> nil

Function delq object list This function removes all elements eq to object from list. It alters list unless the only occurence of object is as the first element(s) of the list (in which case delq simply returns the cdr(s) of list).

It returns the list without object. (This will be eq to list unless the first element is removed.)

(setq l '(1 2 3 (4)))
=> (1 2 3 (4))
(delq 1 l)
=> (2 3 (4))
l
=> (1 2 3 (4))
(delq 2 l)
=> (1 3 (4))
l
=> (1 3 (4))
(delq '(4) l)
=> (1 3 (4))

6.6 Association Lists

An association list, or alist for short, is a list of pairs (cons cells), where the car of each sublist is the key, and the cdr is the associated value. Association lists are often used to record information that one might otherwise keep on a stack since new pairs may be simply added to the front of the list.

A typical alist, with the symbol A associated with the number 1, and the number 5 associated with the list (2), looks like this:

((A . 1) (5 2))

When searching an association list for a pair with a given key, the first pair with that key is returned, even if there are several such pairs. The key may be any lisp object. It is not an error if an element of an association list is not a cons cell.

Function assoc key alist This function returns the first pair associated with key in alist. It returns nil if no pair in alist has a car equal to key.

(setq x '((a . 1) ((b) 2) (a . 99)))
=> ((a . 1) ((b) 2) (a . 99))
(assoc 'a x)
=> (a . 1)
(assoc '(b) x)
=> ((b) 2)

Function assq key alist Like assoc, this function also returns the first pair associated with key in alist. It returns nil if no pair in alist has a car eq to key. This function is used more often than assoc, since eq is faster than equal and most alists use symbols as keys.

(setq x '((a . 1) ((b) 2) (a . 99)))
=> ((a . 1) ((b) 2) (a . 99))
(assq 'a x)
=> (a . 1)
(assq '(b) x)
=> nil

Function rassq alist value rassq is like assq except that the cdr of the alist pairs is tested instead of the car. This function returns the first pair associated with value in alist. It returns nil if no pair in alist has a cdr eq to value.

(setq x '((a . 1) ((b) 2) (99 . 1)))
=> ((a . 1) ((b) 2) (99 . 1))
(rassq 1 x)
=> (a . 1)

Function copy-alist alist

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

(setq alist '((a . 1) (b (2))))
=> ((a . 1) (b (2)))
(setq copy (copy-alist alist))
=> ((a . 1) (b (2)))

(eq alist copy)
=> nil
(eq (car alist) (car copy))
=> nil
(cdr (car (cdr alist)))
=> ((2))
(eq (cdr (car (cdr alist)))
    (cdr (car (cdr copy))))
=> t

7. Sequences, Arrays, and Vectors

Two supertypes are described in this chapter, sequences and arrays. The primitive type, vector, is also described.

The sequence type is a supertype of three other Lisp types: lists, vectors, and strings. That is to say, lists, vectors, and strings are sequences. Common between all sequences is that each is composed of an ordered collection of elements.

The array type is a supertype of two other Lisp types: vectors and strings. An array is an ordered collection of elements in which each element is accessible in equal time. Thus, an array is a sequence with the additional property that the elements are accessible in equal time.

Note that the list type is included in the sequence type but it is not included in the array type because the elements of a list are not all accessible in equal time. In fact, the access time of an element of a list is proportional to its position in the list.

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

(a picture would help here!!)

7.1 Sequences

The sequence type is a supertype of three other Lisp types: lists, vectors, and strings. Common between all sequences is that each is composed of an ordered collection of elements.

Functions are provided to test whether an object is a sequence, to return the length of a sequence, to return an element of a sequence, and to return a copy of a sequence. The concat function (See section 5.2 [concat], page 42) can be used to copy several sequences of characters into a new string.

Function sequencep object

This function returns t if object is a list, vector, or string, nil otherwise.

Function copy-sequence sequence

This function returns a copy of sequence; a change to the copy does not affect the original. However, it copies only the top level of the sequence, not any deeper level. In other words, the elements of sequence and the corresponding elements of the copy will be eq to each other. The types of the copy and the original are the same. See section 6.2 [append], page 51 and see section 5.2 [concat], page 42 for others ways to copy sequences.

     (setq bar '(1 2))
          => (1 2)
     (setq x (vector 'foo bar))
          => [foo (1 2)]
     (setq y (copy-sequence x))
          => [foo (1 2)]
     (eq x y)
          => nil
     (equal x y)
          => t
     (eq (elt x 1) (elt y 1))
          => t

Function length sequence This function returns the number of elements in sequence. If sequence is a list, it is a wrong-type-argument error if the list does not end with nil.

Function elt sequence integer This function returns the element of sequence indexed by integer. This function duplicates the work of aref (see section 7.2.2 [aref], page 61) and nth (see section 6.3 [nth], page 52), but works for any sequence. The index of the first element of a sequence is zero.

It is an error if integer is less than zero or greater than or equal to the length of the sequence.

     (elt [1 2 3 4] 2)
          => 3
     (elt '(1 2 3 4) 2)
          => 3
     (char-to-string (elt "1234" 2))
          => "3"
     (elt [1 2 3 4] 4)
          -> ERROR: Args out of range: [1 2 3 4], 4
     (elt [1 2 3 4] -1)
          -> ERROR: Args out of range: [1 2 3 4], -1

7.2 Arrays

Arrays in Lisp, like arrays in most languages, are blocks of memory whose elements can be addressed by using an offset from the start of the array. All arrays are single dimensional and are zero-based (their first element is indexed with 0).

A vector is an array whose elements are pointers to any kind of Lisp object at all.

The elements of a string must be characters (i.e., integers between 0 and 255). Strings are covered in a separate chapter (see <undefined> [Strings], page <undefined>).

7.2.1 Predicates for Arrays

Function arrayp object

This function returns t if the object is an array (i.e., either a vector or a string).

(arrayp [a])
=> t
(arrayp "asdf")
=> t

7.2.2 Accessing and Changing Elements of an Array

Function aref array integer This function returns the integer’th element of the array (See section 7.1 [elt], page 60).

In the example, the character b is ASCII 98.

(setq primes [2 3 5 7 11 13])
=> [2 3 5 7 11 13]
(aref primes 4)
=> 11
(aref "abcdefg" 1)
=> 98

Function aset array integer object This function sets the integer’th element of the array to be object. It returns object. It is not an error if array is a string and object is not a character -???but it should be!!

(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)
=> foo
x
=> "asdZasfd"

Function fillarray array object This function fills the array with pointers to object, replacing any previous values. It is an error if the array is a string and object is not a character. 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 ?-)
=> "------------------"

7.3 Vectors

A vector is an array whose elements are pointers to any kind of Lisp object at all. See section 2.6.2 [Vector Type], page 14 for the syntax of vectors.

For example:

[1 two '(three) "four" [five]]
=> [1 two (quote (three)) "four" [five]]

Functions are provided to create vectors from other objects. The append function may be used to convert a vector into a list (see section 6.2 [append], page 51).

Function vectorp object

This function returns t if the object is a vector.

     (vectorp [a])
     => t
     (vectorp "asdf")
     => nil

Function vector &rest objects This function returns a vector made up from objects.

     (vector 'foo 23 [bar baz] "rats")
     => [foo 23 [bar baz] "rats"]
     (vector)
     => []

Function make-vector integer object This function returns a new vector made up of integer elements, all initialized to object.

     (make-vector 9 'Z)
     => [Z Z Z Z Z Z Z Z Z]

Function vconcat &rest sequences This function returns a vector consisting of all the elements of the argument sequences. The sequences may be lists, vectors, or strings.

A new vector is always constructed which is not eq to any existing vector (see the last example). If no sequences are given, an empty vector is returned.

As a feature, in the special case where one of the sequences is an integer (not a sequence of integers), it is first converted to the string of digits making up the decimal print representation of the integer. In the second example below, the number 123 is divided into three digits. The ASCII value for the character ‘1’ is 49.

For other concatenation functions, see section 12.2 [mapconcat], page 99, see section 5.2 [concat], page 42, and see section 6.2 [append], page 51.

(setq a (vconcat '(A B C) '(D E F)))
     => [A B C D E F]
(vconcat [A B C] 123 "45" '((6 7)))
     => [A B C 49 50 51 52 53 (6 7)]
(vconcat)
     => []
(eq a (vconcat a))
     => nil

8. Symbols

This chapter describes how symbols may be used, what the components of symbols are, and how symbols are created and interned. Property lists are also described here.

8.1 Symbol Components

A symbol has four components (or attributes or cells), each of which references another object.

The print name cell is described in the chapter Types of Lisp Objects (see section 2.7 [Symbol Type], page 15).

One essential aspect of symbols is that a symbol with a given print name is unique: no other symbol can have the same print name. The Lisp reader ensures that every time it reads a name, it looks for an existing symbol with that name before it creates a new one. (In GNU Emacs Lisp, this is done with a hashing algorithm that uses an obarray. See section 8.4 [obarray], page 68.)

The other three cells of a symbol can be made to reference any Lisp object what-so-ever. In normal usage, if the symbol is used as the name of a function, the function cell usually contains a reference to a function as that is what the Lisp Evaluator expects to see there. But see section 3.2.3.1 [Function Calls], page 27 for alternatives. Keyboard macros (see section 17.7 [Keyboard Macros], page 153) and keymaps (See chapter 18 [Keymaps], page 155) may also be stored in the function cell of symbols.

Likewise, the property list cell normally references a properly formatted property list (see section 8.5 [Property Lists], page 69, as a number of functions will expect to see a property list there. The value cell contains the symbol’s global value, if any, and that may be any Lisp object (see section 9.2 [Global Variables], page 73).

Quite often, we will refer to the function foo when we really mean the function referenced by the function cell of the symbol foo. Similarly for the value cell and property list cell. The distinction will only be made when necessary.

Here is a summary of the components of a symbol with where to find more information about the each component.

Name The string of characters used to identify the symbol when reading or printing.

Value The global value of a symbol. See section 9.4 [symbol-value], page 77. Function The function that will be applied if the symbol appears in the function position in a

form being evaluated, or as the first argument to funcall, apply, etc. This cell is also used by keymaps and keyboard macros. See section 10.3 [symbol-function], page 88.

Property List The list used by several functions to look up values that are associated with the symbol and a property symbol. See section 8.5 [symbol-plist], page 69.

8.2 Uses of Symbols

A symbol can have numerous uses in Lisp simultaneously.

• It can be used simply as a unique symbol, in which case it makes indirect use of the name cell.

• It can be used as a global variable, in which case the variable value is stored in the value cell.

• It can be used as a local variable, in which case the value is stored along with the symbol itself on the stack.

• It can be used to reference a function, in which case the function (or an indirect reference) is stored in the function cell.

• It can be used to reference a property list of global information.

When a symbol is used as a global variable, it is possible for it to be declared buffer-local (only when global??). In this case, the current buffer has a value for symbol that shadows the global value (see chapter 9 [Variables], page 71). In all of the functions discussed below, any reference to a “global” value should be read to mean the current buffer’s value for it, if that variable is “buffer-local” in the buffer.

8.3 Predicates on Symbols

Function symbolp object

This function returns t if object is a symbol, nil otherwise.

8.4 Creating and Interning Symbols

(Define uninterned symbol!! “symbol” means interned symbol.)

To understand how symbols are created in GNU Emacs Lisp, it is necessary to know how Lisp reads them. The essential thing is ensuring that every time Lisp reads the same set of characters, it finds the same symbol. Failure to do so would be disasterous.

Lisp reads in all the characters in a name. Then it hashes those characters into a vector called an obarray. Hashing is just an efficient method of looking something up. 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. There are a number of symbols that all hash to the same element in that array, that is, they hash to the same bucket, and Lisp just looks through them to see if one of them has the name in question.

If such a symbol is found, then it is returned. If no such symbol is found, then a new symbol is created and linked into the obarray at that point.

If a symbol is not linked into an obarray, then there is no way for Lisp ever to find it when its name is read. Such a symbol is called an uninterned symbol relative to the obarray. So it is possible for two different symbols to have the same name. It’s just not very common.

The functions below all take a name and sometimes an obarray as arguments. It is an error if the name is not a string, or if the obarray is not a vector.

Function symbol-name symbol

This function returns the string that is symbol’s name. Changing the name cell of a symbol will change the name of the symbol. Changing the string by substituting characters, etc, will also change the name of the symbol. Don’t do either of these things. Rather, create a new symbol with the desired name.

           (symbol-name 'foo)
           => "foo"

Function make-symbol name

Return a newly allocated uninterned symbol whose name is name (which must be a string). Its value and function definition are void, and its property list is nil. In the example below, the value of sym is not eq to foo because the string was not interned.

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

Function intern name obarray This function returns the symbol whose name is name. If obarray is supplied, it specifies the obarray to use; it defaults to the value of global variable obarray.

(setq sym (intern "foo"))
=> foo
(eq sym 'foo)
=> t

Function intern-soft name obarray

This function returns the symbol whose name is name, or nil if that symbol does not exist yet. If obarray is supplied, it specifies the obarray to use; it defaults to the value of the global variable obarray.

(intern-soft "frazzle")                ; No such symbol exists,
=> nil
(make-symbol "frazzle")                ; Create an uninterned one.
=> frazzle
(intern-soft "frazzle")                ; That one cannot be found.
=> nil
(setq sym (intern "frazzle"))          ; Create an interned one.
=> frazzle
(intern-soft "frazzle")                ; That one can be found!
=> frazzle
(eq sym 'frazzle)                      ; And it is the same one.
=> t

Variable obarray

This global variable is the standard obarray for use by intern and read. It is a vector whose length ought to be prime for best results (presently 511). Each element is an interned symbol whose name hashs to that bucket. That symbol (if any) has an internal link (invisible to the user) to the next symbol that hashes to that bucket. The order of these is unimportant.

Function mapatoms function &optional obarray This function applies function to every symbol in obarray. It returns nil. If obarray is not supplied, it defaults to the value of obarray; the normal obarray of all symbols.

(setq count 0)
     => 0
(defun count-syms (s)
  (setq count (1+ count)))
     => count-syms

           (mapatoms 'count-syms)
                => nil
           count
                => 1871

8.5 Property Lists

A property list (plist for short) is a list of paired elements stored in the property list cell of a symbol. Each of the pairs associate a property name (usually a symbol) with some property or value. Property lists are generally used to record information about a symbol, such as which file it received a function definition in, or the grammatical class the name of the symbol belongs to in a language understanding system. (more appropriate examples??)

Association lists (see section 6.6 [Association Lists], page 56) are very similar to property lists. But unlike association lists, the order in which the pairs of elements occur is not important since each property name can appear only once as a property name.

The property names (or keys) and property values may be any lisp objects. The property names are compared using eq.

Function symbol-plist symbol

Returns the property list of the symbol. A property list is a list in which the odd numbered elements are the property names and the even numbered elements are the properties or associated values. You should not use this function to get access to the property list for the purpose of altering it. (See example for setplist).

Function setplist symbol plist This function sets symbol’s property list to plist. plist should be a well-formed property list, although this condition is not checked for.

           (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)

Function get symbol key This function gets key from symbol’s property list. If symbol has such a key, the associated value is returned. If there is no such key, nil is returned. Thus, there is no distinction between an associated value of nil and the absense of the key. key is compared with the property names using eq, so any object is legitimate. See example for put.

Function put symbol key value This function puts value onto symbol’s property list under the property name key, replacing any previous value.

(Emacs oriented example needed here!! dml)

(put 'fly 'verb 'transitive)
=>'transitive
(put 'fly 'noun '(a nasty little bug))
=> (a nasty little bug)
(get 'fly 'verb)
=> transitive
(symbol-plist 'fly)
=> (verb transitive noun (a nasty little bug))

9. Variables

There are several varieties of variables in GNU Emacs Lisp. Global and local variables are similar to what is found in other versions of Lisp. GNU Emacs Lisp also has two kinds of bufferlocal variables.

9.1 Scope and Extent

Variables are defined to have what is called indefinite scope and dynamic extent. Scope refers to where in the code a variable can be accessed, extent refers to when. As this is an unusual aspect of GNU Emacs Lisp (Pascal, C, Algol, Fortran, etc. are all lexically scoped), it bears some comment.

Indefinite scope means that there are no limitations on which functions can access a given binding of a variable. A variable x, bound in a function fn1, might be accessable to a function fn2, even though the code for function fn2 is completely separate from that of fn1.

In the example below, it is not known if the function fn2 can access the variable x which is bound in function fn1. It would depend upon whether the function foo called fn2, and whether or not x was bound in the meantime. In a lexically scoped language, x would not be accessable in

fn2.
     (defun fn1 (x)
        (foo 5))
     (defun fn2 ()
       (list x))

If the definition of foo is: (defun foo (y) (fn2)), then fn2 will be able to access x. If it is: (defun foo (x) (fn2)), then fn2 will access the x bound by foo instead. (The x in foo is said to shadow the x in fn1.) Of course if fn2 is called directly instead of through fn1 or foo, then the use of x may well signal a void-variable error (assuming that it has been given no value elsewhere).

Extent refers to the time frame (relative to program execution) that a variable is valid. In GNU Emacs Lisp, as with most other languages, a local variable is valid only during that period of time that a form which binds it is executing.

One alternative of dynamic extent, called indefinite extent, means that it is possible for a form to define a function which can access the variables bound in that form, even after that form has exited. GNU Emacs does not support indefinite extent. In the example below, the function makeadd returns a function that purports to add n to its own argument m. In GNU Emacs Lisp, this will not work as intended, because after the call to make-add exits, the variable n is no longer valid. In some languages (such as Common Lisp) this is possible.

     (defun make-add (n)
         (function (lambda (m) (+ n m))))
     => make-add
     (setq add2 (make-add 2))
     => (lambda (m) (+ n m))
     (funcall add2 4)
     -> ERROR: Symbol's value as variable is void: n

Thus, it is the combination of scope and extent that define a variable’s accessability. The combination of dynamic extent and indefinite scope is called dynamic scope or dynamic binding. In GNU Emacs Lisp, dynamic scope translates nicely into a simple stack disipline: A local variable is bound on the stack. As long as a variable remains on the stack and as long as it is not shadowed by another variable with the same name, the evaluator can see it.

Good programming practice dictates that you should avoid using the fact that a variable bound in one function can be accessed in another function unless there is no other means to accomplish the goal.

A symbol which has a non-void value in its value cell is accessable by the evaluator within any form as a global variable, so long as the same symbol is not bound as a local variable.

Function boundp symbol

This function returns t if the symbol is not void; that is it has either a local binding or a global value. It returns nil otherwise. There is one counter-intuitive case involving makunbound. (See section 9.1 [makunbound], page 73)

           (boundp 'abracadabra)                ;Starts out unbound.
           => nil
           (let ((abracadabra 5))
                (boundp 'abracadabra))
           => t
           (boundp 'abracadabra)                ;Still globally unbound.
           => nil
           (setq abracadabra 5)
           => 5
           (boundp 'abracadabra)

=> t

Function makunbound symbol

This function sets the symbol’s value to be void (not the symbol void), causing any attempt to use this symbol as a variable to signal an error. If symbol is bound, it invalidates that binding, but does not allow any previous binding to be seen.

This function is normally only used to make global values unbound, and even that is quite rare. [You probably don’t want to use this function.]

(setq x 1)
     => 1
(makunbound 'x)
     => x
x
     -> ERROR: Symbol's value as variable is void.
(setq x 1)
     => 1
(let ((x 2))
  (makunbound 'x) x)
     -> ERROR: Symbol's value as variable is void.
(let ((x 2))
  (let ((x 3))
    (makunbound 'x)
    x))
     -> ERROR: Symbol's value as variable is void.
(let ((x 2))
  (let ((x 3))
    (makunbound 'x))
    x)
     => 2

9.2 Global Variables

Global variables are simply all symbols that have a value in their value cell (see chapter 8 [Symbols], page 65). Local bindings may shadow the global values. makunbound may make the value unavailable.

Special form defvar symbol [value [doc-string]] This special form informs the person reading the code that symbol is to be used as a variable which will not normally be locally bound. Typically symbol will be given a global value which is subject to change by various programs. symbol is not evaluated.

In addition to the above declaration, defvar performs some work.

When supplied with the optional arguments, defvar will evaluate the argument value and set the global value of symbol to the result if symbol is otherwise unbound. If symbol is bound, value will not even be evaluated.

If doc-string exists, it is put on symbol’s property list under the indicator (??) variabledocumentation, where the Emacs help system will look for it. If the first character of doc-string is *, then this variable is considered to be a user option, a variable that is commonly changed by the user. user-variable-p looks for it. doc-string is not evaluated.

defvar returns symbol as its value.

The first form below declares to the user that foo exists. This form does not set the value cell of foo. The second form sets the value of bar to 23, and gives it a documentation string. It is not a user option. The fourth form changes the documentation string for bar, making it a user option, but does not change the value (the addition (1+ 23) is not even performed!).

     (defvar foo)
     => foo
     (defvar bar 23 "The normal weight of a bar.")
     => bar
     (user-variable-p 'bar)
     => nil
     (defvar bar (1+ 23) "*The normal weight of a bar.")
     => bar
     bar
     => 23
     (user-variable-p 'bar)
     => t

The forms below show what defvar is equivalent to.

(defvar symbol value doc-string)

     ==

     (progn
       (if (not (boundp 'symbol))

(setq symbol value))

       (put 'symbol 'variable-documentation 'doc-string)

'symbol)

Function user-variable-p variable

This function returns t if variable is intended to be set and modified by users, as opposed to by programs. This function just looks at the first character of the documentation string for variable. If this character is ‘*’, then the result is t, otherwise the result is nil.

Special form defconst symbol [value [doc-string]] This special form informs the person reading the code that symbol will not normally be locally bound or changed by the execution of the program (as opposed to variables that are declared by defvar). Typically, symbol will be given a global value which should not be subject to change by any programs although the user may still change it.

In addition to the above definition, defconst performs some work.

defconst will evaluate the argument value and set the global value of symbol to the result. symbol is not evaluated.

If doc-string exists, it is put on symbol’s property list under the indicator variabledocumentation, where the Emacs help system will look for it. If the first character of doc-string is ‘*’, then this variable is considered to be a user option. user-variable-p looks for it. doc-string is not evaluated.

defconst returns symbol as its value.

In the first form below, indent-depth is a constant (programs ought not alter its value), but it is a user option so it’s OK for the user to change it. In the second example, pi is a constant which should never be changed. However, as the third form illustrates, this is only advisory and Lisp won’t stop a program from ignoring the advice.

     (defconst indent-depth 4 "*Indent code this many spaces per level.")
     => indent-depth
     (defconst pi 3 "Pi to one place.")
     => pi
     (defconst pi 4 "Pi to one place, very inaccurately.")

     => pi
     pi
     => 4

9.3 Binding Local Variables

The local variable bindings may be viewed as being implemented as an association list: a list of pairs ((variable . value) ...). When a new binding is added to the front of the list, bindings for the same variable further down on the list will not be seen. When the form which created the binding is exited, the previous binding will again be seen. When there is no local binding, the global value will be seen.

Forms which bind local variables are function calls (see chapter 10 [Functions], page 83), macro calls (see chapter 11 [Macros], page 91), and the special forms let, let* and condition-case (see section 12.7 [condition-case], page 108). (others??)

Special form let binding-list forms* This function binds variables according to binding-list and then evaluates all of the forms in forms in sequence. let returns the value of the last form in forms.

Each element of binding-list is either a symbol (in which case it is bound to nil), or a list of the form (symbol value-form) (in which case let binds symbol to the result of evaluating value-form).

If the let form is exited before the forms are all evaluated, then the local bindings of symbols is removed.

All of the value-forms are evaluated in the order they appear (can we rely on this??) and before any of the symbols are bound. In the example, Z is bound to the old value of Y, which is 2, not the new value.

     (setq Y 2)
     => 2
     (let (X
           (Y 1)
           (Z Y))
       (list X Y Z))
     => (nil 1 2)

Special form let* binding-list forms* This special form is the exact analog to let, except that each symbol of the binding-list is bound in the order given before the remaining symbols are bound. Therefore an expression in the binding-list may refer to symbols already bound by this binding-list. Compare the following example with the example for let.

     (setq Y 2)
     => 2
     (let* (X
            (Y 1)
            (Z Y))
       (list X Y Z))
     => (nil 1 1)

9.4 Referencing and Changing the Value of Symbols

The normal way to reference a variable is to write the symbol which names it, in a form to be evaluated. The following constructs provide other ways to reference and change the value and function cells of symbols.

Function symbol-value symbol

This function returns the value of the symbol. This is the most local binding of the symbol, or its global value if it is not otherwise bound.

It is an error if the symbol has neither a binding nor a global value.

     (setq abracadabra 5)
     => 5
     (let ((abracadabra 'foo))
          (symbol-value 'abracadabra))
     => foo
     (symbol-value 'abracadabra)
     => 5

Function set symbol object This function sets symbol’s value to object. As set is a function, symbol is evaluated, and the value returned (which must be a symbol) is set to object. As usual, it is the most local binding of the variable that is set.

(set one 1)
-> ERROR Symbol's value as variable is void: one
(set 'one 1)
=> 1
(set 'two 'one)
=> one
(set two 2)                ;two evaluates to one, hence one's value
=> 2                       ;gets set to 2.
one
=> 2
(let ((one 1))             ;This binding of one is set,
     (set 'one 3)          ;not the global value.
     one)
=> 3
one
=> 2

__________

CN: In Common Lisp, set will always operate on the global environment, changing the symbol’s global value and never a local binding. This is not the case with GNU Emacs Lisp

__________

Special form setq [symbol object]* This special form is the most common method of changing a symbol’s value. For each symbol, it does not evaluate symbol, but sets the value (either the local binding or, if none, the global value) of that symbol to the result of evaluating object. If there is more than one symbol-object pair, the setting is done in sequence and the value of the last object is returned.

(setq x (1+ 2))
=> 3
(setq x 10
      y (1+ x))                     ;Notice that x gets set before
y
=> 11                               ;and y uses that value.
(let ((x 5))
  (setq x 6)
  x)                                ;The local binding of x gets set.
=> 6
x                                   ;The global value is unchanged.
=> 11

9.5 Buffer Local Variables

A problem unique to Emacs is that it is very often useful to have different values for variables in different buffers. This is accomplished by declaring a variable to be buffer-local. When this is done, that variable takes on a value for the current buffer which is not affected by what happens to that variable when a different buffer is current.

There are two varieties of buffer-local variables. make-local-variable makes a variable local to the current buffer whereas make-variable-buffer-local makes a variable local to every buffer, even new buffers that are created afterwards. The latter will be called per-buffer-local variables when it is necessary to distinguish them from buffer-local variables. (terminology!!) A per-buffer-local variable is buffer-local in every buffer.

When a variable that is buffer-local in the current buffer is changed with set or setq (others?? set-variable let defun) the value that other buffers see is not changed.

(What happens if both are used for a single variable?? What happens if the variable is locally bound before or after it becomes buffer-local??)

The default value of a buffer-local variable is the value that is seen by buffers that have not made the variable buffer-local (in the case of make-local-variable) or have not yet set the variable’s value (in the case ofmake-variable-buffer-local). The default value may be specifically changed

with set-default or setq-default.

(The actual implementation of buffer-local variables involves a shallow binding scheme where the local values are substituted into the global value cell each time a different buffer is selected. This makes switching buffers more expensive, but evaluating variables much less so.)

Function buffer-local-variables &optional buffer

This function builds an association list in which each pair in the list is a buffer-local variable and its value. If buffer is not given, the current buffer is used. Note that changing the values in this list will not change the local value of the variable.

           (setq lcl (buffer-local-variables))
           => ((fill-column . 75)
               (case-fold-search . t)
               ...
               (mark-ring #<marker at 5454 in buffes.texinfo>)
               (require-final-newline . t))

Command make-local-variable symbol

This function makes symbol have a separate value in the current buffer. The current value of the variable will remain as the default value for other buffers that have not made the variable buffer-local.

When called interactively, symbol is prompted for in the minibuffer.

Command make-variable-buffer-local symbol

This function makes symbol a buffer-local variable for every buffer, even new buffers. When make-variable-buffer-local is called, the current value of symbol becomes the default value seen by any buffer that does not have its own buffer-local value. If you change the variable value, this causes it to have a separate value for the current buffer if it was previously using the default value.

The result is symbol.

;;In buffer A
(setq foo 5)
=> 5
(make-variable-buffer-local 'foo)
=> foo
foo
=> 5
(setq foo 6)
=> 6
;;In buffer B, the value hasn't changed.
foo
=> 5
;;Now, change the default value (but not the value in A).
(setq-default foo 9)
=> 9
foo
=> 9

Function kill-all-local-variables

This function eliminates all the buffer-local variable values of the current buffer. This buffer will then see the default values of all variables. It does not change the buffer-local status of any variables.

Command kill-local-variable symbol

This function makes symbol no longer have a separate value in the current buffer. From now on the default value will apply in this buffer.

When called interactively, symbol is prompted for in the minibuffer.

Special form setq-default [symbol value]* This function sets the default value of each of the symbol’s to the respective value. symbol is not evaluated and value is. It returns the first value.

The default value is seen in buffers that do not have their own buffer-local values for this variable.

If a symbol is not buffer-local for the current buffer, this will be just like setq in the current buffer. If symbol is buffer-local for the current buffer, then this will set the value other buffers will see (if they don’t have a buffer-local value yet), but not the value that the current buffer sees.

(make-variable-buffer-local 'local)
=> local
;; In buffer foo:
(setq local 'foo)
=> foo
;; In buffer bar:
local
=> nil
(setq-default local 'default)
=> default
local
=> default
(setq local 'bar)
=> bar
;; In buffer baz:
local
=> default
;; In buffer foo:
(setq local 'foo)
=> foo
(default-value 'local)
=> default

Function set-default symbol value

This function is like setq-default except only one symbol and one value are allowed and both are evaluated. (see setq-default.)

     (set-default (car '(a b c)) 23)
     => 23

Function default-value symbol

Return symbol’s default value. This is the value that is seen in buffers that do not have their own values for this variable. (See section 9.5 [setq-default], page 81) If symbol is not buffer-local, than this will be the same as symbol-value.

Function hack-local-variables &optional force

SourceFile files.el Parse, and bind or evaluate as appropriate, any local variables for current buffer. See chapter 22 [Files], page 199 for the syntax of the hack-local-variables section of a file.

10. Functions

The Lisp language that GNU Emacs uses is, like all Lisp languages, comprised mainly of a set of functions and variables. This chapter is concerned with the definition and manipulation of functions in the Lisp language and their relationship to editing commands.

Functions in GNU Emacs Lisp can be defined in one of two basic ways; they cn be primitives written in C, or they can be defined in Lisp. The C-coded functions, of which there are approximately 500 defined, provide the very lowest-level interfaces to editing functions or operating system services, or in a very few cases, to perform certain operations more quickly than they could be performed in Lisp. These can only be modified by rewriting them and recompiling the editor. This is a fairly complex process, and will be described at the end of this chapter.

The other method, which is the standard method for writing extensions to the editor, is to write new functions in Lisp. If you have ever programmed other versions of Emacs you will find writing code for GNU Emacs very pleasant; the Lisp provided is a true version of Lisp, and functions that are used as commands do not require any terribly arcane calling sequence.

It will be helpful to define a few terms first, as the meanings of a few terms used here differ from the common definitions.

Primitive A primitive is a function callable from Lisp that is written in C, such as car and cdr. These are sometimes called built-in functions or subrs.

Function A function in general is anything that can be called in Lisp code. In this manual, function will normally be used to mean code written in Lisp. But the term is also used to refer to primitives, special forms, and macros. (should Function be used that way?? dml we need a consistent naming scheme!!)

Command A command is something that is advertised to the user and can be invoked by the user either by M-xcommand-name or by means of a keystroke. From the programmer’s point of view, it is a function with an interactive specification (see interactive, below).

Keystroke Command A keystroke command is a command that can be executed with a short key sequence, as opposed to a command that is not bound to a key sequence. The distinction is made here merely to avoid confusion with the meaning of command in non-Emacs editors; for programmers, the distinction is normally unimportant.

10.1 Lambda Expressions

Since many people have not programmed in Lisp before, it may be helpful to review just what a function is before discussing some of the particular facilities provided for manipulating functions. If you are a Lisp programmer, you can skim this section, but there are some points that are specific to the GNU Emacs Lisp language.

A Lisp function is a list that looks like this:

(lambda args documentation body) (This sort of Lisp expression is known as a lambda expression for mainly historical reasons.) The first element of this list is the symbol lambda; the second element of this list is a list of

arguments; the third element is an optional string documenting the function, and all other elements of the list comprise Lisp code to execute, or, as a Lisp programmer would say, “are a list of Lisp forms to evaluate”. The value returned by the function is the value returned by the last element of the body.

The list of arguments, called the lambda-list, is a list of variable names. When a lisp function is called, the arguments provided are matched up against the names in the lambda-list, and those variables are bound to the values provided.

Thus, if the function foo looked like this:

     (lambda (a b c) "Test" (+ a b c))

and was called as follows:

     (foo 1 2 3)

foo would be evaluated with the variable a bound to 1, b bound to 2, and c bound to 3. Note that the arguments could have been the results of other functions; i. e.

     (foo 1 (* 2 3) (- 5 4))

all the arguments to foo (1, (* 2 3), and (- 5 4)) would be evaluated, left to right. Then foo would be applied to these arguments.

Functions are often associated with the symbols used to name them. For example, foo is a symbol, but we will regularly refer to the function foo, meaning the function which that symbol’s function cell normally points to.

The function call in our example here must provide all three arguments to the foo function. If you attempted to call foo with only two arguments, you would get a Lisp error. However, it is often convenient not to have to specify certain arguments, allowing them to default in some way, such as the function rmail, which will default to a predetermined filename if not passed a specific filename. It is also convenient to be able to provide an indefinite number of arguments; functions such as and, or, and + fall into this category.

To specify optional arguments that may or may not be given when a function is called, simply include the keyword &optional before the optional arguments. To specify a list of zero or more extra arguments, include the keyword &rest before one final argument.

The complete syntax for a lambda-expression is:

(lambda (required-vars* [&optional optional-vars*] [&rest rest-var]) [documentation-string] [interactive-declaration] forms*)

The &optional and &rest clauses with the associated variables are optional. A function call requires one actual argument for each of the required-vars. There may be actual arguments for zero or more of the optional-vars, and there cannot be any more actual arguments than these unless &rest exists. In that case, there may be any number of extra actual arguments. If actual arguments are not supplied for the optional and rest variables, then they always default to nil.

   ________________

CN: This is different from Common Lisp, where default values can be supplied for the optional parameters.

   ________________

For example, a lambda-list that looks like this:

     (a b &optional c d &rest e)

binds a and b to the first two actual arguments, which are required. If one or two more arguments are included, c and d are bound to them respectively; any arguments after that are collected into a list and e is bound to that list. After the arguments provided by the caller are used up, any remaining optional or rest variables are bound to nil.

All variables after the &optional are for optional arguments, and only one variable is meaningful after &rest. To see why this must be so, suppose that c in the example were optional and d were required. If three actual arguments are given; then what should be bound to the third argument? Similarly, multiple &rest variables have no meaning.

One minor problem with this is that if the last argument provided is nil, and it is an optional argument, then the function cannot tell if the argument was provided or not.

Returning to the syntax of the lambda-expression, the documentation-string is completely optional as far as the language is concerned; if provided, it is a literal string that is used by a few functions for the user’s benefit. It is a good idea to provide documentation strings for all commands and functions, and it should explain what the function does and all its arguments in order.

You may wonder how the documentation string could be optional, since there are required components of the function that follow it (the body). Since evaluation of a string returns that string, without any side effects, it has no effect if it is not the last form in the body. Thus, in practice, there is no confusion between the first form of the body and the documentation string; if the only body form is a string then it serves as both the return value and the documentation.

The interactive-declaration, if it exists, is a form (interactive code-string), declaring that it is possible for the function to be used interactively. Functions with this declaration are called commands (See chapter 17 [Commands], page 137).

The rest of the function definition is simply a list of lisp forms to be evaluated in order, and the value of the last form is returned as the result of the function call.

More examples of the use of lambda:

     ((lambda (n) (1+ n))                ;One parameter:
      1)                                 ;requires exactly one argument
     => 2
     ((lambda (n &optional n1)           ;One parameter and one optional:
              (if n1 (+ n n1) (1+ n)))   ;1 or 2 arguments.
      1 2)

=> 3
((lambda (n &rest ns)                ;One parameter and &rest:
   (+ n (apply '+ ns)))        ;1 or more arguments.
1 2 3 4 5)
=> 15

10.2 Function Declarations

Special form defun symbol parameter-list forms* defun is the usual way of defining new lisp functions. defun defines symbol to be the name of a function which the rest of the form represents. It does this by setting the function cell of that symbol to point to the lambda-expression it creates from parameter-list and forms: (lambda parameter-list . forms). The same symbol may also be used as a global variable since the value cell is independent of the function cell.

As described above, the first two forms in forms may be a documentation string and a declaration. defun takes no precautions about redefining functions, and will even redefine primitives such as car without any notification. defun returns symbol as its value.

(defun foo () 5)
=> foo
(foo)
=> 5
(defun bar (a &optional b &rest c)
    (list a b c))
=> bar
(bar 1 2 3 4 5)
=> (1 2 (3 4 5))
(bar 1)
=> (1 nil nil)
(bar)
-> ERROR: Wrong number of arguments.
(defun capitalize-backwards ()
    "This function makes the last letter of a word upper-case."
    (interactive)
    (backward-word 1)
    (forward-word 1)
    (backward-char 1)
    (capitalize-word 1))
=> capitalize-backwards

10.3 Manipulating Symbols’ Function Cell

Function subrp object This function returns t if object is a built-in function.

Function symbol-function symbol

Returns the object in the function cell of the symbol. It is an error if the symbol’s function cell is void, although it does not check to verify that the object is a legitimate function.

(defun bar (n) (+ n 2))
=> bar
(symbol-function 'bar)
=> (lambda (n) (+ n 2))
(fset 'baz 'bar)
=> bar
(symbol-function 'baz)
=> bar

Function fboundp symbol

Returns t if the symbol has some value (any non-void object) in its function cell, nil otherwise. It does not check to verify that the value is a legitimate function.

Function fmakunbound symbol

This function sets the symbol’s function pointer to be “void” (not the symbolvoid), causing any attempt to access this cell to be an error. (Also see section 9.1 [makunbound], page 73)

Function fset symbol object This function sets the symbol’s function cell to be object. object is assumed to be a function or the name of one, but this is not checked. object is returned. The normal use is for copying one symbol’s function definition to another. Note that fset stores the object itself in the symbol’s function cell.

(fset 'first (symbol-function 'car))
=> #<subr car>
(first '(1 2 3))
=> 1
;; Or:
(fset 'first (function car))
=> car

(first '(1 2 3))
=> 1
(symbol-function 'first)
=> car

Special form function object

function is identical to quote in interpreted code: it returns the object without evaluating it. The byte complier knows, however, that object is intended to be used as a function, and produces superior code than would be obtained by using quote for this purpose. Both examples below will work but the first is more efficient. See section 3.3 [quote], page 30 for comparison.

(need better example!! this one doesnt look right)

(function car)
     => car
(defun foo (x)
  (funcall (function car) x))                ; faster
     => foo
(byte-compile 'foo)
     => (lambda (x) (byte-code "ABK\" " [x funcall car] 4))
(defun foo1 (x)
  (funcall (quote car) x))                   ; slower
     => foo1
(byte-compile 'foo1)
     => (lambda (x) (byte-code "AB\" " [x funcall car] 3))

10.4 Other Function Related Functions

Here is a table of several other function related functions and where they are described.

apply see section 12.1 [apply], page 98

funcall see section 12.1 [funcall], page 97

eval see section 3.1 [eval], page 23

mapatoms see section 8.4 [mapatoms], page 68

mapcar see section 12.2 [mapcar], page 98

mapconcat

see section 12.2 [mapconcat], page 99

documentation

see chapter 21 [documentation], page 193

interactive

see chapter 17 [interactive], page 138

call-interactively

see chapter 17 [call-interactively], page 137

interactive-p

see chapter 17 [interactive-p], page 140

commandp see chapter 17 [commandp], page 137 autoload see section 13.1 [autoload], page 114 ignore see section 18.1 [ignore], page 156

undefined

see section 18.1 [undefined], page 157

identity see section 3.3 [identity], page 30

11. Macros

Macros are Lisp forms which do not compute the desired results themselves, but rather they create more complex forms that will produce those results. When Lisp encounters a macro, it evaluates the body of the macro to obtain the more complex form. It then evaluates that form to obtain the desired results.

As an example of a place where one would like to use a macro, consider the following: It is quite often the case in that we have a variable that we are using for counting something, and we wish to increment it. C has the construct x++ to save the programmer from writing x = x + 1;. GNU Emacs Lisp has nothing like this, so we have to write (setq x (1+ x)) all the time.

To alleviate this problem, we could write a macro that would allow us to write (inc x), which would simpler and shorter. Here is a macro to do exactly that:

     (defmacro inc (var)
        (list 'setq var (list '1+ var)))

When called as (inc x), this macro computes a list (setq x (1+ x)), which is exactly the form which we want to evaluate in order to obtain the proper result. Lisp does evaluate it and we get the desired result, that of incrementing the variable.

The execution of a macro form proceeds like this: The arguments of the form are passed to the macro unevaluated. The macro then binds them to its parameters and executes its body. The expression returned by the macro is is called the expansion. The expansion is then evaluated by Lisp as if that had been the form originally given.

Since the returned expression is evaluated normally, there is nothing preventing it from containing calls to other macros. Even recursive macro calls are legitimate (if unusual).

A byte compiled macro call is expanded at compile time rather than at run time. So a byte compiled macro call is faster than a function call which performs the same operation. But be careful that the macros are defined before they are called in byte compiled code. If there is a circular dependency in your macro definitions, it may be simplest to cause the file of definitions to be loaded first.

Here is a more complex example of a macro that might be written to facilitate interation:

(defmacro for (var from init to final do &rest body)
  "Execute a simple \"for\" loop, e.g.,
    (for i from 1 to 10 do (print i))."
  (list 'let (list (list var init))
        (cons 'while (cons (list '<= var final)
                           (append body (list (list 'inc var)))
                           ))))
=> for
(for i from 1 to 3 do
   (setq square (* i i))
   (princ (format "\n%d %d" i square)))
==> (let ((i 1))
      (while (<= i 3)
        (setq square (* i i))
        (princ (format "%d      %d" i square))
        (inc i)))
->
1       1
2       4
3       9
=> nil

This macro allows us to write a simple “for” loop such as one might find in Pascal. Notice that the symbols from, to, and do are all “syntactic sugar” in this macro; they are entirely ignored.

However, this macro suffers from the deficit that final is evaluated on every iteration. If final is a constant, there’s no problem. If it had been a more complex form, say (long-complex-calculation x), it could have slowed down the execution significently. If it had produced side effects, it could have been disasterous.

In writing macros then, one has to be cautious and ensure that the arguments are not going to be evaluated more times than the programmer expects. A better expansion for the for macro would be:

(let ((i 1)
      (max 3))
  (while (<= i max)
    (setq square (* i i))
    (princ (format "%d      %d" i square))
    (inc i)))

where max is an uninterned symbol (See section 8.4 [intern], page 68).

(Show how we can produce this expansion.!!)

11.1 Predicates for Macros

There are no predicates explicitly provided for macros. However, you can test whether a symbol has a non-void function cell with fboundp. Here is a function which tests whether its argument is a macro.

(defun macrop (form)
 "Return true if FORM function is a lisp macro."
 (while (and (symbolp form) (fboundp form))
   (setq form (symbol-function form)))
 (and (listp form)
      (eq 'macro (car form)))
 )

11.2 Functions for Macros

Special form defmacro symbol arglist [docstring] body* In a fashion similar to defun, this defines a macro. symbol has its function cell changed to point to the macro created. The macro is created with arglist and the forms in body.

symbol is returned as the value.

It is an error unless arglist is a list of symbols (actually, the form of arglist will only be checked when the macro is executed, so it is possible to type it in incorrectly). Macros cannot be called interactively.

If you must explicitly evaluate an argument of a macro (using eval, for example), be careful to arrange that the actual argument does not use the names of any of the macro’s formal arguments or any variables declared in let constructs unless it is intended that the values of those local variables should be used instead of any previous values.

When you byte compile (see chapter 14 [Byte Compilation], page 117) a file that makes use of macros, be sure that the macros are defined before any forms are evaluated that use the macros. Also, symbols used within macros are expanded to their values at byte-compile time, so you cannot use dynamic binding. (is this correct??)

Function macroexpand form

This function looks at the car of form. If it is a macro, macroexpand will return the expanded form. macroexpand expands its forms recursively, so that if the car of the form obtained is also a macro, that too will be expanded. However, arguments (subexpressions) which are macro forms will not be expanded.

This procedure for the expansion of a macro is similar to that used to expand a macro in a macro call. So you may use of macroexpand to test what a macro call will expand into. The exceptions are that there is no limit on the number of recursive macro expansions and local bindings of indirection symbols are used rather than only the function cell of a symbol. (is this intentional??) See section 3.2.3.2 [Macro Calls], page 27

     (defmacro inc (var)
         (list 'setq var (list '1+ var)))
     => inc
     (macroexpand '(inc r))
     => (setq r (1+ r))
     (defmacro inc2 (var1 var2)
         (list 'progn (list 'inc var1) (list 'inc var2)))
     => inc2
     (macroexpand '(inc2 r s))
     => (progn (inc r) (inc s))        ; inc not expanded here..

11.3 Backquote

It can prove rather awkward to write macros of significent size, simply due the number of times the function list needs to be called. The for example above has about the maximum depth of lists that is legible. To make writing these forms easier, a macro ` (pronounced backquote) exists.

Backquote allows you to quote a list, but selectively evaluate elements of that list. In its simplest form, it is identical to the special form quote. In the example below, the two forms yield identical results.

(` (a list of (+ 2 3) elements))

=> (a list of (+ 2 3) elements)
(quote (a list of (+ 2 3) elements))
=> (a list of (+ 2 3) elements)

By inserting a special marker (,) inside of the argument to backquote, it is possible to evaluate those portions of the argument desired:

(list 'a 'list 'of (+ 2 3) 'elements)
=> (a list of 5 elements)
(` (a list of (, (+ 2 3)) elements))
=> (a list of 5 elements)

It is also possible to have an evaluated list spliced into the resulting list (as opposed to being an element of it) by using the special marker ,@.

(cons 1 (list (+ 1 1) (+ 1 2)))
=> (1 2 3)
(` (1 (,@ (list (+ 1 1) (+ 1 2)))))
=> (1 2 3)

;; A nastier example:

(cons 'a
  (cons 'list
    (cons 'of (append (list (+ 2 3)) '(elements)))))
=> (a list of 5 elements)
(` (a list of (,@ (list (+ 2 3))) elements))
=> (a list of 5 (elements))   ?????
=> (a list of 5 elements)

Our for macro could therefor be rewritten more clearly as:

(defmacro for (var from init to final do &rest body)
  "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  (` (let (( (, var) (, init) ))
       (while (<= (, var) (, final))
              (,@ body)
              (inc (, var))
              ))))
=> for

Macro ‘ list This macro returns list as quote would, except any sublist beginning with the special marker , will have its second element evaluated, and any sublist beginning with the special marker ,@ will have its second element evaluated, and the result spliced into the list being created.

If any of these specially marked sublists contain more than two elements, those elements will be ignored.

??There are several subtle bugs that should simply be avoided. The following forms do not work as one would expect:

(` (a . (, 1)))
=> (a \, 1)                                ; Not (a . 1)
(` [a (, 1) c])
-> ERROR: Wrong type argument              ; Not [a 1 c]
(` (, 2))
=> (\, 2)                                  ; Not 2

12. Control Structures

GNU Emacs Lisp provides a variety of control structures. These include sequencing forms (such as progn), forms that allow evaluation only if certain conditions are met (such as if), forms that specify iteration (while), and forms that perform non-local exits from code (throw).

Some control structures (e.g., if), allow a list of forms to be given where each element of the list is evaluated in sequence, providing what is called an implicit progn. For example, the following two forms, one with a progn and one without, perform identically.

(if test-form

then-form

         (progn

else-form1 else-form2))

     ==

(if test-form

then-form else-form1 else-form2)

12.1 Function Invocation

The most common way of invoking a function is simply to evaluate a list. The car of any list given to the evaluator is assumed to reference a functional object, possibly indirectly, and the object referenced is then applied to the arguments. The two functions apply and funcall are provided for the less common case where one does not know beforehand what function it is that one wishes to call.

See section 3.2.3 [List Forms], page 26 for a complete description of function invocation.

Function funcall function &rest arguments This function applies function to a list of arguments, returning the result of that application. The list is constructed from all arguments.

function must be a function (a Lisp function or a primitive function that evaluates all arguments), and not a special form or macro.

(funcall (function list) 1 2 3 '(4 5))
=> (1 2 3 (4 5))

Function apply function arg &rest args This function is identical to funcall, except that the last argument is treated specially. The list is constructed from all arguments except the last one, and then the last one is appended to the end.

(apply (function list) '(1 2 3 4 5))
=> (1 2 3 4 5)
(apply (function list) 1 2 3 '(4 5))
=> (1 2 3 4 5)
(setq f (function list))
=> list
(apply f 1 2 3 4 '(5))
=> (1 2 3 4 5)
(apply (function list) 1 2 3 4 5)
-> ERROR: Wrong type argument: listp, 5
(apply (function and) t nil)
-> ERROR: Invalid function: #<subr and>

12.2 Mapping Functions

A mapping function may be used to apply a function to every element of some collection. This is useful if the function to apply is not known until run time. mapcar and mapconcat are described here. See section 8.4 [mapatoms], page 68 for another mapping function.

Function mapcar function sequence This function applies function to each element of sequence in turn, returning a list of the results. It is an error if sequence is a list that does not end with nil.

(mapcar (function car) '((a b) (c d) (e f)))
     => (a c e)
(mapcar (function 1+) [1 2 3])
     => (2 3 4)
(mapcar (function char-to-string) "abc")
     => ("a" "b" "c")
(progn
  (setq sum 0)
  (mapcar
     (function (lambda (n) (setq sum (+ sum n))))

          '(1 2 3 4 5))
       sum)
          => 15

Function mapconcat function sequence separator This function applies function to each element of sequence, and concatenates the results together as strings. Between each pair of results, it inserts separator. For example, using " " as the separator results in spaces between the values returned by function.

function must be a function of one argument returning a string.

     (mapconcat (function (lambda (s) (format "%s" s)))
                '(The cat in the hat)
                " ")
          => "The cat in the hat"
     (mapconcat (function (lambda (x) (format "%c" (1+ x))))
                "HAL-8000"
                "")
          => "IBM.9111"

12.3 Sequencing

Special form progn forms* This special form evaluates all of its arguments, one by one in order, returning the result of its final form. This is the most common sequencing form.

     (progn (print "The first form")
            (print "The second form")
            (print "The third form"))
     -> "The first form"
     -> "The second form"
     -> "The third form"
     => "The third form"

Special form prog1 forms* This special form evaluates all of its arguments, one by one in order, returning the result of its first form,

     (prog1 (print "The first form")

       (print "The second form")
       (print "The third form"))
-> "The first form"
-> "The second form"
-> "The third form"
=> "The first form"

Special form prog2 forms* This special form evaluates all of its arguments, one by one in order, returning the result of its second form.

(prog2 (print "The first form")
       (print "The second form")
       (print "The third form"))
-> "The first form"
-> "The second form"
-> "The third form"
=> "The second form"

12.4 Iteration

Special form while test-form forms* This is the sole iterative form in GNU Emacs Lisp. It evaluates test-form. Then, if the value was non-nil, it evaluates the rest of the forms in order, and begins again, re-evaluating test-form. As soon as test-form evaluates to nil, the while form is exited. while always returns nil.

(setq num 0)
=> 0
(while (< num 5)
   (princ (format "That was number %d! \n" num))
   (setq num (1+ num)))
-> That was number 0!
-> That was number 1!
-> That was number 2!
-> That was number 3!
-> That was number 4!
=> nil
(while (< num 5)
       (princ (format "That was number %d! \n" num))
       (setq num (1+ num)))

     => nil

12.5 Conditionals

Special form if condition then-form else-forms* This special form first evaluates condition. If it returns a non-nil value, if returns the value of evaluating then-form.

If condition evaluates to nil, then the else-forms, are evaluated instead of then-form and the value of the last one is returned. If there are not any else-forms, then if returns nil.

In the examples below, it is important to note that forms that are not selected are not evaluated. Hence, false is not printed in the second example, whereas true is both printed by the function print and returned as the value of the form.

     (if t 'true 'false)
     => true
     (if t (print 'true) (print 'false))
     -> true
     => true
     (if t 'true)
     => true
     (if nil 'true)
     => nil
     (if nil (print 'true) (print 'false) 'very-false)
     -> false
     => very-false

Special form cond clauses* This special form first evaluates the car of the each clause in clauses in the order given until one returns non-nil. If this clause looks like (condition body), then cond returns the result of evaluating the body as an implied progn. If the clause looks like (condition), then the value of condition is returned, if it is non-nil.

If no clause succeeds then the cond form “falls though” and returns nil. To avoid falling through unexpectedly, include (t something) as the final clause.

In the examples below, the first clause is never chosen, and the expression (print 1) is never evaluated.

(cond (nil (print 1))
      (t 2)
      (t 3))
=> 2
(cond (nil (print 1))
      (nil 2)
      (t 4 'two))
=> two
(cond (nil (print 1))
      (nil 2)
      (nil)
      (3))
=> 3
(cond (nil (print 1))
      (nil 2))
=> nil

cond and if can both be written in terms of the other. The choice of using one or the other is strictly taste and style. In particular:

(if a b c)
==
(cond ((a b) (t c))

Function not object This function returns t if object is nil, nil for any other value. not is identical to null.

Special form and forms* This special form takes any number of arguments, and evaluates them one at a time. If they all evaluate to a non-nil value, and returns the value of the last form. If any argument evaluates to nil, then and returns nil without evaluating the rest of the arguments.

(and (print 1) (print 2) (print 3))
-> 1
-> 2
-> 3
=> 3
(and (print 1) nil (print 2) (print 3))
-> 1
=> nil

and can be written using either if or cond. In particular:

(and arg1 arg2 arg3)

==

(if arg1 (if arg2 arg3))

Special form or forms* This special form takes any number of arguments, and evaluates them one at a time. If they all evaluate to nil, or returns nil. If any argument evaluates to a non-nil value, then or returns that value, without evaluating the rest of the arguments.

(or nil (eq 1 2) (progn (print 'x) nil))
-> x
=> nil
(or 1 (eq 1 2) (progn (print 'x) nil))
=> 1

or, like and can be written in terms of cond or if.

(or arg1 arg2 arg3)

==
(cond (arg1)

(arg2) (arg3))

12.6 Non-local Exits

(Intro text!!)

__________

CN: In most other versions of Lisp, there are numerous exiting forms available: return, returnfrom, go. GNU Emacs Lisp has only throw and signal.

__________

Special form catch tag forms* This special form sets up a special marker (called a tag) on the stack to allow any of the forms to return immediately to the catch without having to deal with intermediate function returns. catch first evaluates tag which may return any Lisp object. Tags are typically symbols, although this is not necessary. Then it evaluates each of the forms in sequence. The value of the final form is returned as the value of the catch, unless one of the forms executes a throw to this tag.

Function throw tag value This function is the matching form for catch. If there is such a tag (established by catch) which is eq to tag, then control is immediately transfered to the catch form, which returns value.

All intermediate function calls and local variable bindings on the stack are deleted. Any unwind-protect cleanup is performed and any contexts saved with save-excursion, save-

window-excursion, and save-restriction are restored.

If there is no matching tag on the stack, then a no-catch error is signaled.

Because throw searches up the stack specifically for a tag matching tag, any number of intermediate catch invocations may exist with different tags, and they will be ignored. If there are multiple instances of identical tags on the stack, the one closest to the throw (i.e., the most recently entered catch) will be chosen.

Below is a simple example of using catch and throw.

     (setq x 0)
     => 0
     (catch 'tag1 (setq x (1+ x))                 ; x is now 1
                  (if (= x 2) (throw 'tag1 'two)) ; throw is not executed
                  (list x))
     => (1)
     (catch 'tag1 (setq x (1+ x))                 ; x is now 2
                  (if (= x 2) (throw 'tag1 'two)) ; throw is executed
                  (list x))                       ; so this is not executed
     => two

The more complicated set of examples below establish two tags on the stack. The first example will have two tags named tag2 on the stack, and the throw will go to the closest one, (the tag established by the catch in the function catch2). The calling form will print the result of calling catch2 (yes), then continue evaluating its forms, returning the value of second form (no).

The second example will have two tags on the stack also. The shallowest one being tag2, the deepest one being tag3. The throw will throw to tag2. It will bypass the catcher established in catch2, as that established the tag tag3. The throw will instead go to the outside catcher, which is tag2, and return the value yes, never executing the print, never evaluating 'no.

The last form in the function catch2, (setq x 1) can never be evaluated, no matter how catch2 is called.

     (defun catch2 (tag)
       (catch tag
         (setq x 0)
         (throw 'tag2 'yes)
         (setq x 1)))
     => catch2
     (catch 'tag2
       (print (catch2 'tag2)) 'no)    ;First one
     -> yes
     => no
     (catch 'tag2
       (print (catch2 'tag3)) 'no)    ;Second one
     => yes

Special form unwind-protect protected-form cleanup-forms* This special form guarantees that the cleanup-forms will be executed no matter how the protected-form exits. It is used in those cases where it is essential that certain tasks be completed after a particular computation. Even if the protected-form executes a throw over the unwind-protect, or if it encounters an error, cleanup-forms will be evaluated. (what if cleanup-forms cause an error??)

As a simple (if not very useful) example, consider the code below. The throw will cause the catch to return the value thrown. However, on its way out of the unwind-protect, the cleanup form (print (setq x 0)) will be evaluated. x will be set to 0, and then printed.

In the second example, where there is no matching catch for the throw, the cleanup form (print (setq x 0)) will still be evaluated, even though the computation results in an error.

     (catch 'tag
       (unwind-protect
           (progn (setq x 1) (throw 'tag 'thrown))
         (print (setq x 0))

         (sit-for 1)))
     -> 0 ; pause
     => thrown
     (unwind-protect
         (progn (setq x 1) (throw 'tag 'thrown))
       (print (setq x 0))
       (sit-for 1))
     -> 0  ; pause
     -> ERROR: No catch for tag: tag, thrown

As a more realistic example, consider the code below, taken from the file ‘ftp.el’. It is essential that the process (which was created earlier in the function) be deleted, in case the ftp login fail. As the function ftp-login is highly susceptable to numerous problems which the writer of the function may not anticipate, it is protected with a form that guarantees that the process will be deleted on any type of failure.

     (let ((win nil))
       (unwind-protect
          (if (setq win (ftp-login process host user password))
              (message "Logged in")
              (error "Ftp login lost"))
          (or win (delete-process process))))

Only the form protected-form is actually protected by the unwind-protect. If any of the cleanup forms exit in unusual fashions (e.g., via a throw or an error), it is not guaranteed that the rest of them will be executed. If there is the potential for one of the cleanup forms to fail, then it should be protected by another unwind-protect.

In the example below, we assume that the function complex-kill may possibly result in an error, and we wish to ensure that both processes are deleted, no matter what.

     (let ((proca nil) (procb nil))
          (unwind-protect
                (create-and-run proca procb)
                (unwind-protect
                     (complex-kill proca)
                     (delete-process proca)
                     (delete-process procb))))

12.7 Errors

When Lisp attempts to evaluate a form that, for some reason, cannot be evaluated, an error is signaled. An error is an event with an associated error symbol or error name which names the event. When an error is signaled, this causes Emacs to suspend the normal evaluation sequence and attempt to find a handler for the error. The error must either be handled by a specific error handler or the entire computation is aborted and Emacs returns to the command loop. If an error handler for the error is found, it is given control and the error event is considered over.

Handling or trapping of an error should not be confused with catching a tag. You cannot throw or catch an error and you cannot signal or handle a tag. See section 12.6 [throw], page 104.

Errors are signaled within Lisp functions (and primitive functions) by calling signal. Handlers are established in Lisp code by calling condition-case. Each error symbol has one or more associated error conditions which may be used in condition-case error handlers to indicate which error they are intended to handle.

An error handler is free to proceed in any fashion desired. It may execute a completely different form to return a result, or it may signal another error. What it cannot do, is to “resume” the aborted computation in any fashion. The stack has been popped to the point of the error handler, and everything below has been lost. signal does not regain control unless it is called again.

The handler may attempt to do what the offending expression was supposed to do, but this is not the same as “fixing” a computation (with the debugger) and resuming it at the point the error was signaled.

   ________________

CN: The function signal is the sole function that can signal an error (the function error calls it). This means that GNU Emacs Lisp has nothing like the concept of continuable errors in Common Lisp.

   ________________

Function signal symbol data This function signals an error named by symbol. When called, signal searches up the stack, looking for a handler that specifies one of the error condition that symbol is associated with. If one is found, control resumes there; otherwise Emacs displays an error message constructed from data and it returns to the command loop at the current recursive-edit level (not necessarily the top level).

If debug-on-error is non-nil, the debugger will be invoked instead of aborting to the command loop.

symbol must have an error-conditions property in its propery list whose value is a list of condition names (see section 12.7.1 [Error Conditions], page 110 for a description of how to set up error conditions). Otherwise the untrappable ‘peculiar error’ is signaled.

data must be a list. Its elements will be printed as part of the error message if there is no condition-case handler. If there is a handler, then data will be consed to the symbol and bound to the condition-case variable.

     (signal 'wrong-number-of-arguments
       (list "Oh, Rats!" (1+ 1) "many arguments again."))
     ---------- Echo Area ----------
     Wrong-number-of-arguments: "Oh, Rats!", 2, "many arguments again."
     -------------------------------
     (signal 'no-such-error '("My unknown error condition."))
     ---------- Echo Area ----------
     peculiar error: "My unknown error condition."
     -------------------------------

Special form condition-case var form handlers* This special form is provided so that Lisp programs can handle errors when they are signaled, instead of allowing the entire computation to be aborted. When a condition-case form is evaluated, it first sets up a special marker on the stack that signal will look for. It then evaluates the single form. If form evaluates with no errors, then its result is the result of

condition-case.

If, however, an error is signaled sometime during the evaluation of form, then signal looks up in the stack until it finds a condition-case mark. Then it looks at each of the handlers in the order they appear. Each handler looks like (condition-name body*).

If the condition-name in some handler is one of the conditions that the error symbol is associated with, then this handler is used. First the variable var is bound to a list made from the error symbol (not the condition-name) consed with the data list that signal was called with. Then the body forms are evaluated and the last value is the result.

If the condition-case does not have a handler for any of the conditions, then signal continues to see if there might be another condition-case higher up on the stack which will handle the error. If none is found, then the computation is aborted.

In the first example below, division by zero signals an arith-error, which has two associated conditions: arith-error and error. The error is handled by printing out a warning message and returning a very large number.

In the second example, the error quit, which has only one associated condition, quit, is handled by the outside condition-case since the inside condition-case handles only errors which are associated with the condition named error.

     (condition-case ERR
         (/ 3 0)
       (error (princ (format "\nThe error was: %s" ERR)) 1000000))
     -> The error was: (arith-error)
     => 1000000
     (condition-case ERR0
         (condition-case ERR1
             (signal 'quit "No go")
           (error (princ (format "\nThis was caught by CC1: %s" ERR1)) 'VALUE1))
       (quit (princ (format "\nThis was caught by CC0: %s" ERR0)) 'VALUE0))
     -> This was caught by CC0: (quit . "No go")
     => VALUE0

condition-case may be used to trap errors that are unexpected so that some cleanup or recovery may be attempted. It may also be used to trap errors that are expected and consequently add some functionality to the use of a standard Emacs function. In the following example, the down-list function is used to determine if it is possible to move down one level of parentheses. The quit condition should not normally be trapped because it is intended to abort the current computation.

     (condition-case err
         (down-list 1)
       (error (message "Hit bottom"))
       )
     => "Hit bottom"

Function error format-string &rest args This function signals an error, by calling signal with the error named error, and the string constructed by applying format (see section 5.3 [format], page 45) to the arguments.

           (setq BAZ 34)
           => 34
           (if (eq BAZ 35)
               t
             (error "Rats!  The variable %s was %s, not 35." 'BAZ BAZ))
           ---------- Echo Area ----------
           Rats!  The variable BAZ was 34, not 35.
           -------------------------------
           (condition-case ERR
               (if (eq BAZ 35)
                   t
                 (error "Rats!  The variable %s was %s, not 35." 'BAZ BAZ))
             (error (princ (format "\nThe error was: %s" ERR)) 2))
           -> The error was: (error "Rats!  The variable BAZ was 34, not 35.")
           => 2

12.7.1 Error Conditions

Every symbol that is a legitimate name for an error must have an error-conditions property on its property list (see section 8.5 [Property Lists], page 69). This property value is a list of associated error condition symbols. When an error is signaled, if there is a condition-case handler that specifies any one of the error symbol’s associated conditions, then that handler is given control.

Along with the error-conditions list, the error symbol should have an error-message property whose value is a string to be printed when that error is signaled but not handled.

It is important to understand that handlers must use the error conditions, and not the error symbols. It is common, however, for the symbol which is used as the name of an error to be used as one of the associated conditions. In the example below, foo-error is the error symbol; it is used in the call to signal. The associated condition is foo-condition, however, and that is the symbol which the condition-case handler must use.

     (put 'foo-error 'error-message "A Foo-ish Error")
     => "A Foo-ish Error"
     (put 'foo-error 'error-conditions '(error foo-condition))
     => (error foo-condition)
     (signal 'foo-error '(ARG1 ARG2))
     ---------- Echo Area ----------
     A Foo-ish Error: ARG1, ARG2
     -------------------------------

     (condition-case V
         (signal 'foo-error '())
       (foo-condition
        (format "A Foolish Error: %s" V)))
     => "A Foolish Error: (foo-error)"

Below is the complete list of the error symbols and conditions that exist in standard GNU Emacs. Notice that all of the error symbols except quit have the error condition as one of the conditions. This is so that programs may trap any error except quit by using error as the condition in a handler. The quit error does not have the error condition because it is intended that a quit error should abort the current computation.

(cross reference to description of how each error can occur!! or describe it here. maybe move to appendix??)

error     "error" (error)
quit      "Quit" (quit)
no-catch  "No catch for tag" (no-catch error)
invalid-read-syntax
          "Invalid read syntax" (invalid-read-syntax error)
setting-constant

"Attempt to set a constant symbol" (setting-constant error)

void-function

"Symbol’s function definition is void" (void-function error)

void-variable

"Symbol’s value as variable is void" (void-variable error)

invalid-function
          "Invalid function" (invalid-function error)
wrong-type-argument
          "Wrong type argument" (wrong-type-argument error)
args-out-of-range
          "Args out of range" (args-out-of-range error)
wrong-number-of-arguments
          "Wrong number of arguments" (wrong-number-of-arguments error)
search-failed
          "Search failed" (search-failed error)
invalid-regexp
          "Invalid regexp" (invalid-regexp error)

arith-error
          "Arithmetic error" (arith-error error)
end-of-buffer
          "End of buffer" (end-of-buffer error)
beginning-of-buffer
          "Beginning of buffer" (beginning-of-buffer error)
buffer-read-only
          "Buffer is read-only" (buffer-read-only error)
file-error
          "File error" (file-error error)
file-locked
          "" (file-locked file-error error)
end-of-file

"End of file during