This is ../../info/elisp, produced by makeinfo version 4.11 from elisp.texi. This is edition 3.0 of the GNU Emacs Lisp Reference Manual, corresponding to Emacs version 23.2. Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being "GNU General Public License," with the Front-Cover texts being "A GNU Manual," and with the Back-Cover Texts as in (a) below. A copy of the license is included in the section entitled "GNU Free Documentation License." (a) The FSF's Back-Cover Text is: "You have the freedom to copy and modify this GNU manual. Buying copies from the FSF supports it in developing GNU and promoting software freedom." INFO-DIR-SECTION Emacs START-INFO-DIR-ENTRY * Elisp: (elisp). The Emacs Lisp Reference Manual. END-INFO-DIR-ENTRY  File: elisp, Node: Arrays, Next: Array Functions, Prev: Sequence Functions, Up: Sequences Arrays Vectors 6.2 Arrays ========== An "array" object has slots that hold a number of other Lisp objects, called the elements of the array. Any element of an array may be accessed in constant time. In contrast, the time to access an element of a list is proportional to the position of that element in the list. Emacs defines four types of array, all one-dimensional: "strings" (*note String Type::), "vectors" (*note Vector Type::), "bool-vectors" (*note Bool-Vector Type::), and "char-tables" (*note Char-Table Type::). Vectors and char-tables can hold elements of any type, but strings can only hold characters, and bool-vectors can only hold `t' and `nil'. All four kinds of array share these characteristics: * The first element of an array has index zero, the second element has index 1, and so on. This is called "zero-origin" indexing. For example, an array of four elements has indices 0, 1, 2, and 3. * The length of the array is fixed once you create it; you cannot change the length of an existing array. * For purposes of evaluation, the array is a constant--in other words, it evaluates to itself. * The elements of an array may be referenced or changed with the functions `aref' and `aset', respectively (*note Array Functions::). When you create an array, other than a char-table, you must specify its length. You cannot specify the length of a char-table, because that is determined by the range of character codes. In principle, if you want an array of text characters, you could use either a string or a vector. In practice, we always choose strings for such applications, for four reasons: * They occupy one-fourth the space of a vector of the same elements. * Strings are printed in a way that shows the contents more clearly as text. * Strings can hold text properties. *Note Text Properties::. * Many of the specialized editing and I/O facilities of Emacs accept only strings. For example, you cannot insert a vector of characters into a buffer the way you can insert a string. *Note Strings and Characters::. By contrast, for an array of keyboard input characters (such as a key sequence), a vector may be necessary, because many keyboard input characters are outside the range that will fit in a string. *Note Key Sequence Input::.  File: elisp, Node: Array Functions, Next: Vectors, Prev: Arrays, Up: Sequences Arrays Vectors 6.3 Functions that Operate on Arrays ==================================== In this section, we describe the functions that accept all types of arrays. -- Function: arrayp object This function returns `t' if OBJECT is an array (i.e., a vector, a string, a bool-vector or a char-table). (arrayp [a]) => t (arrayp "asdf") => t (arrayp (syntax-table)) ;; A char-table. => t -- Function: aref array index This function returns the INDEXth element of ARRAY. The first element is at index zero. (setq primes [2 3 5 7 11 13]) => [2 3 5 7 11 13] (aref primes 4) => 11 (aref "abcdefg" 1) => 98 ; `b' is ASCII code 98. See also the function `elt', in *note Sequence Functions::. -- Function: aset array index object This function sets the INDEXth element of ARRAY to be OBJECT. It returns OBJECT. (setq w [foo bar baz]) => [foo bar baz] (aset w 0 'fu) => fu w => [fu bar baz] (setq x "asdfasfd") => "asdfasfd" (aset x 3 ?Z) => 90 x => "asdZasfd" If ARRAY is a string and OBJECT is not a character, a `wrong-type-argument' error results. The function converts a unibyte string to multibyte if necessary to insert a character. -- Function: fillarray array object This function fills the array ARRAY with OBJECT, so that each element of ARRAY is OBJECT. It returns ARRAY. (setq a [a b c d e f g]) => [a b c d e f g] (fillarray a 0) => [0 0 0 0 0 0 0] a => [0 0 0 0 0 0 0] (setq s "When in the course") => "When in the course" (fillarray s ?-) => "------------------" If ARRAY is a string and OBJECT is not a character, a `wrong-type-argument' error results. The general sequence functions `copy-sequence' and `length' are often useful for objects known to be arrays. *Note Sequence Functions::.  File: elisp, Node: Vectors, Next: Vector Functions, Prev: Array Functions, Up: Sequences Arrays Vectors 6.4 Vectors =========== A "vector" is a general-purpose array whose elements can be any Lisp objects. (By contrast, the elements of a string can only be characters. *Note Strings and Characters::.) Vectors are used in Emacs for many purposes: as key sequences (*note Key Sequences::), as symbol-lookup tables (*note Creating Symbols::), as part of the representation of a byte-compiled function (*note Byte Compilation::), and more. In Emacs Lisp, the indices of the elements of a vector start from zero and count up from there. Vectors are printed with square brackets surrounding the elements. Thus, a vector whose elements are the symbols `a', `b' and `a' is printed as `[a b a]'. You can write vectors in the same way in Lisp input. A vector, like a string or a number, is considered a constant for evaluation: the result of evaluating it is the same vector. This does not evaluate or even examine the elements of the vector. *Note Self-Evaluating Forms::. Here are examples illustrating these principles: (setq avector [1 two '(three) "four" [five]]) => [1 two (quote (three)) "four" [five]] (eval avector) => [1 two (quote (three)) "four" [five]] (eq avector (eval avector)) => t  File: elisp, Node: Vector Functions, Next: Char-Tables, Prev: Vectors, Up: Sequences Arrays Vectors 6.5 Functions for Vectors ========================= Here are some functions that relate to vectors: -- Function: vectorp object This function returns `t' if OBJECT is a vector. (vectorp [a]) => t (vectorp "asdf") => nil -- Function: vector &rest objects This function creates and returns a vector whose elements are the arguments, OBJECTS. (vector 'foo 23 [bar baz] "rats") => [foo 23 [bar baz] "rats"] (vector) => [] -- Function: make-vector length object This function returns a new vector consisting of LENGTH elements, each initialized to OBJECT. (setq sleepy (make-vector 9 'Z)) => [Z Z Z Z Z Z Z Z Z] -- Function: vconcat &rest sequences This function returns a new vector containing all the elements of SEQUENCES. The arguments SEQUENCES may be true lists, vectors, strings or bool-vectors. If no SEQUENCES are given, an empty vector is returned. The value is a newly constructed vector that is not `eq' to any existing vector. (setq a (vconcat '(A B C) '(D E F))) => [A B C D E F] (eq a (vconcat a)) => nil (vconcat) => [] (vconcat [A B C] "aa" '(foo (6 7))) => [A B C 97 97 foo (6 7)] The `vconcat' function also allows byte-code function objects as arguments. This is a special feature to make it easy to access the entire contents of a byte-code function object. *Note Byte-Code Objects::. For other concatenation functions, see `mapconcat' in *note Mapping Functions::, `concat' in *note Creating Strings::, and `append' in *note Building Lists::. The `append' function also provides a way to convert a vector into a list with the same elements: (setq avector [1 two (quote (three)) "four" [five]]) => [1 two (quote (three)) "four" [five]] (append avector nil) => (1 two (quote (three)) "four" [five])  File: elisp, Node: Char-Tables, Next: Bool-Vectors, Prev: Vector Functions, Up: Sequences Arrays Vectors 6.6 Char-Tables =============== A char-table is much like a vector, except that it is indexed by character codes. Any valid character code, without modifiers, can be used as an index in a char-table. You can access a char-table's elements with `aref' and `aset', as with any array. In addition, a char-table can have "extra slots" to hold additional data not associated with particular character codes. Like vectors, char-tables are constants when evaluated, and can hold elements of any type. Each char-table has a "subtype", a symbol, which serves two purposes: * The subtype provides an easy way to tell what the char-table is for. For instance, display tables are char-tables with `display-table' as the subtype, and syntax tables are char-tables with `syntax-table' as the subtype. The subtype can be queried using the function `char-table-subtype', described below. * The subtype controls the number of "extra slots" in the char-table. This number is specified by the subtype's `char-table-extra-slots' symbol property, which should be an integer between 0 and 10. If the subtype has no such symbol property, the char-table has no extra slots. *Note Property Lists::, for information about symbol properties. A char-table can have a "parent", which is another char-table. If it does, then whenever the char-table specifies `nil' for a particular character C, it inherits the value specified in the parent. In other words, `(aref CHAR-TABLE C)' returns the value from the parent of CHAR-TABLE if CHAR-TABLE itself specifies `nil'. A char-table can also have a "default value". If so, then `(aref CHAR-TABLE C)' returns the default value whenever the char-table does not specify any other non-`nil' value. -- Function: make-char-table subtype &optional init Return a newly-created char-table, with subtype SUBTYPE (a symbol). Each element is initialized to INIT, which defaults to `nil'. You cannot alter the subtype of a char-table after the char-table is created. There is no argument to specify the length of the char-table, because all char-tables have room for any valid character code as an index. If SUBTYPE has the `char-table-extra-slots' symbol property, that specifies the number of extra slots in the char-table. This should be an integer between 0 and 10; otherwise, `make-char-table' raises an error. If SUBTYPE has no `char-table-extra-slots' symbol property (*note Property Lists::), the char-table has no extra slots. -- Function: char-table-p object This function returns `t' if OBJECT is a char-table, and `nil' otherwise. -- Function: char-table-subtype char-table This function returns the subtype symbol of CHAR-TABLE. There is no special function to access default values in a char-table. To do that, use `char-table-range' (see below). -- Function: char-table-parent char-table This function returns the parent of CHAR-TABLE. The parent is always either `nil' or another char-table. -- Function: set-char-table-parent char-table new-parent This function sets the parent of CHAR-TABLE to NEW-PARENT. -- Function: char-table-extra-slot char-table n This function returns the contents of extra slot N of CHAR-TABLE. The number of extra slots in a char-table is determined by its subtype. -- Function: set-char-table-extra-slot char-table n value This function stores VALUE in extra slot N of CHAR-TABLE. A char-table can specify an element value for a single character code; it can also specify a value for an entire character set. -- Function: char-table-range char-table range This returns the value specified in CHAR-TABLE for a range of characters RANGE. Here are the possibilities for RANGE: `nil' Refers to the default value. CHAR Refers to the element for character CHAR (supposing CHAR is a valid character code). `(FROM . TO)' A cons cell refers to all the characters in the inclusive range `[FROM..TO]'. -- Function: set-char-table-range char-table range value This function sets the value in CHAR-TABLE for a range of characters RANGE. Here are the possibilities for RANGE: `nil' Refers to the default value. `t' Refers to the whole range of character codes. CHAR Refers to the element for character CHAR (supposing CHAR is a valid character code). `(FROM . TO)' A cons cell refers to all the characters in the inclusive range `[FROM..TO]'. -- Function: map-char-table function char-table This function calls its argument FUNCTION for each element of CHAR-TABLE that has a non-`nil' value. The call to FUNCTION is with two arguments, a key and a value. The key is a possible RANGE argument for `char-table-range'--either a valid character or a cons cell `(FROM . TO)', specifying a range of characters that share the same value. The value is what `(char-table-range CHAR-TABLE KEY)' returns. Overall, the key-value pairs passed to FUNCTION describe all the values stored in CHAR-TABLE. The return value is always `nil'; to make calls to `map-char-table' useful, FUNCTION should have side effects. For example, here is how to examine the elements of the syntax table: (let (accumulator) (map-char-table #'(lambda (key value) (setq accumulator (cons (list (if (consp key) (list (car key) (cdr key)) key) value) accumulator))) (syntax-table)) accumulator) => (((2597602 4194303) (2)) ((2597523 2597601) (3)) ... (65379 (5 . 65378)) (65378 (4 . 65379)) (65377 (1)) ... (12 (0)) (11 (3)) (10 (12)) (9 (0)) ((0 8) (3)))  File: elisp, Node: Bool-Vectors, Prev: Char-Tables, Up: Sequences Arrays Vectors 6.7 Bool-vectors ================ A bool-vector is much like a vector, except that it stores only the values `t' and `nil'. If you try to store any non-`nil' value into an element of the bool-vector, the effect is to store `t' there. As with all arrays, bool-vector indices start from 0, and the length cannot be changed once the bool-vector is created. Bool-vectors are constants when evaluated. There are two special functions for working with bool-vectors; aside from that, you manipulate them with same functions used for other kinds of arrays. -- Function: make-bool-vector length initial Return a new bool-vector of LENGTH elements, each one initialized to INITIAL. -- Function: bool-vector-p object This returns `t' if OBJECT is a bool-vector, and `nil' otherwise. Here is an example of creating, examining, and updating a bool-vector. Note that the printed form represents up to 8 boolean values as a single character. (setq bv (make-bool-vector 5 t)) => #&5"^_" (aref bv 1) => t (aset bv 3 nil) => nil bv => #&5"^W" These results make sense because the binary codes for control-_ and control-W are 11111 and 10111, respectively.  File: elisp, Node: Hash Tables, Next: Symbols, Prev: Sequences Arrays Vectors, Up: Top 7 Hash Tables ************* A hash table is a very fast kind of lookup table, somewhat like an alist (*note Association Lists::) in that it maps keys to corresponding values. It differs from an alist in these ways: * Lookup in a hash table is extremely fast for large tables--in fact, the time required is essentially _independent_ of how many elements are stored in the table. For smaller tables (a few tens of elements) alists may still be faster because hash tables have a more-or-less constant overhead. * The correspondences in a hash table are in no particular order. * There is no way to share structure between two hash tables, the way two alists can share a common tail. Emacs Lisp provides a general-purpose hash table data type, along with a series of functions for operating on them. Hash tables have a special printed representation, which consists of `#s' followed by a list specifying the hash table properties and contents. *Note Creating Hash::. (Note that the term "hash notation", which refers to the initial `#' character used in the printed representations of objects with no read representation, has nothing to do with the term "hash table". *Note Printed Representation::.) Obarrays are also a kind of hash table, but they are a different type of object and are used only for recording interned symbols (*note Creating Symbols::). * Menu: * Creating Hash:: Functions to create hash tables. * Hash Access:: Reading and writing the hash table contents. * Defining Hash:: Defining new comparison methods. * Other Hash:: Miscellaneous.  File: elisp, Node: Creating Hash, Next: Hash Access, Up: Hash Tables 7.1 Creating Hash Tables ======================== The principal function for creating a hash table is `make-hash-table'. -- Function: make-hash-table &rest keyword-args This function creates a new hash table according to the specified arguments. The arguments should consist of alternating keywords (particular symbols recognized specially) and values corresponding to them. Several keywords make sense in `make-hash-table', but the only two that you really need to know about are `:test' and `:weakness'. `:test TEST' This specifies the method of key lookup for this hash table. The default is `eql'; `eq' and `equal' are other alternatives: `eql' Keys which are numbers are "the same" if they are `equal', that is, if they are equal in value and either both are integers or both are floating point numbers; otherwise, two distinct objects are never "the same." `eq' Any two distinct Lisp objects are "different" as keys. `equal' Two Lisp objects are "the same," as keys, if they are equal according to `equal'. You can use `define-hash-table-test' (*note Defining Hash::) to define additional possibilities for TEST. `:weakness WEAK' The weakness of a hash table specifies whether the presence of a key or value in the hash table preserves it from garbage collection. The value, WEAK, must be one of `nil', `key', `value', `key-or-value', `key-and-value', or `t' which is an alias for `key-and-value'. If WEAK is `key' then the hash table does not prevent its keys from being collected as garbage (if they are not referenced anywhere else); if a particular key does get collected, the corresponding association is removed from the hash table. If WEAK is `value', then the hash table does not prevent values from being collected as garbage (if they are not referenced anywhere else); if a particular value does get collected, the corresponding association is removed from the hash table. If WEAK is `key-and-value' or `t', both the key and the value must be live in order to preserve the association. Thus, the hash table does not protect either keys or values from garbage collection; if either one is collected as garbage, that removes the association. If WEAK is `key-or-value', either the key or the value can preserve the association. Thus, associations are removed from the hash table when both their key and value would be collected as garbage (if not for references from weak hash tables). The default for WEAK is `nil', so that all keys and values referenced in the hash table are preserved from garbage collection. `:size SIZE' This specifies a hint for how many associations you plan to store in the hash table. If you know the approximate number, you can make things a little more efficient by specifying it this way. If you specify too small a size, the hash table will grow automatically when necessary, but doing that takes some extra time. The default size is 65. `:rehash-size REHASH-SIZE' When you add an association to a hash table and the table is "full," it grows automatically. This value specifies how to make the hash table larger, at that time. If REHASH-SIZE is an integer, it should be positive, and the hash table grows by adding that much to the nominal size. If REHASH-SIZE is a floating point number, it had better be greater than 1, and the hash table grows by multiplying the old size by that number. The default value is 1.5. `:rehash-threshold THRESHOLD' This specifies the criterion for when the hash table is "full" (so it should be made larger). The value, THRESHOLD, should be a positive floating point number, no greater than 1. The hash table is "full" whenever the actual number of entries exceeds this fraction of the nominal size. The default for THRESHOLD is 0.8. -- Function: makehash &optional test This is equivalent to `make-hash-table', but with a different style argument list. The argument TEST specifies the method of key lookup. This function is obsolete. Use `make-hash-table' instead. You can also create a new hash table using the printed representation for hash tables. The Lisp reader can read this printed representation, provided each element in the specified hash table has a valid read syntax (*note Printed Representation::). For instance, the following specifies a new hash table containing the keys `key1' and `key2' (both symbols) associated with `val1' (a symbol) and `300' (a number) respectively. #s(hash-table size 30 data (key1 val1 key2 300)) The printed representation for a hash table consists of `#s' followed by a list beginning with `hash-table'. The rest of the list should consist of zero or more property-value pairs specifying the hash table's properties and initial contents. The properties and values are read literally. Valid property names are `size', `test', `weakness', `rehash-size', `rehash-threshold', and `data'. The `data' property should be a list of key-value pairs for the initial contents; the other properties have the same meanings as the matching `make-hash-table' keywords (`:size', `:test', etc.), described above. Note that you cannot specify a hash table whose initial contents include objects that have no read syntax, such as buffers and frames. Such objects may be added to the hash table after it is created.  File: elisp, Node: Hash Access, Next: Defining Hash, Prev: Creating Hash, Up: Hash Tables 7.2 Hash Table Access ===================== This section describes the functions for accessing and storing associations in a hash table. In general, any Lisp object can be used as a hash key, unless the comparison method imposes limits. Any Lisp object can also be used as the value. -- Function: gethash key table &optional default This function looks up KEY in TABLE, and returns its associated VALUE--or DEFAULT, if KEY has no association in TABLE. -- Function: puthash key value table This function enters an association for KEY in TABLE, with value VALUE. If KEY already has an association in TABLE, VALUE replaces the old associated value. -- Function: remhash key table This function removes the association for KEY from TABLE, if there is one. If KEY has no association, `remhash' does nothing. Common Lisp note: In Common Lisp, `remhash' returns non-`nil' if it actually removed an association and `nil' otherwise. In Emacs Lisp, `remhash' always returns `nil'. -- Function: clrhash table This function removes all the associations from hash table TABLE, so that it becomes empty. This is also called "clearing" the hash table. Common Lisp note: In Common Lisp, `clrhash' returns the empty TABLE. In Emacs Lisp, it returns `nil'. -- Function: maphash function table This function calls FUNCTION once for each of the associations in TABLE. The function FUNCTION should accept two arguments--a KEY listed in TABLE, and its associated VALUE. `maphash' returns `nil'.  File: elisp, Node: Defining Hash, Next: Other Hash, Prev: Hash Access, Up: Hash Tables 7.3 Defining Hash Comparisons ============================= You can define new methods of key lookup by means of `define-hash-table-test'. In order to use this feature, you need to understand how hash tables work, and what a "hash code" means. You can think of a hash table conceptually as a large array of many slots, each capable of holding one association. To look up a key, `gethash' first computes an integer, the hash code, from the key. It reduces this integer modulo the length of the array, to produce an index in the array. Then it looks in that slot, and if necessary in other nearby slots, to see if it has found the key being sought. Thus, to define a new method of key lookup, you need to specify both a function to compute the hash code from a key, and a function to compare two keys directly. -- Function: define-hash-table-test name test-fn hash-fn This function defines a new hash table test, named NAME. After defining NAME in this way, you can use it as the TEST argument in `make-hash-table'. When you do that, the hash table will use TEST-FN to compare key values, and HASH-FN to compute a "hash code" from a key value. The function TEST-FN should accept two arguments, two keys, and return non-`nil' if they are considered "the same." The function HASH-FN should accept one argument, a key, and return an integer that is the "hash code" of that key. For good results, the function should use the whole range of integer values for hash codes, including negative integers. The specified functions are stored in the property list of NAME under the property `hash-table-test'; the property value's form is `(TEST-FN HASH-FN)'. -- Function: sxhash obj This function returns a hash code for Lisp object OBJ. This is an integer which reflects the contents of OBJ and the other Lisp objects it points to. If two objects OBJ1 and OBJ2 are equal, then `(sxhash OBJ1)' and `(sxhash OBJ2)' are the same integer. If the two objects are not equal, the values returned by `sxhash' are usually different, but not always; once in a rare while, by luck, you will encounter two distinct-looking objects that give the same result from `sxhash'. This example creates a hash table whose keys are strings that are compared case-insensitively. (defun case-fold-string= (a b) (compare-strings a nil nil b nil nil t)) (defun case-fold-string-hash (a) (sxhash (upcase a))) (define-hash-table-test 'case-fold 'case-fold-string= 'case-fold-string-hash) (make-hash-table :test 'case-fold) Here is how you could define a hash table test equivalent to the predefined test value `equal'. The keys can be any Lisp object, and equal-looking objects are considered the same key. (define-hash-table-test 'contents-hash 'equal 'sxhash) (make-hash-table :test 'contents-hash)  File: elisp, Node: Other Hash, Prev: Defining Hash, Up: Hash Tables 7.4 Other Hash Table Functions ============================== Here are some other functions for working with hash tables. -- Function: hash-table-p table This returns non-`nil' if TABLE is a hash table object. -- Function: copy-hash-table table This function creates and returns a copy of TABLE. Only the table itself is copied--the keys and values are shared. -- Function: hash-table-count table This function returns the actual number of entries in TABLE. -- Function: hash-table-test table This returns the TEST value that was given when TABLE was created, to specify how to hash and compare keys. See `make-hash-table' (*note Creating Hash::). -- Function: hash-table-weakness table This function returns the WEAK value that was specified for hash table TABLE. -- Function: hash-table-rehash-size table This returns the rehash size of TABLE. -- Function: hash-table-rehash-threshold table This returns the rehash threshold of TABLE. -- Function: hash-table-size table This returns the current nominal size of TABLE.  File: elisp, Node: Symbols, Next: Evaluation, Prev: Hash Tables, Up: Top 8 Symbols ********* A "symbol" is an object with a unique name. This chapter describes symbols, their components, their property lists, and how they are created and interned. Separate chapters describe the use of symbols as variables and as function names; see *note Variables::, and *note Functions::. For the precise read syntax for symbols, see *note Symbol Type::. You can test whether an arbitrary Lisp object is a symbol with `symbolp': -- Function: symbolp object This function returns `t' if OBJECT is a symbol, `nil' otherwise. * Menu: * Symbol Components:: Symbols have names, values, function definitions and property lists. * Definitions:: A definition says how a symbol will be used. * Creating Symbols:: How symbols are kept unique. * Property Lists:: Each symbol has a property list for recording miscellaneous information.  File: elisp, Node: Symbol Components, Next: Definitions, Prev: Symbols, Up: Symbols 8.1 Symbol Components ===================== Each symbol has four components (or "cells"), each of which references another object: Print name The "print name cell" holds a string that names the symbol for reading and printing. See `symbol-name' in *note Creating Symbols::. Value The "value cell" holds the current value of the symbol as a variable. When a symbol is used as a form, the value of the form is the contents of the symbol's value cell. See `symbol-value' in *note Accessing Variables::. Function The "function cell" holds the function definition of the symbol. When a symbol is used as a function, its function definition is used in its place. This cell is also used to make a symbol stand for a keymap or a keyboard macro, for editor command execution. Because each symbol has separate value and function cells, variables names and function names do not conflict. See `symbol-function' in *note Function Cells::. Property list The "property list cell" holds the property list of the symbol. See `symbol-plist' in *note Property Lists::. The print name cell always holds a string, and cannot be changed. The other three cells can be set individually to any specified Lisp object. The print name cell holds the string that is the name of the symbol. Since symbols are represented textually by their names, it is important not to have two symbols with the same name. The Lisp reader ensures this: every time it reads a symbol, it looks for an existing symbol with the specified name before it creates a new one. (In GNU Emacs Lisp, this lookup uses a hashing algorithm and an obarray; see *note Creating Symbols::.) The value cell holds the symbol's value as a variable (*note Variables::). That is what you get if you evaluate the symbol as a Lisp expression (*note Evaluation::). Any Lisp object is a legitimate value. Certain symbols have values that cannot be changed; these include `nil' and `t', and any symbol whose name starts with `:' (those are called "keywords"). *Note Constant Variables::. We often refer to "the function `foo'" when we really mean the function stored in the function cell of the symbol `foo'. We make the distinction explicit only when necessary. In normal usage, the function cell usually contains a function (*note Functions::) or a macro (*note Macros::), as that is what the Lisp interpreter expects to see there (*note Evaluation::). Keyboard macros (*note Keyboard Macros::), keymaps (*note Keymaps::) and autoload objects (*note Autoloading::) are also sometimes stored in the function cells of symbols. The property list cell normally should hold a correctly formatted property list (*note Property Lists::), as a number of functions expect to see a property list there. The function cell or the value cell may be "void", which means that the cell does not reference any object. (This is not the same thing as holding the symbol `void', nor the same as holding the symbol `nil'.) Examining a function or value cell that is void results in an error, such as `Symbol's value as variable is void'. The four functions `symbol-name', `symbol-value', `symbol-plist', and `symbol-function' return the contents of the four cells of a symbol. Here as an example we show the contents of the four cells of the symbol `buffer-file-name': (symbol-name 'buffer-file-name) => "buffer-file-name" (symbol-value 'buffer-file-name) => "/gnu/elisp/symbols.texi" (symbol-function 'buffer-file-name) => # (symbol-plist 'buffer-file-name) => (variable-documentation 29529) Because this symbol is the variable which holds the name of the file being visited in the current buffer, the value cell contents we see are the name of the source file of this chapter of the Emacs Lisp Manual. The property list cell contains the list `(variable-documentation 29529)' which tells the documentation functions where to find the documentation string for the variable `buffer-file-name' in the `DOC-VERSION' file. (29529 is the offset from the beginning of the `DOC-VERSION' file to where that documentation string begins--see *note Documentation Basics::.) The function cell contains the function for returning the name of the file. `buffer-file-name' names a primitive function, which has no read syntax and prints in hash notation (*note Primitive Function Type::). A symbol naming a function written in Lisp would have a lambda expression (or a byte-code object) in this cell.  File: elisp, Node: Definitions, Next: Creating Symbols, Prev: Symbol Components, Up: Symbols 8.2 Defining Symbols ==================== A "definition" in Lisp is a special form that announces your intention to use a certain symbol in a particular way. In Emacs Lisp, you can define a symbol as a variable, or define it as a function (or macro), or both independently. A definition construct typically specifies a value or meaning for the symbol for one kind of use, plus documentation for its meaning when used in this way. Thus, when you define a symbol as a variable, you can supply an initial value for the variable, plus documentation for the variable. `defvar' and `defconst' are special forms that define a symbol as a global variable. They are documented in detail in *note Defining Variables::. For defining user option variables that can be customized, use `defcustom' (*note Customization::). `defun' defines a symbol as a function, creating a lambda expression and storing it in the function cell of the symbol. This lambda expression thus becomes the function definition of the symbol. (The term "function definition," meaning the contents of the function cell, is derived from the idea that `defun' gives the symbol its definition as a function.) `defsubst' and `defalias' are two other ways of defining a function. *Note Functions::. `defmacro' defines a symbol as a macro. It creates a macro object and stores it in the function cell of the symbol. Note that a given symbol can be a macro or a function, but not both at once, because both macro and function definitions are kept in the function cell, and that cell can hold only one Lisp object at any given time. *Note Macros::. In Emacs Lisp, a definition is not required in order to use a symbol as a variable or function. Thus, you can make a symbol a global variable with `setq', whether you define it first or not. The real purpose of definitions is to guide programmers and programming tools. They inform programmers who read the code that certain symbols are _intended_ to be used as variables, or as functions. In addition, utilities such as `etags' and `make-docfile' recognize definitions, and add appropriate information to tag tables and the `DOC-VERSION' file. *Note Accessing Documentation::.  File: elisp, Node: Creating Symbols, Next: Property Lists, Prev: Definitions, Up: Symbols 8.3 Creating and Interning Symbols ================================== To understand how symbols are created in GNU Emacs Lisp, you must know how Lisp reads them. Lisp must ensure that it finds the same symbol every time it reads the same set of characters. Failure to do so would cause complete confusion. When the Lisp reader encounters a symbol, it reads all the characters of the name. Then it "hashes" those characters to find an index in a table called an "obarray". Hashing is an efficient method of looking something up. For example, instead of searching a telephone book cover to cover when looking up Jan Jones, you start with the J's and go from there. That is a simple version of hashing. Each element of the obarray is a "bucket" which holds all the symbols with a given hash code; to look for a given name, it is sufficient to look through all the symbols in the bucket for that name's hash code. (The same idea is used for general Emacs hash tables, but they are a different data type; see *note Hash Tables::.) If a symbol with the desired name is found, the reader uses that symbol. If the obarray does not contain a symbol with that name, the reader makes a new symbol and adds it to the obarray. Finding or adding a symbol with a certain name is called "interning" it, and the symbol is then called an "interned symbol". Interning ensures that each obarray has just one symbol with any particular name. Other like-named symbols may exist, but not in the same obarray. Thus, the reader gets the same symbols for the same names, as long as you keep reading with the same obarray. Interning usually happens automatically in the reader, but sometimes other programs need to do it. For example, after the `M-x' command obtains the command name as a string using the minibuffer, it then interns the string, to get the interned symbol with that name. No obarray contains all symbols; in fact, some symbols are not in any obarray. They are called "uninterned symbols". An uninterned symbol has the same four cells as other symbols; however, the only way to gain access to it is by finding it in some other object or as the value of a variable. Creating an uninterned symbol is useful in generating Lisp code, because an uninterned symbol used as a variable in the code you generate cannot clash with any variables used in other Lisp programs. In Emacs Lisp, an obarray is actually a vector. Each element of the vector is a bucket; its value is either an interned symbol whose name hashes to that bucket, or 0 if the bucket is empty. Each interned symbol has an internal link (invisible to the user) to the next symbol in the bucket. Because these links are invisible, there is no way to find all the symbols in an obarray except using `mapatoms' (below). The order of symbols in a bucket is not significant. In an empty obarray, every element is 0, so you can create an obarray with `(make-vector LENGTH 0)'. *This is the only valid way to create an obarray.* Prime numbers as lengths tend to result in good hashing; lengths one less than a power of two are also good. *Do not try to put symbols in an obarray yourself.* This does not work--only `intern' can enter a symbol in an obarray properly. Common Lisp note: In Common Lisp, a single symbol may be interned in several obarrays. Most of the functions below take a name and sometimes an obarray as arguments. A `wrong-type-argument' error is signaled if the name is not a string, or if the obarray is not a vector. -- Function: symbol-name symbol This function returns the string that is SYMBOL's name. For example: (symbol-name 'foo) => "foo" *Warning:* Changing the string by substituting characters does change the name of the symbol, but fails to update the obarray, so don't do it! -- Function: make-symbol name This function returns a newly-allocated, uninterned symbol whose name is NAME (which must be a string). Its value and function definition are void, and its property list is `nil'. In the example below, the value of `sym' is not `eq' to `foo' because it is a distinct uninterned symbol whose name is also `foo'. (setq sym (make-symbol "foo")) => foo (eq sym 'foo) => nil -- Function: intern name &optional obarray This function returns the interned symbol whose name is NAME. If there is no such symbol in the obarray OBARRAY, `intern' creates a new one, adds it to the obarray, and returns it. If OBARRAY is omitted, the value of the global variable `obarray' is used. (setq sym (intern "foo")) => foo (eq sym 'foo) => t (setq sym1 (intern "foo" other-obarray)) => foo (eq sym1 'foo) => nil Common Lisp note: In Common Lisp, you can intern an existing symbol in an obarray. In Emacs Lisp, you cannot do this, because the argument to `intern' must be a string, not a symbol. -- Function: intern-soft name &optional obarray This function returns the symbol in OBARRAY whose name is NAME, or `nil' if OBARRAY has no symbol with that name. Therefore, you can use `intern-soft' to test whether a symbol with a given name is already interned. If OBARRAY is omitted, the value of the global variable `obarray' is used. The argument NAME may also be a symbol; in that case, the function returns NAME if NAME is interned in the specified obarray, and otherwise `nil'. (intern-soft "frazzle") ; No such symbol exists. => nil (make-symbol "frazzle") ; Create an uninterned one. => frazzle (intern-soft "frazzle") ; That one cannot be found. => nil (setq sym (intern "frazzle")) ; Create an interned one. => frazzle (intern-soft "frazzle") ; That one can be found! => frazzle (eq sym 'frazzle) ; And it is the same one. => t -- Variable: obarray This variable is the standard obarray for use by `intern' and `read'. -- Function: mapatoms function &optional obarray This function calls FUNCTION once with each symbol in the obarray OBARRAY. Then it returns `nil'. If OBARRAY is omitted, it defaults to the value of `obarray', the standard obarray for ordinary symbols. (setq count 0) => 0 (defun count-syms (s) (setq count (1+ count))) => count-syms (mapatoms 'count-syms) => nil count => 1871 See `documentation' in *note Accessing Documentation::, for another example using `mapatoms'. -- Function: unintern symbol &optional obarray This function deletes SYMBOL from the obarray OBARRAY. If `symbol' is not actually in the obarray, `unintern' does nothing. If OBARRAY is `nil', the current obarray is used. If you provide a string instead of a symbol as SYMBOL, it stands for a symbol name. Then `unintern' deletes the symbol (if any) in the obarray which has that name. If there is no such symbol, `unintern' does nothing. If `unintern' does delete a symbol, it returns `t'. Otherwise it returns `nil'.  File: elisp, Node: Property Lists, Prev: Creating Symbols, Up: Symbols 8.4 Property Lists ================== A "property list" ("plist" for short) is a list of paired elements. Each of the pairs associates a property name (usually a symbol) with a property or value. Every symbol has a cell that stores a property list (*note Symbol Components::). This property list is used to record information about the symbol, such as its variable documentation and the name of the file where it was defined. Property lists can also be used in other contexts. For instance, you can assign property lists to character positions in a string or buffer. *Note Text Properties::. The property names and values in a property list can be any Lisp objects, but the names are usually symbols. Property list functions compare the property names using `eq'. Here is an example of a property list, found on the symbol `progn' when the compiler is loaded: (lisp-indent-function 0 byte-compile byte-compile-progn) Here `lisp-indent-function' and `byte-compile' are property names, and the other two elements are the corresponding values. * Menu: * Plists and Alists:: Comparison of the advantages of property lists and association lists. * Symbol Plists:: Functions to access symbols' property lists. * Other Plists:: Accessing property lists stored elsewhere.  File: elisp, Node: Plists and Alists, Next: Symbol Plists, Up: Property Lists 8.4.1 Property Lists and Association Lists ------------------------------------------ Association lists (*note Association Lists::) are very similar to property lists. In contrast to association lists, the order of the pairs in the property list is not significant since the property names must be distinct. Property lists are better than association lists for attaching information to various Lisp function names or variables. If your program keeps all of its associations in one association list, it will typically need to search that entire list each time it checks for an association. This could be slow. By contrast, if you keep the same information in the property lists of the function names or variables themselves, each search will scan only the length of one property list, which is usually short. This is why the documentation for a variable is recorded in a property named `variable-documentation'. The byte compiler likewise uses properties to record those functions needing special treatment. However, association lists have their own advantages. Depending on your application, it may be faster to add an association to the front of an association list than to update a property. All properties for a symbol are stored in the same property list, so there is a possibility of a conflict between different uses of a property name. (For this reason, it is a good idea to choose property names that are probably unique, such as by beginning the property name with the program's usual name-prefix for variables and functions.) An association list may be used like a stack where associations are pushed on the front of the list and later discarded; this is not possible with a property list.  File: elisp, Node: Symbol Plists, Next: Other Plists, Prev: Plists and Alists, Up: Property Lists 8.4.2 Property List Functions for Symbols ----------------------------------------- -- Function: symbol-plist symbol This function returns the property list of SYMBOL. -- Function: setplist symbol plist This function sets SYMBOL's property list to PLIST. Normally, PLIST should be a well-formed property list, but this is not enforced. The return value is PLIST. (setplist 'foo '(a 1 b (2 3) c nil)) => (a 1 b (2 3) c nil) (symbol-plist 'foo) => (a 1 b (2 3) c nil) For symbols in special obarrays, which are not used for ordinary purposes, it may make sense to use the property list cell in a nonstandard fashion; in fact, the abbrev mechanism does so (*note Abbrevs::). -- Function: get symbol property This function finds the value of the property named PROPERTY in SYMBOL's property list. If there is no such property, `nil' is returned. Thus, there is no distinction between a value of `nil' and the absence of the property. The name PROPERTY is compared with the existing property names using `eq', so any object is a legitimate property. See `put' for an example. -- Function: put symbol property value This function puts VALUE onto SYMBOL's property list under the property name PROPERTY, replacing any previous property value. The `put' function returns VALUE. (put 'fly 'verb 'transitive) =>'transitive (put 'fly 'noun '(a buzzing little bug)) => (a buzzing little bug) (get 'fly 'verb) => transitive (symbol-plist 'fly) => (verb transitive noun (a buzzing little bug))  File: elisp, Node: Other Plists, Prev: Symbol Plists, Up: Property Lists 8.4.3 Property Lists Outside Symbols ------------------------------------ These functions are useful for manipulating property lists that are stored in places other than symbols: -- Function: plist-get plist property This returns the value of the PROPERTY property stored in the property list PLIST. It accepts a malformed PLIST argument. If PROPERTY is not found in the PLIST, it returns `nil'. For example, (plist-get '(foo 4) 'foo) => 4 (plist-get '(foo 4 bad) 'foo) => 4 (plist-get '(foo 4 bad) 'bad) => `nil' (plist-get '(foo 4 bad) 'bar) => nil -- Function: plist-put plist property value This stores VALUE as the value of the PROPERTY property in the property list PLIST. It may modify PLIST destructively, or it may construct a new list structure without altering the old. The function returns the modified property list, so you can store that back in the place where you got PLIST. For example, (setq my-plist '(bar t foo 4)) => (bar t foo 4) (setq my-plist (plist-put my-plist 'foo 69)) => (bar t foo 69) (setq my-plist (plist-put my-plist 'quux '(a))) => (bar t foo 69 quux (a)) You could define `put' in terms of `plist-put' as follows: (defun put (symbol prop value) (setplist symbol (plist-put (symbol-plist symbol) prop value))) -- Function: lax-plist-get plist property Like `plist-get' except that it compares properties using `equal' instead of `eq'. -- Function: lax-plist-put plist property value Like `plist-put' except that it compares properties using `equal' instead of `eq'. -- Function: plist-member plist property This returns non-`nil' if PLIST contains the given PROPERTY. Unlike `plist-get', this allows you to distinguish between a missing property and a property with the value `nil'. The value is actually the tail of PLIST whose `car' is PROPERTY.  File: elisp, Node: Evaluation, Next: Control Structures, Prev: Symbols, Up: Top 9 Evaluation ************ The "evaluation" of expressions in Emacs Lisp is performed by the "Lisp interpreter"--a program that receives a Lisp object as input and computes its "value as an expression". How it does this depends on the data type of the object, according to rules described in this chapter. The interpreter runs automatically to evaluate portions of your program, but can also be called explicitly via the Lisp primitive function `eval'. * Menu: * Intro Eval:: Evaluation in the scheme of things. * Forms:: How various sorts of objects are evaluated. * Quoting:: Avoiding evaluation (to put constants in the program). * Eval:: How to invoke the Lisp interpreter explicitly.  File: elisp, Node: Intro Eval, Next: Forms, Up: Evaluation 9.1 Introduction to Evaluation ============================== The Lisp interpreter, or evaluator, is the part of Emacs that computes the value of an expression that is given to it. When a function written in Lisp is called, the evaluator computes the value of the function by evaluating the expressions in the function body. Thus, running any Lisp program really means running the Lisp interpreter. A Lisp object that is intended for evaluation is called an "expression" or a "form". The fact that forms are data objects and not merely text is one of the fundamental differences between Lisp-like languages and typical programming languages. Any object can be evaluated, but in practice only numbers, symbols, lists and strings are evaluated very often. In subsequent sections, we will describe the details of what evaluation means for each kind of form. It is very common to read a Lisp form and then evaluate the form, but reading and evaluation are separate activities, and either can be performed alone. Reading per se does not evaluate anything; it converts the printed representation of a Lisp object to the object itself. It is up to the caller of `read' to specify whether this object is a form to be evaluated, or serves some entirely different purpose. *Note Input Functions::. Evaluation is a recursive process, and evaluating a form often involves evaluating parts within that form. For instance, when you evaluate a "function call" form such as `(car x)', Emacs first evaluates the argument (the subform `x'). After evaluating the argument, Emacs "executes" the function (`car'), and if the function is written in Lisp, execution works by evaluating the "body" of the function. (In this example, however, `car' is not a Lisp function; it is a primitive function implemented in C.) *Note Functions::, for more information about functions and function calls. Evaluation takes place in a context called the "environment", which consists of the current values and bindings of all Lisp variables (*note Variables::).(1) Whenever a form refers to a variable without creating a new binding for it, the variable evaluates to the value given by the current environment. Evaluating a form may create a new environment for recursive evaluation, by binding variables (*note Local Variables::). Such environments are temporary, and vanish when the evaluation of the form is complete. Evaluating a form may also make changes that persist; these changes are called "side effects". An example of a form that produces a side effect is `(setq foo 1)'. Do not confuse evaluation with command key interpretation. The editor command loop translates keyboard input into a command (an interactively callable function) using the active keymaps, and then uses `call-interactively' to execute that command. Executing the command usually involves evaluation, if the command is written in Lisp; however, this step is not considered a part of command key interpretation. *Note Command Loop::. ---------- Footnotes ---------- (1) This definition of "environment" is specifically not intended to include all the data that can affect the result of a program.  File: elisp, Node: Forms, Next: Quoting, Prev: Intro Eval, Up: Evaluation 9.2 Kinds of Forms ================== A Lisp object that is intended to be evaluated is called a "form". How Emacs evaluates a form depends on its data type. Emacs has three different kinds of form that are evaluated differently: symbols, lists, and "all other types." This section describes all three kinds, one by one, starting with the "all other types" which are self-evaluating forms. * Menu: * Self-Evaluating Forms:: Forms that evaluate to themselves. * Symbol Forms:: Symbols evaluate as variables. * Classifying Lists:: How to distinguish various sorts of list forms. * Function Indirection:: When a symbol appears as the car of a list, we find the real function via the symbol. * Function Forms:: Forms that call functions. * Macro Forms:: Forms that call macros. * Special Forms:: "Special forms" are idiosyncratic primitives, most of them extremely important. * Autoloading:: Functions set up to load files containing their real definitions.  File: elisp, Node: Self-Evaluating Forms, Next: Symbol Forms, Up: Forms 9.2.1 Self-Evaluating Forms --------------------------- A "self-evaluating form" is any form that is not a list or symbol. Self-evaluating forms evaluate to themselves: the result of evaluation is the same object that was evaluated. Thus, the number 25 evaluates to 25, and the string `"foo"' evaluates to the string `"foo"'. Likewise, evaluating a vector does not cause evaluation of the elements of the vector--it returns the same vector with its contents unchanged. '123 ; A number, shown without evaluation. => 123 123 ; Evaluated as usual--result is the same. => 123 (eval '123) ; Evaluated "by hand"--result is the same. => 123 (eval (eval '123)) ; Evaluating twice changes nothing. => 123 It is common to write numbers, characters, strings, and even vectors in Lisp code, taking advantage of the fact that they self-evaluate. However, it is quite unusual to do this for types that lack a read syntax, because there's no way to write them textually. It is possible to construct Lisp expressions containing these types by means of a Lisp program. Here is an example: ;; Build an expression containing a buffer object. (setq print-exp (list 'print (current-buffer))) => (print #) ;; Evaluate it. (eval print-exp) -| # => #  File: elisp, Node: Symbol Forms, Next: Classifying Lists, Prev: Self-Evaluating Forms, Up: Forms 9.2.2 Symbol Forms ------------------ When a symbol is evaluated, it is treated as a variable. The result is the variable's value, if it has one. If it has none (if its value cell is void), an error is signaled. For more information on the use of variables, see *note Variables::. In the following example, we set the value of a symbol with `setq'. Then we evaluate the symbol, and get back the value that `setq' stored. (setq a 123) => 123 (eval 'a) => 123 a => 123 The symbols `nil' and `t' are treated specially, so that the value of `nil' is always `nil', and the value of `t' is always `t'; you cannot set or bind them to any other values. Thus, these two symbols act like self-evaluating forms, even though `eval' treats them like any other symbol. A symbol whose name starts with `:' also self-evaluates in the same way; likewise, its value ordinarily cannot be changed. *Note Constant Variables::.  File: elisp, Node: Classifying Lists, Next: Function Indirection, Prev: Symbol Forms, Up: Forms 9.2.3 Classification of List Forms ---------------------------------- A form that is a nonempty list is either a function call, a macro call, or a special form, according to its first element. These three kinds of forms are evaluated in different ways, described below. The remaining list elements constitute the "arguments" for the function, macro, or special form. The first step in evaluating a nonempty list is to examine its first element. This element alone determines what kind of form the list is and how the rest of the list is to be processed. The first element is _not_ evaluated, as it would be in some Lisp dialects such as Scheme.  File: elisp, Node: Function Indirection, Next: Function Forms, Prev: Classifying Lists, Up: Forms 9.2.4 Symbol Function Indirection --------------------------------- If the first element of the list is a symbol then evaluation examines the symbol's function cell, and uses its contents instead of the original symbol. If the contents are another symbol, this process, called "symbol function indirection", is repeated until it obtains a non-symbol. *Note Function Names::, for more information about symbol function indirection. One possible consequence of this process is an infinite loop, in the event that a symbol's function cell refers to the same symbol. Or a symbol may have a void function cell, in which case the subroutine `symbol-function' signals a `void-function' error. But if neither of these things happens, we eventually obtain a non-symbol, which ought to be a function or other suitable object. More precisely, we should now have a Lisp function (a lambda expression), a byte-code function, a primitive function, a Lisp macro, a special form, or an autoload object. Each of these types is a case described in one of the following sections. If the object is not one of these types, Emacs signals an `invalid-function' error. The following example illustrates the symbol indirection process. We use `fset' to set the function cell of a symbol and `symbol-function' to get the function cell contents (*note Function Cells::). Specifically, we store the symbol `car' into the function cell of `first', and the symbol `first' into the function cell of `erste'. ;; Build this function cell linkage: ;; ------------- ----- ------- ------- ;; | # | <-- | car | <-- | first | <-- | erste | ;; ------------- ----- ------- ------- (symbol-function 'car) => # (fset 'first 'car) => car (fset 'erste 'first) => first (erste '(1 2 3)) ; Call the function referenced by `erste'. => 1 By contrast, the following example calls a function without any symbol function indirection, because the first element is an anonymous Lisp function, not a symbol. ((lambda (arg) (erste arg)) '(1 2 3)) => 1 Executing the function itself evaluates its body; this does involve symbol function indirection when calling `erste'. The built-in function `indirect-function' provides an easy way to perform symbol function indirection explicitly. -- Function: indirect-function function &optional noerror This function returns the meaning of FUNCTION as a function. If FUNCTION is a symbol, then it finds FUNCTION's function definition and starts over with that value. If FUNCTION is not a symbol, then it returns FUNCTION itself. This function signals a `void-function' error if the final symbol is unbound and optional argument NOERROR is `nil' or omitted. Otherwise, if NOERROR is non-`nil', it returns `nil' if the final symbol is unbound. It signals a `cyclic-function-indirection' error if there is a loop in the chain of symbols. Here is how you could define `indirect-function' in Lisp: (defun indirect-function (function) (if (symbolp function) (indirect-function (symbol-function function)) function))  File: elisp, Node: Function Forms, Next: Macro Forms, Prev: Function Indirection, Up: Forms 9.2.5 Evaluation of Function Forms ---------------------------------- If the first element of a list being evaluated is a Lisp function object, byte-code object or primitive function object, then that list is a "function call". For example, here is a call to the function `+': (+ 1 x) The first step in evaluating a function call is to evaluate the remaining elements of the list from left to right. The results are the actual argument values, one value for each list element. The next step is to call the function with this list of arguments, effectively using the function `apply' (*note Calling Functions::). If the function is written in Lisp, the arguments are used to bind the argument variables of the function (*note Lambda Expressions::); then the forms in the function body are evaluated in order, and the value of the last body form becomes the value of the function call.  File: elisp, Node: Macro Forms, Next: Special Forms, Prev: Function Forms, Up: Forms 9.2.6 Lisp Macro Evaluation --------------------------- If the first element of a list being evaluated is a macro object, then the list is a "macro call". When a macro call is evaluated, the elements of the rest of the list are _not_ initially evaluated. Instead, these elements themselves are used as the arguments of the macro. The macro definition computes a replacement form, called the "expansion" of the macro, to be evaluated in place of the original form. The expansion may be any sort of form: a self-evaluating constant, a symbol, or a list. If the expansion is itself a macro call, this process of expansion repeats until some other sort of form results. Ordinary evaluation of a macro call finishes by evaluating the expansion. However, the macro expansion is not necessarily evaluated right away, or at all, because other programs also expand macro calls, and they may or may not evaluate the expansions. Normally, the argument expressions are not evaluated as part of computing the macro expansion, but instead appear as part of the expansion, so they are computed when the expansion is evaluated. For example, given a macro defined as follows: (defmacro cadr (x) (list 'car (list 'cdr x))) an expression such as `(cadr (assq 'handler list))' is a macro call, and its expansion is: (car (cdr (assq 'handler list))) Note that the argument `(assq 'handler list)' appears in the expansion. *Note Macros::, for a complete description of Emacs Lisp macros.  File: elisp, Node: Special Forms, Next: Autoloading, Prev: Macro Forms, Up: Forms 9.2.7 Special Forms ------------------- A "special form" is a primitive function specially marked so that its arguments are not all evaluated. Most special forms define control structures or perform variable bindings--things which functions cannot do. Each special form has its own rules for which arguments are evaluated and which are used without evaluation. Whether a particular argument is evaluated may depend on the results of evaluating other arguments. Here is a list, in alphabetical order, of all of the special forms in Emacs Lisp with a reference to where each is described. `and' *note Combining Conditions:: `catch' *note Catch and Throw:: `cond' *note Conditionals:: `condition-case' *note Handling Errors:: `defconst' *note Defining Variables:: `defmacro' *note Defining Macros:: `defun' *note Defining Functions:: `defvar' *note Defining Variables:: `function' *note Anonymous Functions:: `if' *note Conditionals:: `interactive' *note Interactive Call:: `let' `let*' *note Local Variables:: `or' *note Combining Conditions:: `prog1' `prog2' `progn' *note Sequencing:: `quote' *note Quoting:: `save-current-buffer' *note Current Buffer:: `save-excursion' *note Excursions:: `save-restriction' *note Narrowing:: `save-window-excursion' *note Window Configurations:: `setq' *note Setting Variables:: `setq-default' *note Creating Buffer-Local:: `track-mouse' *note Mouse Tracking:: `unwind-protect' *note Nonlocal Exits:: `while' *note Iteration:: `with-output-to-temp-buffer' *note Temporary Displays:: Common Lisp note: Here are some comparisons of special forms in GNU Emacs Lisp and Common Lisp. `setq', `if', and `catch' are special forms in both Emacs Lisp and Common Lisp. `defun' is a special form in Emacs Lisp, but a macro in Common Lisp. `save-excursion' is a special form in Emacs Lisp, but doesn't exist in Common Lisp. `throw' is a special form in Common Lisp (because it must be able to throw multiple values), but it is a function in Emacs Lisp (which doesn't have multiple values).  File: elisp, Node: Autoloading, Prev: Special Forms, Up: Forms 9.2.8 Autoloading ----------------- The "autoload" feature allows you to call a function or macro whose function definition has not yet been loaded into Emacs. It specifies which file contains the definition. When an autoload object appears as a symbol's function definition, calling that symbol as a function automatically loads the specified file; then it calls the real definition loaded from that file. *Note Autoload::.  File: elisp, Node: Quoting, Next: Eval, Prev: Forms, Up: Evaluation 9.3 Quoting =========== The special form `quote' returns its single argument, as written, without evaluating it. This provides a way to include constant symbols and lists, which are not self-evaluating objects, in a program. (It is not necessary to quote self-evaluating objects such as numbers, strings, and vectors.) -- Special Form: quote object This special form returns OBJECT, without evaluating it. Because `quote' is used so often in programs, Lisp provides a convenient read syntax for it. An apostrophe character (`'') followed by a Lisp object (in read syntax) expands to a list whose first element is `quote', and whose second element is the object. Thus, the read syntax `'x' is an abbreviation for `(quote x)'. Here are some examples of expressions that use `quote': (quote (+ 1 2)) => (+ 1 2) (quote foo) => foo 'foo => foo ''foo => (quote foo) '(quote foo) => (quote foo) ['foo] => [(quote foo)] Other quoting constructs include `function' (*note Anonymous Functions::), which causes an anonymous lambda expression written in Lisp to be compiled, and ``' (*note Backquote::), which is used to quote only part of a list, while computing and substituting other parts.  File: elisp, Node: Eval, Prev: Quoting, Up: Evaluation 9.4 Eval ======== Most often, forms are evaluated automatically, by virtue of their occurrence in a program being run. On rare occasions, you may need to write code that evaluates a form that is computed at run time, such as after reading a form from text being edited or getting one from a property list. On these occasions, use the `eval' function. The functions and variables described in this section evaluate forms, specify limits to the evaluation process, or record recently returned values. Loading a file also does evaluation (*note Loading::). It is generally cleaner and more flexible to store a function in a data structure, and call it with `funcall' or `apply', than to store an expression in the data structure and evaluate it. Using functions provides the ability to pass information to them as arguments. -- Function: eval form This is the basic function evaluating an expression. It evaluates FORM in the current environment and returns the result. How the evaluation proceeds depends on the type of the object (*note Forms::). Since `eval' is a function, the argument expression that appears in a call to `eval' is evaluated twice: once as preparation before `eval' is called, and again by the `eval' function itself. Here is an example: (setq foo 'bar) => bar (setq bar 'baz) => baz ;; Here `eval' receives argument `foo' (eval 'foo) => bar ;; Here `eval' receives argument `bar', which is the value of `foo' (eval foo) => baz The number of currently active calls to `eval' is limited to `max-lisp-eval-depth' (see below). -- Command: eval-region start end &optional stream read-function This function evaluates the forms in the current buffer in the region defined by the positions START and END. It reads forms from the region and calls `eval' on them until the end of the region is reached, or until an error is signaled and not handled. By default, `eval-region' does not produce any output. However, if STREAM is non-`nil', any output produced by output functions (*note Output Functions::), as well as the values that result from evaluating the expressions in the region are printed using STREAM. *Note Output Streams::. If READ-FUNCTION is non-`nil', it should be a function, which is used instead of `read' to read expressions one by one. This function is called with one argument, the stream for reading input. You can also use the variable `load-read-function' (*note How Programs Do Loading: Definition of load-read-function.) to specify this function, but it is more robust to use the READ-FUNCTION argument. `eval-region' does not move point. It always returns `nil'. -- Command: eval-buffer &optional buffer-or-name stream filename unibyte print This is similar to `eval-region', but the arguments provide different optional features. `eval-buffer' operates on the entire accessible portion of buffer BUFFER-OR-NAME. BUFFER-OR-NAME can be a buffer, a buffer name (a string), or `nil' (or omitted), which means to use the current buffer. STREAM is used as in `eval-region', unless STREAM is `nil' and PRINT non-`nil'. In that case, values that result from evaluating the expressions are still discarded, but the output of the output functions is printed in the echo area. FILENAME is the file name to use for `load-history' (*note Unloading::), and defaults to `buffer-file-name' (*note Buffer File Name::). If UNIBYTE is non-`nil', `read' converts strings to unibyte whenever possible. `eval-current-buffer' is an alias for this command. -- User Option: max-lisp-eval-depth This variable defines the maximum depth allowed in calls to `eval', `apply', and `funcall' before an error is signaled (with error message `"Lisp nesting exceeds max-lisp-eval-depth"'). This limit, with the associated error when it is exceeded, is one way Emacs Lisp avoids infinite recursion on an ill-defined function. If you increase the value of `max-lisp-eval-depth' too much, such code can cause stack overflow instead. The depth limit counts internal uses of `eval', `apply', and `funcall', such as for calling the functions mentioned in Lisp expressions, and recursive evaluation of function call arguments and function body forms, as well as explicit calls in Lisp code. The default value of this variable is 400. If you set it to a value less than 100, Lisp will reset it to 100 if the given value is reached. Entry to the Lisp debugger increases the value, if there is little room left, to make sure the debugger itself has room to execute. `max-specpdl-size' provides another limit on nesting. *Note Local Variables: Definition of max-specpdl-size. -- Variable: values The value of this variable is a list of the values returned by all the expressions that were read, evaluated, and printed from buffers (including the minibuffer) by the standard Emacs commands which do this. (Note that this does _not_ include evaluation in `*ielm*' buffers, nor evaluation using `C-j' in `lisp-interaction-mode'.) The elements are ordered most recent first. (setq x 1) => 1 (list 'A (1+ 2) auto-save-default) => (A 3 t) values => ((A 3 t) 1 ...) This variable is useful for referring back to values of forms recently evaluated. It is generally a bad idea to print the value of `values' itself, since this may be very long. Instead, examine particular elements, like this: ;; Refer to the most recent evaluation result. (nth 0 values) => (A 3 t) ;; That put a new element on, ;; so all elements move back one. (nth 1 values) => (A 3 t) ;; This gets the element that was next-to-most-recent ;; before this example. (nth 3 values) => 1  File: elisp, Node: Control Structures, Next: Variables, Prev: Evaluation, Up: Top 10 Control Structures ********************* A Lisp program consists of expressions or "forms" (*note Forms::). We control the order of execution of these forms by enclosing them in "control structures". Control structures are special forms which control when, whether, or how many times to execute the forms they contain. The simplest order of execution is sequential execution: first form A, then form B, and so on. This is what happens when you write several forms in succession in the body of a function, or at top level in a file of Lisp code--the forms are executed in the order written. We call this "textual order". For example, if a function body consists of two forms A and B, evaluation of the function evaluates first A and then B. The result of evaluating B becomes the value of the function. Explicit control structures make possible an order of execution other than sequential. Emacs Lisp provides several kinds of control structure, including other varieties of sequencing, conditionals, iteration, and (controlled) jumps--all discussed below. The built-in control structures are special forms since their subforms are not necessarily evaluated or not evaluated sequentially. You can use macros to define your own control structure constructs (*note Macros::). * Menu: * Sequencing:: Evaluation in textual order. * Conditionals:: `if', `cond', `when', `unless'. * Combining Conditions:: `and', `or', `not'. * Iteration:: `while' loops. * Nonlocal Exits:: Jumping out of a sequence.  File: elisp, Node: Sequencing, Next: Conditionals, Up: Control Structures 10.1 Sequencing =============== Evaluating forms in the order they appear is the most common way control passes from one form to another. In some contexts, such as in a function body, this happens automatically. Elsewhere you must use a control structure construct to do this: `progn', the simplest control construct of Lisp. A `progn' special form looks like this: (progn A B C ...) and it says to execute the forms A, B, C, and so on, in that order. These forms are called the "body" of the `progn' form. The value of the last form in the body becomes the value of the entire `progn'. `(progn)' returns `nil'. In the early days of Lisp, `progn' was the only way to execute two or more forms in succession and use the value of the last of them. But programmers found they often needed to use a `progn' in the body of a function, where (at that time) only one form was allowed. So the body of a function was made into an "implicit `progn'": several forms are allowed just as in the body of an actual `progn'. Many other control structures likewise contain an implicit `progn'. As a result, `progn' is not used as much as it was many years ago. It is needed now most often inside an `unwind-protect', `and', `or', or in the THEN-part of an `if'. -- Special Form: progn forms... This special form evaluates all of the FORMS, in textual order, returning the result of the final form. (progn (print "The first form") (print "The second form") (print "The third form")) -| "The first form" -| "The second form" -| "The third form" => "The third form" Two other control constructs likewise evaluate a series of forms but return a different value: -- Special Form: prog1 form1 forms... This special form evaluates FORM1 and all of the FORMS, in textual order, returning the result of FORM1. (prog1 (print "The first form") (print "The second form") (print "The third form")) -| "The first form" -| "The second form" -| "The third form" => "The first form" Here is a way to remove the first element from a list in the variable `x', then return the value of that former element: (prog1 (car x) (setq x (cdr x))) -- Special Form: prog2 form1 form2 forms... This special form evaluates FORM1, FORM2, and all of the following FORMS, in textual order, returning the result of FORM2. (prog2 (print "The first form") (print "The second form") (print "The third form")) -| "The first form" -| "The second form" -| "The third form" => "The second form"  File: elisp, Node: Conditionals, Next: Combining Conditions, Prev: Sequencing, Up: Control Structures 10.2 Conditionals ================= Conditional control structures choose among alternatives. Emacs Lisp has four conditional forms: `if', which is much the same as in other languages; `when' and `unless', which are variants of `if'; and `cond', which is a generalized case statement. -- Special Form: if condition then-form else-forms... `if' chooses between the THEN-FORM and the ELSE-FORMS based on the value of CONDITION. If the evaluated CONDITION is non-`nil', THEN-FORM is evaluated and the result returned. Otherwise, the ELSE-FORMS are evaluated in textual order, and the value of the last one is returned. (The ELSE part of `if' is an example of an implicit `progn'. *Note Sequencing::.) If CONDITION has the value `nil', and no ELSE-FORMS are given, `if' returns `nil'. `if' is a special form because the branch that is not selected is never evaluated--it is ignored. Thus, in the example below, `true' is not printed because `print' is never called. (if nil (print 'true) 'very-false) => very-false -- Macro: when condition then-forms... This is a variant of `if' where there are no ELSE-FORMS, and possibly several THEN-FORMS. In particular, (when CONDITION A B C) is entirely equivalent to (if CONDITION (progn A B C) nil) -- Macro: unless condition forms... This is a variant of `if' where there is no THEN-FORM: (unless CONDITION A B C) is entirely equivalent to (if CONDITION nil A B C) -- Special Form: cond clause... `cond' chooses among an arbitrary number of alternatives. Each CLAUSE in the `cond' must be a list. The CAR of this list is the CONDITION; the remaining elements, if any, the BODY-FORMS. Thus, a clause looks like this: (CONDITION BODY-FORMS...) `cond' tries the clauses in textual order, by evaluating the CONDITION of each clause. If the value of CONDITION is non-`nil', the clause "succeeds"; then `cond' evaluates its BODY-FORMS, and the value of the last of BODY-FORMS becomes the value of the `cond'. The remaining clauses are ignored. If the value of CONDITION is `nil', the clause "fails," so the `cond' moves on to the following clause, trying its CONDITION. If every CONDITION evaluates to `nil', so that every clause fails, `cond' returns `nil'. A clause may also look like this: (CONDITION) Then, if CONDITION is non-`nil' when tested, the value of CONDITION becomes the value of the `cond' form. The following example has four clauses, which test for the cases where the value of `x' is a number, string, buffer and symbol, respectively: (cond ((numberp x) x) ((stringp x) x) ((bufferp x) (setq temporary-hack x) ; multiple body-forms (buffer-name x)) ; in one clause ((symbolp x) (symbol-value x))) Often we want to execute the last clause whenever none of the previous clauses was successful. To do this, we use `t' as the CONDITION of the last clause, like this: `(t BODY-FORMS)'. The form `t' evaluates to `t', which is never `nil', so this clause never fails, provided the `cond' gets to it at all. For example, (setq a 5) (cond ((eq a 'hack) 'foo) (t "default")) => "default" This `cond' expression returns `foo' if the value of `a' is `hack', and returns the string `"default"' otherwise. Any conditional construct can be expressed with `cond' or with `if'. Therefore, the choice between them is a matter of style. For example: (if A B C) == (cond (A B) (t C))  File: elisp, Node: Combining Conditions, Next: Iteration, Prev: Conditionals, Up: Control Structures 10.3 Constructs for Combining Conditions ======================================== This section describes three constructs that are often used together with `if' and `cond' to express complicated conditions. The constructs `and' and `or' can also be used individually as kinds of multiple conditional constructs. -- Function: not condition This function tests for the falsehood of CONDITION. It returns `t' if CONDITION is `nil', and `nil' otherwise. The function `not' is identical to `null', and we recommend using the name `null' if you are testing for an empty list. -- Special Form: and conditions... The `and' special form tests whether all the CONDITIONS are true. It works by evaluating the CONDITIONS one by one in the order written. If any of the CONDITIONS evaluates to `nil', then the result of the `and' must be `nil' regardless of the remaining CONDITIONS; so `and' returns `nil' right away, ignoring the remaining CONDITIONS. If all the CONDITIONS turn out non-`nil', then the value of the last of them becomes the value of the `and' form. Just `(and)', with no CONDITIONS, returns `t', appropriate because all the CONDITIONS turned out non-`nil'. (Think about it; which one did not?) Here is an example. The first condition returns the integer 1, which is not `nil'. Similarly, the second condition returns the integer 2, which is not `nil'. The third condition is `nil', so the remaining condition is never evaluated. (and (print 1) (print 2) nil (print 3)) -| 1 -| 2 => nil Here is a more realistic example of using `and': (if (and (consp foo) (eq (car foo) 'x)) (message "foo is a list starting with x")) Note that `(car foo)' is not executed if `(consp foo)' returns `nil', thus avoiding an error. `and' expressions can also be written using either `if' or `cond'. Here's how: (and ARG1 ARG2 ARG3) == (if ARG1 (if ARG2 ARG3)) == (cond (ARG1 (cond (ARG2 ARG3)))) -- Special Form: or conditions... The `or' special form tests whether at least one of the CONDITIONS is true. It works by evaluating all the CONDITIONS one by one in the order written. If any of the CONDITIONS evaluates to a non-`nil' value, then the result of the `or' must be non-`nil'; so `or' returns right away, ignoring the remaining CONDITIONS. The value it returns is the non-`nil' value of the condition just evaluated. If all the CONDITIONS turn out `nil', then the `or' expression returns `nil'. Just `(or)', with no CONDITIONS, returns `nil', appropriate because all the CONDITIONS turned out `nil'. (Think about it; which one did not?) For example, this expression tests whether `x' is either `nil' or the integer zero: (or (eq x nil) (eq x 0)) Like the `and' construct, `or' can be written in terms of `cond'. For example: (or ARG1 ARG2 ARG3) == (cond (ARG1) (ARG2) (ARG3)) You could almost write `or' in terms of `if', but not quite: (if ARG1 ARG1 (if ARG2 ARG2 ARG3)) This is not completely equivalent because it can evaluate ARG1 or ARG2 twice. By contrast, `(or ARG1 ARG2 ARG3)' never evaluates any argument more than once.  File: elisp, Node: Iteration, Next: Nonlocal Exits, Prev: Combining Conditions, Up: Control Structures 10.4 Iteration ============== Iteration means executing part of a program repetitively. For example, you might want to repeat some computation once for each element of a list, or once for each integer from 0 to N. You can do this in Emacs Lisp with the special form `while': -- Special Form: while condition forms... `while' first evaluates CONDITION. If the result is non-`nil', it evaluates FORMS in textual order. Then it reevaluates CONDITION, and if the result is non-`nil', it evaluates FORMS again. This process repeats until CONDITION evaluates to `nil'. There is no limit on the number of iterations that may occur. The loop will continue until either CONDITION evaluates to `nil' or until an error or `throw' jumps out of it (*note Nonlocal Exits::). The value of a `while' form is always `nil'. (setq num 0) => 0 (while (< num 4) (princ (format "Iteration %d." num)) (setq num (1+ num))) -| Iteration 0. -| Iteration 1. -| Iteration 2. -| Iteration 3. => nil To write a "repeat...until" loop, which will execute something on each iteration and then do the end-test, put the body followed by the end-test in a `progn' as the first argument of `while', as shown here: (while (progn (forward-line 1) (not (looking-at "^$")))) This moves forward one line and continues moving by lines until it reaches an empty line. It is peculiar in that the `while' has no body, just the end test (which also does the real work of moving point). The `dolist' and `dotimes' macros provide convenient ways to write two common kinds of loops. -- Macro: dolist (var list [result]) body... This construct executes BODY once for each element of LIST, binding the variable VAR locally to hold the current element. Then it returns the value of evaluating RESULT, or `nil' if RESULT is omitted. For example, here is how you could use `dolist' to define the `reverse' function: (defun reverse (list) (let (value) (dolist (elt list value) (setq value (cons elt value))))) -- Macro: dotimes (var count [result]) body... This construct executes BODY once for each integer from 0 (inclusive) to COUNT (exclusive), binding the variable VAR to the integer for the current iteration. Then it returns the value of evaluating RESULT, or `nil' if RESULT is omitted. Here is an example of using `dotimes' to do something 100 times: (dotimes (i 100) (insert "I will not obey absurd orders\n"))  File: elisp, Node: Nonlocal Exits, Prev: Iteration, Up: Control Structures 10.5 Nonlocal Exits =================== A "nonlocal exit" is a transfer of control from one point in a program to another remote point. Nonlocal exits can occur in Emacs Lisp as a result of errors; you can also use them under explicit control. Nonlocal exits unbind all variable bindings made by the constructs being exited. * Menu: * Catch and Throw:: Nonlocal exits for the program's own purposes. * Examples of Catch:: Showing how such nonlocal exits can be written. * Errors:: How errors are signaled and handled. * Cleanups:: Arranging to run a cleanup form if an error happens.  File: elisp, Node: Catch and Throw, Next: Examples of Catch, Up: Nonlocal Exits 10.5.1 Explicit Nonlocal Exits: `catch' and `throw' --------------------------------------------------- Most control constructs affect only the flow of control within the construct itself. The function `throw' is the exception to this rule of normal program execution: it performs a nonlocal exit on request. (There are other exceptions, but they are for error handling only.) `throw' is used inside a `catch', and jumps back to that `catch'. For example: (defun foo-outer () (catch 'foo (foo-inner))) (defun foo-inner () ... (if x (throw 'foo t)) ...) The `throw' form, if executed, transfers control straight back to the corresponding `catch', which returns immediately. The code following the `throw' is not executed. The second argument of `throw' is used as the return value of the `catch'. The function `throw' finds the matching `catch' based on the first argument: it searches for a `catch' whose first argument is `eq' to the one specified in the `throw'. If there is more than one applicable `catch', the innermost one takes precedence. Thus, in the above example, the `throw' specifies `foo', and the `catch' in `foo-outer' specifies the same symbol, so that `catch' is the applicable one (assuming there is no other matching `catch' in between). Executing `throw' exits all Lisp constructs up to the matching `catch', including function calls. When binding constructs such as `let' or function calls are exited in this way, the bindings are unbound, just as they are when these constructs exit normally (*note Local Variables::). Likewise, `throw' restores the buffer and position saved by `save-excursion' (*note Excursions::), and the narrowing status saved by `save-restriction' and the window selection saved by `save-window-excursion' (*note Window Configurations::). It also runs any cleanups established with the `unwind-protect' special form when it exits that form (*note Cleanups::). The `throw' need not appear lexically within the `catch' that it jumps to. It can equally well be called from another function called within the `catch'. As long as the `throw' takes place chronologically after entry to the `catch', and chronologically before exit from it, it has access to that `catch'. This is why `throw' can be used in commands such as `exit-recursive-edit' that throw back to the editor command loop (*note Recursive Editing::). Common Lisp note: Most other versions of Lisp, including Common Lisp, have several ways of transferring control nonsequentially: `return', `return-from', and `go', for example. Emacs Lisp has only `throw'. -- Special Form: catch tag body... `catch' establishes a return point for the `throw' function. The return point is distinguished from other such return points by TAG, which may be any Lisp object except `nil'. The argument TAG is evaluated normally before the return point is established. With the return point in effect, `catch' evaluates the forms of the BODY in textual order. If the forms execute normally (without error or nonlocal exit) the value of the last body form is returned from the `catch'. If a `throw' is executed during the execution of BODY, specifying the same value TAG, the `catch' form exits immediately; the value it returns is whatever was specified as the second argument of `throw'. -- Function: throw tag value The purpose of `throw' is to return from a return point previously established with `catch'. The argument TAG is used to choose among the various existing return points; it must be `eq' to the value specified in the `catch'. If multiple return points match TAG, the innermost one is used. The argument VALUE is used as the value to return from that `catch'. If no return point is in effect with tag TAG, then a `no-catch' error is signaled with data `(TAG VALUE)'.  File: elisp, Node: Examples of Catch, Next: Errors, Prev: Catch and Throw, Up: Nonlocal Exits 10.5.2 Examples of `catch' and `throw' -------------------------------------- One way to use `catch' and `throw' is to exit from a doubly nested loop. (In most languages, this would be done with a "go to.") Here we compute `(foo I J)' for I and J varying from 0 to 9: (defun search-foo () (catch 'loop (let ((i 0)) (while (< i 10) (let ((j 0)) (while (< j 10) (if (foo i j) (throw 'loop (list i j))) (setq j (1+ j)))) (setq i (1+ i)))))) If `foo' ever returns non-`nil', we stop immediately and return a list of I and J. If `foo' always returns `nil', the `catch' returns normally, and the value is `nil', since that is the result of the `while'. Here are two tricky examples, slightly different, showing two return points at once. First, two return points with the same tag, `hack': (defun catch2 (tag) (catch tag (throw 'hack 'yes))) => catch2 (catch 'hack (print (catch2 'hack)) 'no) -| yes => no Since both return points have tags that match the `throw', it goes to the inner one, the one established in `catch2'. Therefore, `catch2' returns normally with value `yes', and this value is printed. Finally the second body form in the outer `catch', which is `'no', is evaluated and returned from the outer `catch'. Now let's change the argument given to `catch2': (catch 'hack (print (catch2 'quux)) 'no) => yes We still have two return points, but this time only the outer one has the tag `hack'; the inner one has the tag `quux' instead. Therefore, `throw' makes the outer `catch' return the value `yes'. The function `print' is never called, and the body-form `'no' is never evaluated.  File: elisp, Node: Errors, Next: Cleanups, Prev: Examples of Catch, Up: Nonlocal Exits 10.5.3 Errors ------------- When Emacs Lisp attempts to evaluate a form that, for some reason, cannot be evaluated, it "signals" an "error". When an error is signaled, Emacs's default reaction is to print an error message and terminate execution of the current command. This is the right thing to do in most cases, such as if you type `C-f' at the end of the buffer. In complicated programs, simple termination may not be what you want. For example, the program may have made temporary changes in data structures, or created temporary buffers that should be deleted before the program is finished. In such cases, you would use `unwind-protect' to establish "cleanup expressions" to be evaluated in case of error. (*Note Cleanups::.) Occasionally, you may wish the program to continue execution despite an error in a subroutine. In these cases, you would use `condition-case' to establish "error handlers" to recover control in case of error. Resist the temptation to use error handling to transfer control from one part of the program to another; use `catch' and `throw' instead. *Note Catch and Throw::. * Menu: * Signaling Errors:: How to report an error. * Processing of Errors:: What Emacs does when you report an error. * Handling Errors:: How you can trap errors and continue execution. * Error Symbols:: How errors are classified for trapping them.  File: elisp, Node: Signaling Errors, Next: Processing of Errors, Up: Errors 10.5.3.1 How to Signal an Error ............................... "Signaling" an error means beginning error processing. Error processing normally aborts all or part of the running program and returns to a point that is set up to handle the error (*note Processing of Errors::). Here we describe how to signal an error. Most errors are signaled "automatically" within Lisp primitives which you call for other purposes, such as if you try to take the CAR of an integer or move forward a character at the end of the buffer. You can also signal errors explicitly with the functions `error' and `signal'. Quitting, which happens when the user types `C-g', is not considered an error, but it is handled almost like an error. *Note Quitting::. Every error specifies an error message, one way or another. The message should state what is wrong ("File does not exist"), not how things ought to be ("File must exist"). The convention in Emacs Lisp is that error messages should start with a capital letter, but should not end with any sort of punctuation. -- Function: error format-string &rest args This function signals an error with an error message constructed by applying `format' (*note Formatting Strings::) to FORMAT-STRING and ARGS. These examples show typical uses of `error': (error "That is an error -- try something else") error--> That is an error -- try something else (error "You have committed %d errors" 10) error--> You have committed 10 errors `error' works by calling `signal' with two arguments: the error symbol `error', and a list containing the string returned by `format'. *Warning:* If you want to use your own string as an error message verbatim, don't just write `(error STRING)'. If STRING contains `%', it will be interpreted as a format specifier, with undesirable results. Instead, use `(error "%s" STRING)'. -- Function: signal error-symbol data This function signals an error named by ERROR-SYMBOL. The argument DATA is a list of additional Lisp objects relevant to the circumstances of the error. The argument ERROR-SYMBOL must be an "error symbol"--a symbol bearing a property `error-conditions' whose value is a list of condition names. This is how Emacs Lisp classifies different sorts of errors. *Note Error Symbols::, for a description of error symbols, error conditions and condition names. If the error is not handled, the two arguments are used in printing the error message. Normally, this error message is provided by the `error-message' property of ERROR-SYMBOL. If DATA is non-`nil', this is followed by a colon and a comma separated list of the unevaluated elements of DATA. For `error', the error message is the CAR of DATA (that must be a string). Subcategories of `file-error' are handled specially. The number and significance of the objects in DATA depends on ERROR-SYMBOL. For example, with a `wrong-type-argument' error, there should be two objects in the list: a predicate that describes the type that was expected, and the object that failed to fit that type. Both ERROR-SYMBOL and DATA are available to any error handlers that handle the error: `condition-case' binds a local variable to a list of the form `(ERROR-SYMBOL . DATA)' (*note Handling Errors::). The function `signal' never returns (though in older Emacs versions it could sometimes return). (signal 'wrong-number-of-arguments '(x y)) error--> Wrong number of arguments: x, y (signal 'no-such-error '("My unknown error condition")) error--> peculiar error: "My unknown error condition" Common Lisp note: Emacs Lisp has nothing like the Common Lisp concept of continuable errors.  File: elisp, Node: Processing of Errors, Next: Handling Errors, Prev: Signaling Errors, Up: Errors 10.5.3.2 How Emacs Processes Errors ................................... When an error is signaled, `signal' searches for an active "handler" for the error. A handler is a sequence of Lisp expressions designated to be executed if an error happens in part of the Lisp program. If the error has an applicable handler, the handler is executed, and control resumes following the handler. The handler executes in the environment of the `condition-case' that established it; all functions called within that `condition-case' have already been exited, and the handler cannot return to them. If there is no applicable handler for the error, it terminates the current command and returns control to the editor command loop. (The command loop has an implicit handler for all kinds of errors.) The command loop's handler uses the error symbol and associated data to print an error message. You can use the variable `command-error-function' to control how this is done: -- Variable: command-error-function This variable, if non-`nil', specifies a function to use to handle errors that return control to the Emacs command loop. The function should take three arguments: DATA, a list of the same form that `condition-case' would bind to its variable; CONTEXT, a string describing the situation in which the error occurred, or (more often) `nil'; and CALLER, the Lisp function which called the primitive that signaled the error. An error that has no explicit handler may call the Lisp debugger. The debugger is enabled if the variable `debug-on-error' (*note Error Debugging::) is non-`nil'. Unlike error handlers, the debugger runs in the environment of the error, so that you can examine values of variables precisely as they were at the time of the error.  File: elisp, Node: Handling Errors, Next: Error Symbols, Prev: Processing of Errors, Up: Errors 10.5.3.3 Writing Code to Handle Errors ...................................... The usual effect of signaling an error is to terminate the command that is running and return immediately to the Emacs editor command loop. You can arrange to trap errors occurring in a part of your program by establishing an error handler, with the special form `condition-case'. A simple example looks like this: (condition-case nil (delete-file filename) (error nil)) This deletes the file named FILENAME, catching any error and returning `nil' if an error occurs(1). The `condition-case' construct is often used to trap errors that are predictable, such as failure to open a file in a call to `insert-file-contents'. It is also used to trap errors that are totally unpredictable, such as when the program evaluates an expression read from the user. The second argument of `condition-case' is called the "protected form". (In the example above, the protected form is a call to `delete-file'.) The error handlers go into effect when this form begins execution and are deactivated when this form returns. They remain in effect for all the intervening time. In particular, they are in effect during the execution of functions called by this form, in their subroutines, and so on. This is a good thing, since, strictly speaking, errors can be signaled only by Lisp primitives (including `signal' and `error') called by the protected form, not by the protected form itself. The arguments after the protected form are handlers. Each handler lists one or more "condition names" (which are symbols) to specify which errors it will handle. The error symbol specified when an error is signaled also defines a list of condition names. A handler applies to an error if they have any condition names in common. In the example above, there is one handler, and it specifies one condition name, `error', which covers all errors. The search for an applicable handler checks all the established handlers starting with the most recently established one. Thus, if two nested `condition-case' forms offer to handle the same error, the inner of the two gets to handle it. If an error is handled by some `condition-case' form, this ordinarily prevents the debugger from being run, even if `debug-on-error' says this error should invoke the debugger. If you want to be able to debug errors that are caught by a `condition-case', set the variable `debug-on-signal' to a non-`nil' value. You can also specify that a particular handler should let the debugger run first, by writing `debug' among the conditions, like this: (condition-case nil (delete-file filename) ((debug error) nil)) The effect of `debug' here is only to prevent `condition-case' from suppressing the call to the debugger. Any given error will invoke the debugger only if `debug-on-error' and the other usual filtering mechanisms say it should. *Note Error Debugging::. Once Emacs decides that a certain handler handles the error, it returns control to that handler. To do so, Emacs unbinds all variable bindings made by binding constructs that are being exited, and executes the cleanups of all `unwind-protect' forms that are being exited. Once control arrives at the handler, the body of the handler executes normally. After execution of the handler body, execution returns from the `condition-case' form. Because the protected form is exited completely before execution of the handler, the handler cannot resume execution at the point of the error, nor can it examine variable bindings that were made within the protected form. All it can do is clean up and proceed. Error signaling and handling have some resemblance to `throw' and `catch' (*note Catch and Throw::), but they are entirely separate facilities. An error cannot be caught by a `catch', and a `throw' cannot be handled by an error handler (though using `throw' when there is no suitable `catch' signals an error that can be handled). -- Special Form: condition-case var protected-form handlers... This special form establishes the error handlers HANDLERS around the execution of PROTECTED-FORM. If PROTECTED-FORM executes without error, the value it returns becomes the value of the `condition-case' form; in this case, the `condition-case' has no effect. The `condition-case' form makes a difference when an error occurs during PROTECTED-FORM. Each of the HANDLERS is a list of the form `(CONDITIONS BODY...)'. Here CONDITIONS is an error condition name to be handled, or a list of condition names (which can include `debug' to allow the debugger to run before the handler); BODY is one or more Lisp expressions to be executed when this handler handles an error. Here are examples of handlers: (error nil) (arith-error (message "Division by zero")) ((arith-error file-error) (message "Either division by zero or failure to open a file")) Each error that occurs has an "error symbol" that describes what kind of error it is. The `error-conditions' property of this symbol is a list of condition names (*note Error Symbols::). Emacs searches all the active `condition-case' forms for a handler that specifies one or more of these condition names; the innermost matching `condition-case' handles the error. Within this `condition-case', the first applicable handler handles the error. After executing the body of the handler, the `condition-case' returns normally, using the value of the last form in the handler body as the overall value. The argument VAR is a variable. `condition-case' does not bind this variable when executing the PROTECTED-FORM, only when it handles an error. At that time, it binds VAR locally to an "error description", which is a list giving the particulars of the error. The error description has the form `(ERROR-SYMBOL . DATA)'. The handler can refer to this list to decide what to do. For example, if the error is for failure opening a file, the file name is the second element of DATA--the third element of the error description. If VAR is `nil', that means no variable is bound. Then the error symbol and associated data are not available to the handler. Sometimes it is necessary to re-throw a signal caught by `condition-case', for some outer-level handler to catch. Here's how to do that: (signal (car err) (cdr err)) where `err' is the error description variable, the first argument to `condition-case' whose error condition you want to re-throw. *Note Definition of signal::. -- Function: error-message-string error-description This function returns the error message string for a given error descriptor. It is useful if you want to handle an error by printing the usual error message for that error. *Note Definition of signal::. Here is an example of using `condition-case' to handle the error that results from dividing by zero. The handler displays the error message (but without a beep), then returns a very large number. (defun safe-divide (dividend divisor) (condition-case err ;; Protected form. (/ dividend divisor) ;; The handler. (arith-error ; Condition. ;; Display the usual message for this error. (message "%s" (error-message-string err)) 1000000))) => safe-divide (safe-divide 5 0) -| Arithmetic error: (arith-error) => 1000000 The handler specifies condition name `arith-error' so that it will handle only division-by-zero errors. Other kinds of errors will not be handled, at least not by this `condition-case'. Thus, (safe-divide nil 3) error--> Wrong type argument: number-or-marker-p, nil Here is a `condition-case' that catches all kinds of errors, including those signaled with `error': (setq baz 34) => 34 (condition-case err (if (eq baz 35) t ;; This is a call to the function `error'. (error "Rats! The variable %s was %s, not 35" 'baz baz)) ;; This is the handler; it is not a form. (error (princ (format "The error was: %s" err)) 2)) -| The error was: (error "Rats! The variable baz was 34, not 35") => 2 -- Macro: ignore-errors body... This construct executes BODY, ignoring any errors that occur during its execution. If the execution is without error, `ignore-errors' returns the value of the last form in BODY; otherwise, it returns `nil'. Here's the example at the beginning of this subsection rewritten using `ignore-errors': (ignore-errors (delete-file filename)) ---------- Footnotes ---------- (1) Actually, you should use `ignore-errors' in such a simple case; see below.  File: elisp, Node: Error Symbols, Prev: Handling Errors, Up: Errors 10.5.3.4 Error Symbols and Condition Names .......................................... When you signal an error, you specify an "error symbol" to specify the kind of error you have in mind. Each error has one and only one error symbol to categorize it. This is the finest classification of errors defined by the Emacs Lisp language. These narrow classifications are grouped into a hierarchy of wider classes called "error conditions", identified by "condition names". The narrowest such classes belong to the error symbols themselves: each error symbol is also a condition name. There are also condition names for more extensive classes, up to the condition name `error' which takes in all kinds of errors (but not `quit'). Thus, each error has one or more condition names: `error', the error symbol if that is distinct from `error', and perhaps some intermediate classifications. In order for a symbol to be an error symbol, it must have an `error-conditions' property which gives a list of condition names. This list defines the conditions that this kind of error belongs to. (The error symbol itself, and the symbol `error', should always be members of this list.) Thus, the hierarchy of condition names is defined by the `error-conditions' properties of the error symbols. Because quitting is not considered an error, the value of the `error-conditions' property of `quit' is just `(quit)'. In addition to the `error-conditions' list, the error symbol should have an `error-message' property whose value is a string to be printed when that error is signaled but not handled. If the error symbol has no `error-message' property or if the `error-message' property exists, but is not a string, the error message `peculiar error' is used. *Note Definition of signal::. Here is how we define a new error symbol, `new-error': (put 'new-error 'error-conditions '(error my-own-errors new-error)) => (error my-own-errors new-error) (put 'new-error 'error-message "A new error") => "A new error" This error has three condition names: `new-error', the narrowest classification; `my-own-errors', which we imagine is a wider classification; and `error', which is the widest of all. The error string should start with a capital letter but it should not end with a period. This is for consistency with the rest of Emacs. Naturally, Emacs will never signal `new-error' on its own; only an explicit call to `signal' (*note Definition of signal::) in your code can do this: (signal 'new-error '(x y)) error--> A new error: x, y This error can be handled through any of the three condition names. This example handles `new-error' and any other errors in the class `my-own-errors': (condition-case foo (bar nil t) (my-own-errors nil)) The significant way that errors are classified is by their condition names--the names used to match errors with handlers. An error symbol serves only as a convenient way to specify the intended error message and list of condition names. It would be cumbersome to give `signal' a list of condition names rather than one error symbol. By contrast, using only error symbols without condition names would seriously decrease the power of `condition-case'. Condition names make it possible to categorize errors at various levels of generality when you write an error handler. Using error symbols alone would eliminate all but the narrowest level of classification. *Note Standard Errors::, for a list of all the standard error symbols and their conditions.  File: elisp, Node: Cleanups, Prev: Errors, Up: Nonlocal Exits 10.5.4 Cleaning Up from Nonlocal Exits -------------------------------------- The `unwind-protect' construct is essential whenever you temporarily put a data structure in an inconsistent state; it permits you to make the data consistent again in the event of an error or throw. (Another more specific cleanup construct that is used only for changes in buffer contents is the atomic change group; *note Atomic Changes::.) -- Special Form: unwind-protect body-form cleanup-forms... `unwind-protect' executes BODY-FORM with a guarantee that the CLEANUP-FORMS will be evaluated if control leaves BODY-FORM, no matter how that happens. BODY-FORM may complete normally, or execute a `throw' out of the `unwind-protect', or cause an error; in all cases, the CLEANUP-FORMS will be evaluated. If BODY-FORM finishes normally, `unwind-protect' returns the value of BODY-FORM, after it evaluates the CLEANUP-FORMS. If BODY-FORM does not finish, `unwind-protect' does not return any value in the normal sense. Only BODY-FORM is protected by the `unwind-protect'. If any of the CLEANUP-FORMS themselves exits nonlocally (via a `throw' or an error), `unwind-protect' is _not_ guaranteed to evaluate the rest of them. If the failure of one of the CLEANUP-FORMS has the potential to cause trouble, then protect it with another `unwind-protect' around that form. The number of currently active `unwind-protect' forms counts, together with the number of local variable bindings, against the limit `max-specpdl-size' (*note Local Variables: Definition of max-specpdl-size.). For example, here we make an invisible buffer for temporary use, and make sure to kill it before finishing: (let ((buffer (get-buffer-create " *temp*"))) (with-current-buffer buffer (unwind-protect BODY-FORM (kill-buffer buffer)))) You might think that we could just as well write `(kill-buffer (current-buffer))' and dispense with the variable `buffer'. However, the way shown above is safer, if BODY-FORM happens to get an error after switching to a different buffer! (Alternatively, you could write a `save-current-buffer' around BODY-FORM, to ensure that the temporary buffer becomes current again in time to kill it.) Emacs includes a standard macro called `with-temp-buffer' which expands into more or less the code shown above (*note Current Buffer: Definition of with-temp-buffer.). Several of the macros defined in this manual use `unwind-protect' in this way. Here is an actual example derived from an FTP package. It creates a process (*note Processes::) to try to establish a connection to a remote machine. As the function `ftp-login' is highly susceptible to numerous problems that the writer of the function cannot anticipate, it is protected with a form that guarantees deletion of the process in the event of failure. Otherwise, Emacs might fill up with useless subprocesses. (let ((win nil)) (unwind-protect (progn (setq process (ftp-setup-buffer host file)) (if (setq win (ftp-login process host user password)) (message "Logged in") (error "Ftp login failed"))) (or win (and process (delete-process process))))) This example has a small bug: if the user types `C-g' to quit, and the quit happens immediately after the function `ftp-setup-buffer' returns but before the variable `process' is set, the process will not be killed. There is no easy way to fix this bug, but at least it is very unlikely.  File: elisp, Node: Variables, Next: Functions, Prev: Control Structures, Up: Top 11 Variables ************ A "variable" is a name used in a program to stand for a value. Nearly all programming languages have variables of some sort. In the text of a Lisp program, variables are written using the syntax for symbols. In Lisp, unlike most programming languages, programs are represented primarily as Lisp objects and only secondarily as text. The Lisp objects used for variables are symbols: the symbol name is the variable name, and the variable's value is stored in the value cell of the symbol. The use of a symbol as a variable is independent of its use as a function name. *Note Symbol Components::. The textual form of a Lisp program is given by the read syntax of the Lisp objects that constitute the program. Hence, a variable in a textual Lisp program is written using the read syntax for the symbol representing the variable. * Menu: * Global Variables:: Variable values that exist permanently, everywhere. * Constant Variables:: Certain "variables" have values that never change. * Local Variables:: Variable values that exist only temporarily. * Void Variables:: Symbols that lack values. * Defining Variables:: A definition says a symbol is used as a variable. * Tips for Defining:: Things you should think about when you define a variable. * Accessing Variables:: Examining values of variables whose names are known only at run time. * Setting Variables:: Storing new values in variables. * Variable Scoping:: How Lisp chooses among local and global values. * Buffer-Local Variables:: Variable values in effect only in one buffer. * File Local Variables:: Handling local variable lists in files. * Directory Local Variables:: Local variables common to all files in a directory. * Frame-Local Variables:: Frame-local bindings for variables. * Variable Aliases:: Variables that are aliases for other variables. * Variables with Restricted Values:: Non-constant variables whose value can _not_ be an arbitrary Lisp object.  File: elisp, Node: Global Variables, Next: Constant Variables, Up: Variables 11.1 Global Variables ===================== The simplest way to use a variable is "globally". This means that the variable has just one value at a time, and this value is in effect (at least for the moment) throughout the Lisp system. The value remains in effect until you specify a new one. When a new value replaces the old one, no trace of the old value remains in the variable. You specify a value for a symbol with `setq'. For example, (setq x '(a b)) gives the variable `x' the value `(a b)'. Note that `setq' is a special form (*note Special Forms::); it does not evaluate its first argument, the name of the variable, but it does evaluate the second argument, the new value. Once the variable has a value, you can refer to it by using the symbol itself as an expression. Thus, x => (a b) assuming the `setq' form shown above has already been executed. If you do set the same variable again, the new value replaces the old one: x => (a b) (setq x 4) => 4 x => 4  File: elisp, Node: Constant Variables, Next: Local Variables, Prev: Global Variables, Up: Variables 11.2 Variables that Never Change ================================ In Emacs Lisp, certain symbols normally evaluate to themselves. These include `nil' and `t', as well as any symbol whose name starts with `:' (these are called "keywords"). These symbols cannot be rebound, nor can their values be changed. Any attempt to set or bind `nil' or `t' signals a `setting-constant' error. The same is true for a keyword (a symbol whose name starts with `:'), if it is interned in the standard obarray, except that setting such a symbol to itself is not an error. nil == 'nil => nil (setq nil 500) error--> Attempt to set constant symbol: nil -- Function: keywordp object function returns `t' if OBJECT is a symbol whose name starts with `:', interned in the standard obarray, and returns `nil' otherwise. These constants are fundamentally different from the "constants" defined using the `defconst' special form (*note Defining Variables::). A `defconst' form serves to inform human readers that you do not intend to change the value of a variable, but Emacs does not raise an error if you actually change it.  File: elisp, Node: Local Variables, Next: Void Variables, Prev: Constant Variables, Up: Variables 11.3 Local Variables ==================== Global variables have values that last until explicitly superseded with new values. Sometimes it is useful to create variable values that exist temporarily--only until a certain part of the program finishes. These values are called "local", and the variables so used are called "local variables". For example, when a function is called, its argument variables receive new local values that last until the function exits. The `let' special form explicitly establishes new local values for specified variables; these last until exit from the `let' form. Establishing a local value saves away the variable's previous value (or lack of one). We say that the previous value is "shadowed" and "not visible". Both global and local values may be shadowed (*note Scope::). After the life span of the local value is over, the previous value (or lack of one) is restored. If you set a variable (such as with `setq') while it is local, this replaces the local value; it does not alter the global value, or previous local values, that are shadowed. To model this behavior, we speak of a "local binding" of the variable as well as a local value. The local binding is a conceptual place that holds a local value. Entering a function, or a special form such as `let', creates the local binding; exiting the function or the `let' removes the local binding. While the local binding lasts, the variable's value is stored within it. Using `setq' or `set' while there is a local binding stores a different value into the local binding; it does not create a new binding. We also speak of the "global binding", which is where (conceptually) the global value is kept. A variable can have more than one local binding at a time (for example, if there are nested `let' forms that bind it). In such a case, the most recently created local binding that still exists is the "current binding" of the variable. (This rule is called "dynamic scoping"; see *note Variable Scoping::.) If there are no local bindings, the variable's global binding is its current binding. We sometimes call the current binding the "most-local existing binding", for emphasis. Ordinary evaluation of a symbol always returns the value of its current binding. The special forms `let' and `let*' exist to create local bindings. -- Special Form: let (bindings...) forms... This special form binds variables according to BINDINGS and then evaluates all of the FORMS in textual order. The `let'-form returns the value of the last form in FORMS. Each of the BINDINGS is either (i) a symbol, in which case that symbol is bound to `nil'; or (ii) a list of the form `(SYMBOL VALUE-FORM)', in which case SYMBOL is bound to the result of evaluating VALUE-FORM. If VALUE-FORM is omitted, `nil' is used. All of the VALUE-FORMs in BINDINGS are evaluated in the order they appear and _before_ binding any of the symbols to them. Here is an example of this: `z' is bound to the old value of `y', which is 2, not the new value of `y', which is 1. (setq y 2) => 2 (let ((y 1) (z y)) (list y z)) => (1 2) -- Special Form: let* (bindings...) forms... This special form is like `let', but it binds each variable right after computing its local value, before computing the local value for the next variable. Therefore, an expression in BINDINGS can reasonably refer to the preceding symbols bound in this `let*' form. Compare the following example with the example above for `let'. (setq y 2) => 2 (let* ((y 1) (z y)) ; Use the just-established value of `y'. (list y z)) => (1 1) Here is a complete list of the other facilities that create local bindings: * Function calls (*note Functions::). * Macro calls (*note Macros::). * `condition-case' (*note Errors::). Variables can also have buffer-local bindings (*note Buffer-Local Variables::); a few variables have terminal-local bindings (*note Multiple Terminals::). These kinds of bindings work somewhat like ordinary local bindings, but they are localized depending on "where" you are in Emacs, rather than localized in time. -- User Option: max-specpdl-size This variable defines the limit on the total number of local variable bindings and `unwind-protect' cleanups (see *note Cleaning Up from Nonlocal Exits: Cleanups.) that are allowed before Emacs signals an error (with data `"Variable binding depth exceeds max-specpdl-size"'). This limit, with the associated error when it is exceeded, is one way that Lisp avoids infinite recursion on an ill-defined function. `max-lisp-eval-depth' provides another limit on depth of nesting. *Note Eval: Definition of max-lisp-eval-depth. The default value is 1000. Entry to the Lisp debugger increases the value, if there is little room left, to make sure the debugger itself has room to execute.  File: elisp, Node: Void Variables, Next: Defining Variables, Prev: Local Variables, Up: Variables 11.4 When a Variable is "Void" ============================== If you have never given a symbol any value as a global variable, we say that that symbol's global value is "void". In other words, the symbol's value cell does not have any Lisp object in it. If you try to evaluate the symbol, you get a `void-variable' error rather than a value. Note that a value of `nil' is not the same as void. The symbol `nil' is a Lisp object and can be the value of a variable just as any other object can be; but it is _a value_. A void variable does not have any value. After you have given a variable a value, you can make it void once more using `makunbound'. -- Function: makunbound symbol This function makes the current variable binding of SYMBOL void. Subsequent attempts to use this symbol's value as a variable will signal the error `void-variable', unless and until you set it again. `makunbound' returns SYMBOL. (makunbound 'x) ; Make the global value of `x' void. => x x error--> Symbol's value as variable is void: x If SYMBOL is locally bound, `makunbound' affects the most local existing binding. This is the only way a symbol can have a void local binding, since all the constructs that create local bindings create them with values. In this case, the voidness lasts at most as long as the binding does; when the binding is removed due to exit from the construct that made it, the previous local or global binding is reexposed as usual, and the variable is no longer void unless the newly reexposed binding was void all along. (setq x 1) ; Put a value in the global binding. => 1 (let ((x 2)) ; Locally bind it. (makunbound 'x) ; Void the local binding. x) error--> Symbol's value as variable is void: x x ; The global binding is unchanged. => 1 (let ((x 2)) ; Locally bind it. (let ((x 3)) ; And again. (makunbound 'x) ; Void the innermost-local binding. x)) ; And refer: it's void. error--> Symbol's value as variable is void: x (let ((x 2)) (let ((x 3)) (makunbound 'x)) ; Void inner binding, then remove it. x) ; Now outer `let' binding is visible. => 2 A variable that has been made void with `makunbound' is indistinguishable from one that has never received a value and has always been void. You can use the function `boundp' to test whether a variable is currently void. -- Function: boundp variable `boundp' returns `t' if VARIABLE (a symbol) is not void; more precisely, if its current binding is not void. It returns `nil' otherwise. (boundp 'abracadabra) ; Starts out void. => nil (let ((abracadabra 5)) ; Locally bind it. (boundp 'abracadabra)) => t (boundp 'abracadabra) ; Still globally void. => nil (setq abracadabra 5) ; Make it globally nonvoid. => 5 (boundp 'abracadabra) => t  File: elisp, Node: Defining Variables, Next: Tips for Defining, Prev: Void Variables, Up: Variables 11.5 Defining Global Variables ============================== You may announce your intention to use a symbol as a global variable with a "variable definition": a special form, either `defconst' or `defvar'. In Emacs Lisp, definitions serve three purposes. First, they inform people who read the code that certain symbols are _intended_ to be used a certain way (as variables). Second, they inform the Lisp system of these things, supplying a value and documentation. Third, they provide information to utilities such as `etags' and `make-docfile', which create data bases of the functions and variables in a program. The difference between `defconst' and `defvar' is primarily a matter of intent, serving to inform human readers of whether the value should ever change. Emacs Lisp does not restrict the ways in which a variable can be used based on `defconst' or `defvar' declarations. However, it does make a difference for initialization: `defconst' unconditionally initializes the variable, while `defvar' initializes it only if it is void. -- Special Form: defvar symbol [value [doc-string]] This special form defines SYMBOL as a variable and can also initialize and document it. The definition informs a person reading your code that SYMBOL is used as a variable that might be set or changed. Note that SYMBOL is not evaluated; the symbol to be defined must appear explicitly in the `defvar'. If SYMBOL is void and VALUE is specified, `defvar' evaluates it and sets SYMBOL to the result. But if SYMBOL already has a value (i.e., it is not void), VALUE is not even evaluated, and SYMBOL's value remains unchanged. If VALUE is omitted, the value of SYMBOL is not changed in any case. If SYMBOL has a buffer-local binding in the current buffer, `defvar' operates on the default value, which is buffer-independent, not the current (buffer-local) binding. It sets the default value if the default value is void. *Note Buffer-Local Variables::. When you evaluate a top-level `defvar' form with `C-M-x' in Emacs Lisp mode (`eval-defun'), a special feature of `eval-defun' arranges to set the variable unconditionally, without testing whether its value is void. If the DOC-STRING argument appears, it specifies the documentation for the variable. (This opportunity to specify documentation is one of the main benefits of defining the variable.) The documentation is stored in the symbol's `variable-documentation' property. The Emacs help functions (*note Documentation::) look for this property. If the documentation string begins with the character `*', Emacs allows users to set it interactively using the `set-variable' command. However, you should nearly always use `defcustom' instead of `defvar' to define such variables, so that users can use `M-x customize' and related commands to set them. In that case, it is not necessary to begin the documentation string with `*'. *Note Customization::. Here are some examples. This form defines `foo' but does not initialize it: (defvar foo) => foo This example initializes the value of `bar' to `23', and gives it a documentation string: (defvar bar 23 "The normal weight of a bar.") => bar The following form changes the documentation string for `bar', making it a user option, but does not change the value, since `bar' already has a value. (The addition `(1+ nil)' would get an error if it were evaluated, but since it is not evaluated, there is no error.) (defvar bar (1+ nil) "*The normal weight of a bar.") => bar bar => 23 Here is an equivalent expression for the `defvar' special form: (defvar SYMBOL VALUE DOC-STRING) == (progn (if (not (boundp 'SYMBOL)) (setq SYMBOL VALUE)) (if 'DOC-STRING (put 'SYMBOL 'variable-documentation 'DOC-STRING)) 'SYMBOL) The `defvar' form returns SYMBOL, but it is normally used at top level in a file where its value does not matter. -- Special Form: defconst symbol value [doc-string] This special form defines SYMBOL as a value and initializes it. It informs a person reading your code that SYMBOL has a standard global value, established here, that should not be changed by the user or by other programs. Note that SYMBOL is not evaluated; the symbol to be defined must appear explicitly in the `defconst'. `defconst' always evaluates VALUE, and sets the value of SYMBOL to the result. If SYMBOL does have a buffer-local binding in the current buffer, `defconst' sets the default value, not the buffer-local value. (But you should not be making buffer-local bindings for a symbol that is defined with `defconst'.) Here, `pi' is a constant that presumably ought not to be changed by anyone (attempts by the Indiana State Legislature notwithstanding). As the second form illustrates, however, this is only advisory. (defconst pi 3.1415 "Pi to five places.") => pi (setq pi 3) => pi pi => 3 -- Function: user-variable-p variable This function returns `t' if VARIABLE is a user option--a variable intended to be set by the user for customization--and `nil' otherwise. (Variables other than user options exist for the internal purposes of Lisp programs, and users need not know about them.) User option variables are distinguished from other variables either though being declared using `defcustom'(1) or by the first character of their `variable-documentation' property. If the property exists and is a string, and its first character is `*', then the variable is a user option. Aliases of user options are also user options. If a user option variable has a `variable-interactive' property, the `set-variable' command uses that value to control reading the new value for the variable. The property's value is used as if it were specified in `interactive' (*note Using Interactive::). However, this feature is largely obsoleted by `defcustom' (*note Customization::). *Warning:* If the `defconst' and `defvar' special forms are used while the variable has a local binding (made with `let', or a function argument), they set the local-binding's value; the top-level binding is not changed. This is not what you usually want. To prevent it, use these special forms at top level in a file, where normally no local binding is in effect, and make sure to load the file before making a local binding for the variable. ---------- Footnotes ---------- (1) They may also be declared equivalently in `cus-start.el'.  File: elisp, Node: Tips for Defining, Next: Accessing Variables, Prev: Defining Variables, Up: Variables 11.6 Tips for Defining Variables Robustly ========================================= When you define a variable whose value is a function, or a list of functions, use a name that ends in `-function' or `-functions', respectively. There are several other variable name conventions; here is a complete list: `...-hook' The variable is a normal hook (*note Hooks::). `...-function' The value is a function. `...-functions' The value is a list of functions. `...-form' The value is a form (an expression). `...-forms' The value is a list of forms (expressions). `...-predicate' The value is a predicate--a function of one argument that returns non-`nil' for "good" arguments and `nil' for "bad" arguments. `...-flag' The value is significant only as to whether it is `nil' or not. Since such variables often end up acquiring more values over time, this convention is not strongly recommended. `...-program' The value is a program name. `...-command' The value is a whole shell command. `...-switches' The value specifies options for a command. When you define a variable, always consider whether you should mark it as "safe" or "risky"; see *note File Local Variables::. When defining and initializing a variable that holds a complicated value (such as a keymap with bindings in it), it's best to put the entire computation of the value into the `defvar', like this: (defvar my-mode-map (let ((map (make-sparse-keymap))) (define-key map "\C-c\C-a" 'my-command) ... map) DOCSTRING) This method has several benefits. First, if the user quits while loading the file, the variable is either still uninitialized or initialized properly, never in-between. If it is still uninitialized, reloading the file will initialize it properly. Second, reloading the file once the variable is initialized will not alter it; that is important if the user has run hooks to alter part of the contents (such as, to rebind keys). Third, evaluating the `defvar' form with `C-M-x' _will_ reinitialize the map completely. Putting so much code in the `defvar' form has one disadvantage: it puts the documentation string far away from the line which names the variable. Here's a safe way to avoid that: (defvar my-mode-map nil DOCSTRING) (unless my-mode-map (let ((map (make-sparse-keymap))) (define-key map "\C-c\C-a" 'my-command) ... (setq my-mode-map map))) This has all the same advantages as putting the initialization inside the `defvar', except that you must type `C-M-x' twice, once on each form, if you do want to reinitialize the variable. But be careful not to write the code like this: (defvar my-mode-map nil DOCSTRING) (unless my-mode-map (setq my-mode-map (make-sparse-keymap)) (define-key my-mode-map "\C-c\C-a" 'my-command) ...) This code sets the variable, then alters it, but it does so in more than one step. If the user quits just after the `setq', that leaves the variable neither correctly initialized nor void nor `nil'. Once that happens, reloading the file will not initialize the variable; it will remain incomplete.  File: elisp, Node: Accessing Variables, Next: Setting Variables, Prev: Tips for Defining, Up: Variables 11.7 Accessing Variable Values ============================== The usual way to reference a variable is to write the symbol which names it (*note Symbol Forms::). This requires you to specify the variable name when you write the program. Usually that is exactly what you want to do. Occasionally you need to choose at run time which variable to reference; then you can use `symbol-value'. -- Function: symbol-value symbol This function returns the value of SYMBOL. This is the value in the innermost local binding of the symbol, or its global value if it has no local bindings. (setq abracadabra 5) => 5 (setq foo 9) => 9 ;; Here the symbol `abracadabra' ;; is the symbol whose value is examined. (let ((abracadabra 'foo)) (symbol-value 'abracadabra)) => foo ;; Here, the value of `abracadabra', ;; which is `foo', ;; is the symbol whose value is examined. (let ((abracadabra 'foo)) (symbol-value abracadabra)) => 9 (symbol-value 'abracadabra) => 5 A `void-variable' error is signaled if the current binding of SYMBOL is void.  File: elisp, Node: Setting Variables, Next: Variable Scoping, Prev: Accessing Variables, Up: Variables 11.8 How to Alter a Variable Value ================================== The usual way to change the value of a variable is with the special form `setq'. When you need to compute the choice of variable at run time, use the function `set'. -- Special Form: setq [symbol form]... This special form is the most common method of changing a variable's value. Each SYMBOL is given a new value, which is the result of evaluating the corresponding FORM. The most-local existing binding of the symbol is changed. `setq' does not evaluate SYMBOL; it sets the symbol that you write. We say that this argument is "automatically quoted". The `q' in `setq' stands for "quoted." The value of the `setq' form is the value of the last FORM. (setq x (1+ 2)) => 3 x ; `x' now has a global value. => 3 (let ((x 5)) (setq x 6) ; The local binding of `x' is set. x) => 6 x ; The global value is unchanged. => 3 Note that the first FORM is evaluated, then the first SYMBOL is set, then the second FORM is evaluated, then the second SYMBOL is set, and so on: (setq x 10 ; Notice that `x' is set before y (1+ x)) ; the value of `y' is computed. => 11 -- Function: set symbol value This function sets SYMBOL's value to VALUE, then returns VALUE. Since `set' is a function, the expression written for SYMBOL is evaluated to obtain the symbol to set. The most-local existing binding of the variable is the binding that is set; shadowed bindings are not affected. (set one 1) error--> Symbol's value as variable is void: one (set 'one 1) => 1 (set 'two 'one) => one (set two 2) ; `two' evaluates to symbol `one'. => 2 one ; So it is `one' that was set. => 2 (let ((one 1)) ; This binding of `one' is set, (set 'one 3) ; not the global value. one) => 3 one => 2 If SYMBOL is not actually a symbol, a `wrong-type-argument' error is signaled. (set '(x y) 'z) error--> Wrong type argument: symbolp, (x y) Logically speaking, `set' is a more fundamental primitive than `setq'. Any use of `setq' can be trivially rewritten to use `set'; `setq' could even be defined as a macro, given the availability of `set'. However, `set' itself is rarely used; beginners hardly need to know about it. It is useful only for choosing at run time which variable to set. For example, the command `set-variable', which reads a variable name from the user and then sets the variable, needs to use `set'. Common Lisp note: In Common Lisp, `set' always changes the symbol's "special" or dynamic value, ignoring any lexical bindings. In Emacs Lisp, all variables and all bindings are dynamic, so `set' always affects the most local existing binding.  File: elisp, Node: Variable Scoping, Next: Buffer-Local Variables, Prev: Setting Variables, Up: Variables 11.9 Scoping Rules for Variable Bindings ======================================== A given symbol `foo' can have several local variable bindings, established at different places in the Lisp program, as well as a global binding. The most recently established binding takes precedence over the others. Local bindings in Emacs Lisp have "indefinite scope" and "dynamic extent". "Scope" refers to _where_ textually in the source code the binding can be accessed. "Indefinite scope" means that any part of the program can potentially access the variable binding. "Extent" refers to _when_, as the program is executing, the binding exists. "Dynamic extent" means that the binding lasts as long as the activation of the construct that established it. The combination of dynamic extent and indefinite scope is called "dynamic scoping". By contrast, most programming languages use "lexical scoping", in which references to a local variable must be located textually within the function or block that binds the variable. Common Lisp note: Variables declared "special" in Common Lisp are dynamically scoped, like all variables in Emacs Lisp. * Menu: * Scope:: Scope means where in the program a value is visible. Comparison with other languages. * Extent:: Extent means how long in time a value exists. * Impl of Scope:: Two ways to implement dynamic scoping. * Using Scoping:: How to use dynamic scoping carefully and avoid problems.  File: elisp, Node: Scope, Next: Extent, Up: Variable Scoping 11.9.1 Scope ------------ Emacs Lisp uses "indefinite scope" for local variable bindings. This means that any function anywhere in the program text might access a given binding of a variable. Consider the following function definitions: (defun binder (x) ; `x' is bound in `binder'. (foo 5)) ; `foo' is some other function. (defun user () ; `x' is used "free" in `user'. (list x)) In a lexically scoped language, the binding of `x' in `binder' would never be accessible in `user', because `user' is not textually contained within the function `binder'. However, in dynamically-scoped Emacs Lisp, `user' may or may not refer to the binding of `x' established in `binder', depending on the circumstances: * If we call `user' directly without calling `binder' at all, then whatever binding of `x' is found, it cannot come from `binder'. * If we define `foo' as follows and then call `binder', then the binding made in `binder' will be seen in `user': (defun foo (lose) (user)) * However, if we define `foo' as follows and then call `binder', then the binding made in `binder' _will not_ be seen in `user': (defun foo (x) (user)) Here, when `foo' is called by `binder', it binds `x'. (The binding in `foo' is said to "shadow" the one made in `binder'.) Therefore, `user' will access the `x' bound by `foo' instead of the one bound by `binder'. Emacs Lisp uses dynamic scoping because simple implementations of lexical scoping are slow. In addition, every Lisp system needs to offer dynamic scoping at least as an option; if lexical scoping is the norm, there must be a way to specify dynamic scoping instead for a particular variable. It might not be a bad thing for Emacs to offer both, but implementing it with dynamic scoping only was much easier.  File: elisp, Node: Extent, Next: Impl of Scope, Prev: Scope, Up: Variable Scoping 11.9.2 Extent ------------- "Extent" refers to the time during program execution that a variable name is valid. In Emacs Lisp, a variable is valid only while the form that bound it is executing. This is called "dynamic extent". "Local" or "automatic" variables in most languages, including C and Pascal, have dynamic extent. One alternative to dynamic extent is "indefinite extent". This means that a variable binding can live on past the exit from the form that made the binding. Common Lisp and Scheme, for example, support this, but Emacs Lisp does not. To illustrate this, the function below, `make-add', returns a function that purports to add N to its own argument M. This would work in Common Lisp, but it does not do the job in Emacs Lisp, because after the call to `make-add' exits, the variable `n' is no longer bound to the actual argument 2. (defun make-add (n) (function (lambda (m) (+ n m)))) ; Return a function. => make-add (fset 'add2 (make-add 2)) ; Define function `add2' ; with `(make-add 2)'. => (lambda (m) (+ n m)) (add2 4) ; Try to add 2 to 4. error--> Symbol's value as variable is void: n Some Lisp dialects have "closures," objects that are like functions but record additional variable bindings. Emacs Lisp does not have closures.  File: elisp, Node: Impl of Scope, Next: Using Scoping, Prev: Extent, Up: Variable Scoping 11.9.3 Implementation of Dynamic Scoping ---------------------------------------- A simple sample implementation (which is not how Emacs Lisp actually works) may help you understand dynamic binding. This technique is called "deep binding" and was used in early Lisp systems. Suppose there is a stack of bindings, which are variable-value pairs. At entry to a function or to a `let' form, we can push bindings onto the stack for the arguments or local variables created there. We can pop those bindings from the stack at exit from the binding construct. We can find the value of a variable by searching the stack from top to bottom for a binding for that variable; the value from that binding is the value of the variable. To set the variable, we search for the current binding, then store the new value into that binding. As you can see, a function's bindings remain in effect as long as it continues execution, even during its calls to other functions. That is why we say the extent of the binding is dynamic. And any other function can refer to the bindings, if it uses the same variables while the bindings are in effect. That is why we say the scope is indefinite. The actual implementation of variable scoping in GNU Emacs Lisp uses a technique called "shallow binding". Each variable has a standard place in which its current value is always found--the value cell of the symbol. In shallow binding, setting the variable works by storing a value in the value cell. Creating a new binding works by pushing the old value (belonging to a previous binding) onto a stack, and storing the new local value in the value cell. Eliminating a binding works by popping the old value off the stack, into the value cell. We use shallow binding because it has the same results as deep binding, but runs faster, since there is never a need to search for a binding.  File: elisp, Node: Using Scoping, Prev: Impl of Scope, Up: Variable Scoping 11.9.4 Proper Use of Dynamic Scoping ------------------------------------ Binding a variable in one function and using it in another is a powerful technique, but if used without restraint, it can make programs hard to understand. There are two clean ways to use this technique: * Use or bind the variable only in a few related functions, written close together in one file. Such a variable is used for communication within one program. You should write comments to inform other programmers that they can see all uses of the variable before them, and to advise them not to add uses elsewhere. * Give the variable a well-defined, documented meaning, and make all appropriate functions refer to it (but not bind it or set it) wherever that meaning is relevant. For example, the variable `case-fold-search' is defined as "non-`nil' means ignore case when searching"; various search and replace functions refer to it directly or through their subroutines, but do not bind or set it. Then you can bind the variable in other programs, knowing reliably what the effect will be. In either case, you should define the variable with `defvar'. This helps other people understand your program by telling them to look for inter-function usage. It also avoids a warning from the byte compiler. Choose the variable's name to avoid name conflicts--don't use short names like `x'.  File: elisp, Node: Buffer-Local Variables, Next: File Local Variables, Prev: Variable Scoping, Up: Variables 11.10 Buffer-Local Variables ============================ Global and local variable bindings are found in most programming languages in one form or another. Emacs, however, also supports additional, unusual kinds of variable binding, such as "buffer-local" bindings, which apply only in one buffer. Having different values for a variable in different buffers is an important customization method. (Variables can also have bindings that are local to each terminal, or to each frame. *Note Multiple Terminals::, and *Note Frame-Local Variables::.) * Menu: * Intro to Buffer-Local:: Introduction and concepts. * Creating Buffer-Local:: Creating and destroying buffer-local bindings. * Default Value:: The default value is seen in buffers that don't have their own buffer-local values.  File: elisp, Node: Intro to Buffer-Local, Next: Creating Buffer-Local, Up: Buffer-Local Variables 11.10.1 Introduction to Buffer-Local Variables ---------------------------------------------- A buffer-local variable has a buffer-local binding associated with a particular buffer. The binding is in effect when that buffer is current; otherwise, it is not in effect. If you set the variable while a buffer-local binding is in effect, the new value goes in that binding, so its other bindings are unchanged. This means that the change is visible only in the buffer where you made it. The variable's ordinary binding, which is not associated with any specific buffer, is called the "default binding". In most cases, this is the global binding. A variable can have buffer-local bindings in some buffers but not in other buffers. The default binding is shared by all the buffers that don't have their own bindings for the variable. (This includes all newly-created buffers.) If you set the variable in a buffer that does not have a buffer-local binding for it, this sets the default binding, so the new value is visible in all the buffers that see the default binding. The most common use of buffer-local bindings is for major modes to change variables that control the behavior of commands. For example, C mode and Lisp mode both set the variable `paragraph-start' to specify that only blank lines separate paragraphs. They do this by making the variable buffer-local in the buffer that is being put into C mode or Lisp mode, and then setting it to the new value for that mode. *Note Major Modes::. The usual way to make a buffer-local binding is with `make-local-variable', which is what major mode commands typically use. This affects just the current buffer; all other buffers (including those yet to be created) will continue to share the default value unless they are explicitly given their own buffer-local bindings. A more powerful operation is to mark the variable as "automatically buffer-local" by calling `make-variable-buffer-local'. You can think of this as making the variable local in all buffers, even those yet to be created. More precisely, the effect is that setting the variable automatically makes the variable local to the current buffer if it is not already so. All buffers start out by sharing the default value of the variable as usual, but setting the variable creates a buffer-local binding for the current buffer. The new value is stored in the buffer-local binding, leaving the default binding untouched. This means that the default value cannot be changed with `setq' in any buffer; the only way to change it is with `setq-default'. *Warning:* When a variable has buffer-local bindings in one or more buffers, `let' rebinds the binding that's currently in effect. For instance, if the current buffer has a buffer-local value, `let' temporarily rebinds that. If no buffer-local bindings are in effect, `let' rebinds the default value. If inside the `let' you then change to a different current buffer in which a different binding is in effect, you won't see the `let' binding any more. And if you exit the `let' while still in the other buffer, you won't see the unbinding occur (though it will occur properly). Here is an example to illustrate: (setq foo 'g) (set-buffer "a") (make-local-variable 'foo) (setq foo 'a) (let ((foo 'temp)) ;; foo => 'temp ; let binding in buffer `a' (set-buffer "b") ;; foo => 'g ; the global value since foo is not local in `b' BODY...) foo => 'g ; exiting restored the local value in buffer `a', ; but we don't see that in buffer `b' (set-buffer "a") ; verify the local value was restored foo => 'a Note that references to `foo' in BODY access the buffer-local binding of buffer `b'. When a file specifies local variable values, these become buffer-local values when you visit the file. *Note File Variables: (emacs)File Variables. A buffer-local variable cannot be made frame-local (*note Frame-Local Variables::) or terminal-local (*note Multiple Terminals::).  File: elisp, Node: Creating Buffer-Local, Next: Default Value, Prev: Intro to Buffer-Local, Up: Buffer-Local Variables 11.10.2 Creating and Deleting Buffer-Local Bindings --------------------------------------------------- -- Command: make-local-variable variable This function creates a buffer-local binding in the current buffer for VARIABLE (a symbol). Other buffers are not affected. The value returned is VARIABLE. The buffer-local value of VARIABLE starts out as the same value VARIABLE previously had. If VARIABLE was void, it remains void. ;; In buffer `b1': (setq foo 5) ; Affects all buffers. => 5 (make-local-variable 'foo) ; Now it is local in `b1'. => foo foo ; That did not change => 5 ; the value. (setq foo 6) ; Change the value => 6 ; in `b1'. foo => 6 ;; In buffer `b2', the value hasn't changed. (with-current-buffer "b2" foo) => 5 Making a variable buffer-local within a `let'-binding for that variable does not work reliably, unless the buffer in which you do this is not current either on entry to or exit from the `let'. This is because `let' does not distinguish between different kinds of bindings; it knows only which variable the binding was made for. If the variable is terminal-local (*note Multiple Terminals::), or frame-local (*note Frame-Local Variables::), this function signals an error. Such variables cannot have buffer-local bindings as well. *Warning:* do not use `make-local-variable' for a hook variable. The hook variables are automatically made buffer-local as needed if you use the LOCAL argument to `add-hook' or `remove-hook'. -- Command: make-variable-buffer-local variable This function marks VARIABLE (a symbol) automatically buffer-local, so that any subsequent attempt to set it will make it local to the current buffer at the time. A peculiar wrinkle of this feature is that binding the variable (with `let' or other binding constructs) does not create a buffer-local binding for it. Only setting the variable (with `set' or `setq'), while the variable does not have a `let'-style binding that was made in the current buffer, does so. If VARIABLE does not have a default value, then calling this command will give it a default value of `nil'. If VARIABLE already has a default value, that value remains unchanged. Subsequently calling `makunbound' on VARIABLE will result in a void buffer-local value and leave the default value unaffected. The value returned is VARIABLE. *Warning:* Don't assume that you should use `make-variable-buffer-local' for user-option variables, simply because users _might_ want to customize them differently in different buffers. Users can make any variable local, when they wish to. It is better to leave the choice to them. The time to use `make-variable-buffer-local' is when it is crucial that no two buffers ever share the same binding. For example, when a variable is used for internal purposes in a Lisp program which depends on having separate values in separate buffers, then using `make-variable-buffer-local' can be the best solution. -- Function: local-variable-p variable &optional buffer This returns `t' if VARIABLE is buffer-local in buffer BUFFER (which defaults to the current buffer); otherwise, `nil'. -- Function: local-variable-if-set-p variable &optional buffer This returns `t' if VARIABLE will become buffer-local in buffer BUFFER (which defaults to the current buffer) if it is set there. -- Function: buffer-local-value variable buffer This function returns the buffer-local binding of VARIABLE (a symbol) in buffer BUFFER. If VARIABLE does not have a buffer-local binding in buffer BUFFER, it returns the default value (*note Default Value::) of VARIABLE instead. -- Function: buffer-local-variables &optional buffer This function returns a list describing the buffer-local variables in buffer BUFFER. (If BUFFER is omitted, the current buffer is used.) It returns an association list (*note Association Lists::) in which each element contains one buffer-local variable and its value. However, when a variable's buffer-local binding in BUFFER is void, then the variable appears directly in the resulting list. (make-local-variable 'foobar) (makunbound 'foobar) (make-local-variable 'bind-me) (setq bind-me 69) (setq lcl (buffer-local-variables)) ;; First, built-in variables local in all buffers: => ((mark-active . nil) (buffer-undo-list . nil) (mode-name . "Fundamental") ... ;; Next, non-built-in buffer-local variables. ;; This one is buffer-local and void: foobar ;; This one is buffer-local and nonvoid: (bind-me . 69)) Note that storing new values into the CDRs of cons cells in this list does _not_ change the buffer-local values of the variables. -- Command: kill-local-variable variable This function deletes the buffer-local binding (if any) for VARIABLE (a symbol) in the current buffer. As a result, the default binding of VARIABLE becomes visible in this buffer. This typically results in a change in the value of VARIABLE, since the default value is usually different from the buffer-local value just eliminated. If you kill the buffer-local binding of a variable that automatically becomes buffer-local when set, this makes the default value visible in the current buffer. However, if you set the variable again, that will once again create a buffer-local binding for it. `kill-local-variable' returns VARIABLE. This function is a command because it is sometimes useful to kill one buffer-local variable interactively, just as it is useful to create buffer-local variables interactively. -- Function: kill-all-local-variables This function eliminates all the buffer-local variable bindings of the current buffer except for variables marked as "permanent" and local hook functions that have a non-`nil' `permanent-local-hook' property (*note Setting Hooks::). As a result, the buffer will see the default values of most variables. This function also resets certain other information pertaining to the buffer: it sets the local keymap to `nil', the syntax table to the value of `(standard-syntax-table)', the case table to `(standard-case-table)', and the abbrev table to the value of `fundamental-mode-abbrev-table'. The very first thing this function does is run the normal hook `change-major-mode-hook' (see below). Every major mode command begins by calling this function, which has the effect of switching to Fundamental mode and erasing most of the effects of the previous major mode. To ensure that this does its job, the variables that major modes set should not be marked permanent. `kill-all-local-variables' returns `nil'. -- Variable: change-major-mode-hook The function `kill-all-local-variables' runs this normal hook before it does anything else. This gives major modes a way to arrange for something special to be done if the user switches to a different major mode. It is also useful for buffer-specific minor modes that should be forgotten if the user changes the major mode. For best results, make this variable buffer-local, so that it will disappear after doing its job and will not interfere with the subsequent major mode. *Note Hooks::. A buffer-local variable is "permanent" if the variable name (a symbol) has a `permanent-local' property that is non-`nil'. Permanent locals are appropriate for data pertaining to where the file came from or how to save it, rather than with how to edit the contents.  File: elisp, Node: Default Value, Prev: Creating Buffer-Local, Up: Buffer-Local Variables 11.10.3 The Default Value of a Buffer-Local Variable ---------------------------------------------------- The global value of a variable with buffer-local bindings is also called the "default" value, because it is the value that is in effect whenever neither the current buffer nor the selected frame has its own binding for the variable. The functions `default-value' and `setq-default' access and change a variable's default value regardless of whether the current buffer has a buffer-local binding. For example, you could use `setq-default' to change the default setting of `paragraph-start' for most buffers; and this would work even when you are in a C or Lisp mode buffer that has a buffer-local value for this variable. The special forms `defvar' and `defconst' also set the default value (if they set the variable at all), rather than any buffer-local value. -- Function: default-value symbol This function returns SYMBOL's default value. This is the value that is seen in buffers and frames that do not have their own values for this variable. If SYMBOL is not buffer-local, this is equivalent to `symbol-value' (*note Accessing Variables::). -- Function: default-boundp symbol The function `default-boundp' tells you whether SYMBOL's default value is nonvoid. If `(default-boundp 'foo)' returns `nil', then `(default-value 'foo)' would get an error. `default-boundp' is to `default-value' as `boundp' is to `symbol-value'. -- Special Form: setq-default [symbol form]... This special form gives each SYMBOL a new default value, which is the result of evaluating the corresponding FORM. It does not evaluate SYMBOL, but does evaluate FORM. The value of the `setq-default' form is the value of the last FORM. If a SYMBOL is not buffer-local for the current buffer, and is not marked automatically buffer-local, `setq-default' has the same effect as `setq'. If SYMBOL is buffer-local for the current buffer, then this changes the value that other buffers will see (as long as they don't have a buffer-local value), but not the value that the current buffer sees. ;; In buffer `foo': (make-local-variable 'buffer-local) => buffer-local (setq buffer-local 'value-in-foo) => value-in-foo (setq-default buffer-local 'new-default) => new-default buffer-local => value-in-foo (default-value 'buffer-local) => new-default ;; In (the new) buffer `bar': buffer-local => new-default (default-value 'buffer-local) => new-default (setq buffer-local 'another-default) => another-default (default-value 'buffer-local) => another-default ;; Back in buffer `foo': buffer-local => value-in-foo (default-value 'buffer-local) => another-default -- Function: set-default symbol value This function is like `setq-default', except that SYMBOL is an ordinary evaluated argument. (set-default (car '(a b c)) 23) => 23 (default-value 'a) => 23  File: elisp, Node: File Local Variables, Next: Directory Local Variables, Prev: Buffer-Local Variables, Up: Variables 11.11 File Local Variables ========================== A file can specify local variable values; Emacs uses these to create buffer-local bindings for those variables in the buffer visiting that file. *Note Local Variables in Files: (emacs)File variables, for basic information about file-local variables. This section describes the functions and variables that affect how file-local variables are processed. If a file-local variable could specify an arbitrary function or Lisp expression that would be called later, visiting a file could take over your Emacs. Emacs protects against this by automatically setting only those file-local variables whose specified values are known to be safe. Other file-local variables are set only if the user agrees. For additional safety, `read-circle' is temporarily bound to `nil' when Emacs reads file-local variables (*note Input Functions::). This prevents the Lisp reader from recognizing circular and shared Lisp structures (*note Circular Objects::). -- User Option: enable-local-variables This variable controls whether to process file-local variables. The possible values are: `t' (the default) Set the safe variables, and query (once) about any unsafe variables. `:safe' Set only the safe variables and do not query. `:all' Set all the variables and do not query. `nil' Don't set any variables. anything else Query (once) about all the variables. -- Function: hack-local-variables &optional mode-only This function parses, and binds or evaluates as appropriate, any local variables specified by the contents of the current buffer. The variable `enable-local-variables' has its effect here. However, this function does not look for the `mode:' local variable in the `-*-' line. `set-auto-mode' does that, also taking `enable-local-variables' into account (*note Auto Major Mode::). This function works by walking the alist stored in `file-local-variables-alist' and applying each local variable in turn. It calls `before-hack-local-variables-hook' and `hack-local-variables-hook' before and after applying the variables, respectively. If the optional argument MODE-ONLY is non-`nil', then all this function does is return `t' if the `-*-' line or the local variables list specifies a mode and `nil' otherwise. It does not set the mode nor any other file-local variable. -- Variable: file-local-variables-alist This buffer-local variable holds the alist of file-local variable settings. Each element of the alist is of the form `(VAR . VALUE)', where VAR is a symbol of the local variable and VALUE is its value. When Emacs visits a file, it first collects all the file-local variables into this alist, and then the `hack-local-variables' function applies them one by one. -- Variable: before-hack-local-variables-hook Emacs calls this hook immediately before applying file-local variables stored in `file-local-variables-alist'. -- Variable: hack-local-variables-hook Emacs calls this hook immediately after it finishes applying file-local variables stored in `file-local-variables-alist'. You can specify safe values for a variable with a `safe-local-variable' property. The property has to be a function of one argument; any value is safe if the function returns non-`nil' given that value. Many commonly-encountered file variables have `safe-local-variable' properties; these include `fill-column', `fill-prefix', and `indent-tabs-mode'. For boolean-valued variables that are safe, use `booleanp' as the property value. Lambda expressions should be quoted so that `describe-variable' can display the predicate. -- User Option: safe-local-variable-values This variable provides another way to mark some variable values as safe. It is a list of cons cells `(VAR . VAL)', where VAR is a variable name and VAL is a value which is safe for that variable. When Emacs asks the user whether or not to obey a set of file-local variable specifications, the user can choose to mark them as safe. Doing so adds those variable/value pairs to `safe-local-variable-values', and saves it to the user's custom file. -- Function: safe-local-variable-p sym val This function returns non-`nil' if it is safe to give SYM the value VAL, based on the above criteria. Some variables are considered "risky". A variable whose name ends in any of `-command', `-frame-alist', `-function', `-functions', `-hook', `-hooks', `-form', `-forms', `-map', `-map-alist', `-mode-alist', `-program', or `-predicate' is considered risky. The variables `font-lock-keywords', `font-lock-keywords' followed by a digit, and `font-lock-syntactic-keywords' are also considered risky. Finally, any variable whose name has a non-`nil' `risky-local-variable' property is considered risky. -- Function: risky-local-variable-p sym This function returns non-`nil' if SYM is a risky variable, based on the above criteria. If a variable is risky, it will not be entered automatically into `safe-local-variable-values' as described above. Therefore, Emacs will always query before setting a risky variable, unless the user explicitly allows the setting by customizing `safe-local-variable-values' directly. -- Variable: ignored-local-variables This variable holds a list of variables that should not be given local values by files. Any value specified for one of these variables is completely ignored. The `Eval:' "variable" is also a potential loophole, so Emacs normally asks for confirmation before handling it. -- User Option: enable-local-eval This variable controls processing of `Eval:' in `-*-' lines or local variables lists in files being visited. A value of `t' means process them unconditionally; `nil' means ignore them; anything else means ask the user what to do for each file. The default value is `maybe'. -- User Option: safe-local-eval-forms This variable holds a list of expressions that are safe to evaluate when found in the `Eval:' "variable" in a file local variables list. If the expression is a function call and the function has a `safe-local-eval-function' property, the property value determines whether the expression is safe to evaluate. The property value can be a predicate to call to test the expression, a list of such predicates (it's safe if any predicate succeeds), or `t' (always safe provided the arguments are constant). Text properties are also potential loopholes, since their values could include functions to call. So Emacs discards all text properties from string values specified for file-local variables.  File: elisp, Node: Directory Local Variables, Next: Frame-Local Variables, Prev: File Local Variables, Up: Variables 11.12 Directory Local Variables =============================== A directory can specify local variable values common to all files in that directory; Emacs uses these to create buffer-local bindings for those variables in buffers visiting any file in that directory. This is useful when the files in the directory belong to some "project" and therefore share the same local variables. There are two different methods for specifying directory local variables: by putting them in a special file, or by defining a "project class" for that directory. -- Constant: dir-locals-file This constant is the name of the file where Emacs expects to find the directory-local variables. The name of the file is `.dir-locals.el'(1). A file by that name in a directory causes Emacs to apply its settings to any file in that directory or any of its subdirectories. If some of the subdirectories have their own `.dir-locals.el' files, Emacs uses the settings from the deepest file it finds starting from the file's directory and moving up the directory tree. The file specifies local variables as a specially formatted list; see *note Per-directory Local Variables: (emacs)Directory Variables, for more details. -- Function: hack-dir-local-variables This function reads the `.dir-locals.el' file and stores the directory-local variables in `file-local-variables-alist' that is local to the buffer visiting any file in the directory, without applying them. It also stores the directory-local settings in `dir-locals-class-alist', where it defines a special class for the directory in which `.dir-locals.el' file was found. This function works by calling `dir-locals-set-class-variables' and `dir-locals-set-directory-class', described below. -- Function: dir-locals-set-class-variables class variables This function defines a set of variable settings for the named CLASS, which is a symbol. You can later assign the class to one or more directories, and Emacs will apply those variable settings to all files in those directories. The list in VARIABLES can be of one of the two forms: `(MAJOR-MODE . ALIST)' or `(DIRECTORY . LIST)'. With the first form, if the file's buffer turns on a mode that is derived from MAJOR-MODE, then the all the variables in the associated ALIST are applied; ALIST should be of the form `(NAME . VALUE)'. A special value `nil' for MAJOR-MODE means the settings are applicable to any mode. With the second form of VARIABLES, if DIRECTORY is the initial substring of the file's directory, then LIST is applied recursively by following the above rules; LIST should be of one of the two forms accepted by this function in VARIABLES. -- Function: dir-locals-set-directory-class directory class This function assigns CLASS to all the files in `directory' and its subdirectories. Thereafter, all the variable settings specified for CLASS will be applied to any visited file in DIRECTORY and its children. CLASS must have been already defined by `dir-locals-set-class-variables' -- Variable: dir-locals-class-alist This alist holds the class symbols and the associated variable settings. It is updated by `dir-locals-set-class-variables'. -- Variable: dir-locals-directory-cache This alist holds directory names, their assigned class names, and modification times of the associated directory local variables file. It is updated by `dir-locals-set-directory-class'. ---------- Footnotes ---------- (1) The MS-DOS version of Emacs uses `_dir-locals.el' instead, due to limitations of the DOS filesystems.  File: elisp, Node: Frame-Local Variables, Next: Variable Aliases, Prev: Directory Local Variables, Up: Variables 11.13 Frame-Local Values for Variables ====================================== In addition to buffer-local variable bindings (*note Buffer-Local Variables::), Emacs supports "frame-local" bindings. A frame-local binding for a variable is in effect in a frame for which it was defined. In practice, frame-local variables have not proven very useful. Ordinary frame parameters are generally used instead (*note Frame Parameters::). The function `make-variable-frame-local', which was used to define frame-local variables, has been deprecated since Emacs 22.2. However, you can still define a frame-specific binding for a variable VAR in frame FRAME, by setting the VAR frame parameter for that frame: (modify-frame-parameters FRAME '((VAR . VALUE))) This causes the variable VAR to be bound to the specified VALUE in the named FRAME. To check the frame-specific values of such variables, use `frame-parameter'. *Note Parameter Access::. Note that you cannot have a frame-local binding for a variable that has a buffer-local binding.  File: elisp, Node: Variable Aliases, Next: Variables with Restricted Values, Prev: Frame-Local Variables, Up: Variables 11.14 Variable Aliases ====================== It is sometimes useful to make two variables synonyms, so that both variables always have the same value, and changing either one also changes the other. Whenever you change the name of a variable--either because you realize its old name was not well chosen, or because its meaning has partly changed--it can be useful to keep the old name as an _alias_ of the new one for compatibility. You can do this with `defvaralias'. -- Function: defvaralias new-alias base-variable &optional docstring This function defines the symbol NEW-ALIAS as a variable alias for symbol BASE-VARIABLE. This means that retrieving the value of NEW-ALIAS returns the value of BASE-VARIABLE, and changing the value of NEW-ALIAS changes the value of BASE-VARIABLE. The two aliased variable names always share the same value and the same bindings. If the DOCSTRING argument is non-`nil', it specifies the documentation for NEW-ALIAS; otherwise, the alias gets the same documentation as BASE-VARIABLE has, if any, unless BASE-VARIABLE is itself an alias, in which case NEW-ALIAS gets the documentation of the variable at the end of the chain of aliases. This function returns BASE-VARIABLE. Variable aliases are convenient for replacing an old name for a variable with a new name. `make-obsolete-variable' declares that the old name is obsolete and therefore that it may be removed at some stage in the future. -- Function: make-obsolete-variable obsolete-name current-name &optional when This function makes the byte compiler warn that the variable OBSOLETE-NAME is obsolete. If CURRENT-NAME is a symbol, it is the variable's new name; then the warning message says to use CURRENT-NAME instead of OBSOLETE-NAME. If CURRENT-NAME is a string, this is the message and there is no replacement variable. If provided, WHEN should be a string indicating when the variable was first made obsolete--for example, a date or a release number. You can make two variables synonyms and declare one obsolete at the same time using the macro `define-obsolete-variable-alias'. -- Macro: define-obsolete-variable-alias obsolete-name current-name &optional when docstring This macro marks the variable OBSOLETE-NAME as obsolete and also makes it an alias for the variable CURRENT-NAME. It is equivalent to the following: (defvaralias OBSOLETE-NAME CURRENT-NAME DOCSTRING) (make-obsolete-variable OBSOLETE-NAME CURRENT-NAME WHEN) -- Function: indirect-variable variable This function returns the variable at the end of the chain of aliases of VARIABLE. If VARIABLE is not a symbol, or if VARIABLE is not defined as an alias, the function returns VARIABLE. This function signals a `cyclic-variable-indirection' error if there is a loop in the chain of symbols. (defvaralias 'foo 'bar) (indirect-variable 'foo) => bar (indirect-variable 'bar) => bar (setq bar 2) bar => 2 foo => 2 (setq foo 0) bar => 0 foo => 0  File: elisp, Node: Variables with Restricted Values, Prev: Variable Aliases, Up: Variables 11.15 Variables with Restricted Values ====================================== Ordinary Lisp variables can be assigned any value that is a valid Lisp object. However, certain Lisp variables are not defined in Lisp, but in C. Most of these variables are defined in the C code using `DEFVAR_LISP'. Like variables defined in Lisp, these can take on any value. However, some variables are defined using `DEFVAR_INT' or `DEFVAR_BOOL'. *Note Writing Emacs Primitives: Defining Lisp variables in C, in particular the description of functions of the type `syms_of_FILENAME', for a brief discussion of the C implementation. Variables of type `DEFVAR_BOOL' can only take on the values `nil' or `t'. Attempting to assign them any other value will set them to `t': (let ((display-hourglass 5)) display-hourglass) => t -- Variable: byte-boolean-vars This variable holds a list of all variables of type `DEFVAR_BOOL'. Variables of type `DEFVAR_INT' can only take on integer values. Attempting to assign them any other value will result in an error: (setq window-min-height 5.0) error--> Wrong type argument: integerp, 5.0  File: elisp, Node: Functions, Next: Macros, Prev: Variables, Up: Top 12 Functions ************ A Lisp program is composed mainly of Lisp functions. This chapter explains what functions are, how they accept arguments, and how to define them. * Menu: * What Is a Function:: Lisp functions vs. primitives; terminology. * Lambda Expressions:: How functions are expressed as Lisp objects. * Function Names:: A symbol can serve as the name of a function. * Defining Functions:: Lisp expressions for defining functions. * Calling Functions:: How to use an existing function. * Mapping Functions:: Applying a function to each element of a list, etc. * Anonymous Functions:: Lambda expressions are functions with no names. * Function Cells:: Accessing or setting the function definition of a symbol. * Obsolete Functions:: Declaring functions obsolete. * Inline Functions:: Defining functions that the compiler will open code. * Declaring Functions:: Telling the compiler that a function is defined. * Function Safety:: Determining whether a function is safe to call. * Related Topics:: Cross-references to specific Lisp primitives that have a special bearing on how functions work.  File: elisp, Node: What Is a Function, Next: Lambda Expressions, Up: Functions 12.1 What Is a Function? ======================== In a general sense, a function is a rule for carrying on a computation given several values called "arguments". The result of the computation is called the value of the function. The computation can also have side effects: lasting changes in the values of variables or the contents of data structures. Here are important terms for functions in Emacs Lisp and for other function-like objects. "function" In Emacs Lisp, a "function" is anything that can be applied to arguments in a Lisp program. In some cases, we use it more specifically to mean a function written in Lisp. Special forms and macros are not functions. "primitive" A "primitive" is a function callable from Lisp that is written in C, such as `car' or `append'. These functions are also called "built-in functions", or "subrs". (Special forms are also considered primitives.) Usually the reason we implement a function as a primitive is either because it is fundamental, because it provides a low-level interface to operating system services, or because it needs to run fast. Primitives can be modified or added only by changing the C sources and recompiling the editor. See *note Writing Emacs Primitives::. "lambda expression" A "lambda expression" is a function written in Lisp. These are described in the following section. *Note Lambda Expressions::. "special form" A "special form" is a primitive that is like a function but does not evaluate all of its arguments in the usual way. It may evaluate only some of the arguments, or may evaluate them in an unusual order, or several times. Many special forms are described in *note Control Structures::. "macro" A "macro" is a construct defined in Lisp by the programmer. It differs from a function in that it translates a Lisp expression that you write into an equivalent expression to be evaluated instead of the original expression. Macros enable Lisp programmers to do the sorts of things that special forms can do. *Note Macros::, for how to define and use macros. "command" A "command" is an object that `command-execute' can invoke; it is a possible definition for a key sequence. Some functions are commands; a function written in Lisp is a command if it contains an interactive declaration (*note Defining Commands::). Such a function can be called from Lisp expressions like other functions; in this case, the fact that the function is a command makes no difference. Keyboard macros (strings and vectors) are commands also, even though they are not functions. A symbol is a command if its function definition is a command; such symbols can be invoked with `M-x'. The symbol is a function as well if the definition is a function. *Note Interactive Call::. "keystroke command" A "keystroke command" is a command that is bound to a key sequence (typically one to three keystrokes). The distinction is made here merely to avoid confusion with the meaning of "command" in non-Emacs editors; for Lisp programs, the distinction is normally unimportant. "byte-code function" A "byte-code function" is a function that has been compiled by the byte compiler. *Note Byte-Code Type::. -- Function: functionp object This function returns `t' if OBJECT is any kind of function, i.e. can be passed to `funcall'. Note that `functionp' returns `nil' for special forms (*note Special Forms::). Unlike `functionp', the next three functions do _not_ treat a symbol as its function definition. -- Function: subrp object This function returns `t' if OBJECT is a built-in function (i.e., a Lisp primitive). (subrp 'message) ; `message' is a symbol, => nil ; not a subr object. (subrp (symbol-function 'message)) => t -- Function: byte-code-function-p object This function returns `t' if OBJECT is a byte-code function. For example: (byte-code-function-p (symbol-function 'next-line)) => t -- Function: subr-arity subr This function provides information about the argument list of a primitive, SUBR. The returned value is a pair `(MIN . MAX)'. MIN is the minimum number of args. MAX is the maximum number or the symbol `many', for a function with `&rest' arguments, or the symbol `unevalled' if SUBR is a special form.  File: elisp, Node: Lambda Expressions, Next: Function Names, Prev: What Is a Function, Up: Functions 12.2 Lambda Expressions ======================= A function written in Lisp is a list that looks like this: (lambda (ARG-VARIABLES...) [DOCUMENTATION-STRING] [INTERACTIVE-DECLARATION] BODY-FORMS...) Such a list is called a "lambda expression". In Emacs Lisp, it actually is valid as an expression--it evaluates to itself. In some other Lisp dialects, a lambda expression is not a valid expression at all. In either case, its main use is not to be evaluated as an expression, but to be called as a function. * Menu: * Lambda Components:: The parts of a lambda expression. * Simple Lambda:: A simple example. * Argument List:: Details and special features of argument lists. * Function Documentation:: How to put documentation in a function.  File: elisp, Node: Lambda Components, Next: Simple Lambda, Up: Lambda Expressions 12.2.1 Components of a Lambda Expression ---------------------------------------- A function written in Lisp (a "lambda expression") is a list that looks like this: (lambda (ARG-VARIABLES...) [DOCUMENTATION-STRING] [INTERACTIVE-DECLARATION] BODY-FORMS...) The first element of a lambda expression is always the symbol `lambda'. This indicates that the list represents a function. The reason functions are defined to start with `lambda' is so that other lists, intended for other uses, will not accidentally be valid as functions. The second element is a list of symbols--the argument variable names. This is called the "lambda list". When a Lisp function is called, the argument values are matched up against the variables in the lambda list, which are given local bindings with the values provided. *Note Local Variables::. The documentation string is a Lisp string object placed within the function definition to describe the function for the Emacs help facilities. *Note Function Documentation::. The interactive declaration is a list of the form `(interactive CODE-STRING)'. This declares how to provide arguments if the function is used interactively. Functions with this declaration are called "commands"; they can be called using `M-x' or bound to a key. Functions not intended to be called in this way should not have interactive declarations. *Note Defining Commands::, for how to write an interactive declaration. The rest of the elements are the "body" of the function: the Lisp code to do the work of the function (or, as a Lisp programmer would say, "a list of Lisp forms to evaluate"). The value returned by the function is the value returned by the last element of the body.  File: elisp, Node: Simple Lambda, Next: Argument List, Prev: Lambda Components, Up: Lambda Expressions 12.2.2 A Simple Lambda-Expression Example ----------------------------------------- Consider for example the following function: (lambda (a b c) (+ a b c)) We can call this function by writing it as the CAR of an expression, like this: ((lambda (a b c) (+ a b c)) 1 2 3) This call evaluates the body of the lambda expression with the variable `a' bound to 1, `b' bound to 2, and `c' bound to 3. Evaluation of the body adds these three numbers, producing the result 6; therefore, this call to the function returns the value 6. Note that the arguments can be the results of other function calls, as in this example: ((lambda (a b c) (+ a b c)) 1 (* 2 3) (- 5 4)) This evaluates the arguments `1', `(* 2 3)', and `(- 5 4)' from left to right. Then it applies the lambda expression to the argument values 1, 6 and 1 to produce the value 8. It is not often useful to write a lambda expression as the CAR of a form in this way. You can get the same result, of making local variables and giving them values, using the special form `let' (*note Local Variables::). And `let' is clearer and easier to use. In practice, lambda expressions are either stored as the function definitions of symbols, to produce named functions, or passed as arguments to other functions (*note Anonymous Functions::). However, calls to explicit lambda expressions were very useful in the old days of Lisp, before the special form `let' was invented. At that time, they were the only way to bind and initialize local variables.  File: elisp, Node: Argument List, Next: Function Documentation, Prev: Simple Lambda, Up: Lambda Expressions 12.2.3 Other Features of Argument Lists --------------------------------------- Our simple sample function, `(lambda (a b c) (+ a b c))', specifies three argument variables, so it must be called with three arguments: if you try to call it with only two arguments or four arguments, you get a `wrong-number-of-arguments' error. It is often convenient to write a function that allows certain arguments to be omitted. For example, the function `substring' accepts three arguments--a string, the start index and the end index--but the third argument defaults to the LENGTH of the string if you omit it. It is also convenient for certain functions to accept an indefinite number of arguments, as the functions `list' and `+' do. To specify optional arguments that may be omitted when a function is called, simply include the keyword `&optional' before the optional arguments. To specify a list of zero or more extra arguments, include the keyword `&rest' before one final argument. Thus, the complete syntax for an argument list is as follows: (REQUIRED-VARS... [&optional OPTIONAL-VARS...] [&rest REST-VAR]) The square brackets indicate that the `&optional' and `&rest' clauses, and the variables that follow them, are optional. A call to the function requires one actual argument for each of the REQUIRED-VARS. There may be actual arguments for zero or more of the OPTIONAL-VARS, and there cannot be any actual arguments beyond that unless the lambda list uses `&rest'. In that case, there may be any number of extra actual arguments. If actual arguments for the optional and rest variables are omitted, then they always default to `nil'. There is no way for the function to distinguish between an explicit argument of `nil' and an omitted argument. However, the body of the function is free to consider `nil' an abbreviation for some other meaningful value. This is what `substring' does; `nil' as the third argument to `substring' means to use the length of the string supplied. Common Lisp note: Common Lisp allows the function to specify what default value to use when an optional argument is omitted; Emacs Lisp always uses `nil'. Emacs Lisp does not support "supplied-p" variables that tell you whether an argument was explicitly passed. For example, an argument list that looks like this: (a b &optional c d &rest e) binds `a' and `b' to the first two actual arguments, which are required. If one or two more arguments are provided, `c' and `d' are bound to them respectively; any arguments after the first four are collected into a list and `e' is bound to that list. If there are only two arguments, `c' is `nil'; if two or three arguments, `d' is `nil'; if four arguments or fewer, `e' is `nil'. There is no way to have required arguments following optional ones--it would not make sense. To see why this must be so, suppose that `c' in the example were optional and `d' were required. Suppose three actual arguments are given; which variable would the third argument be for? Would it be used for the C, or for D? One can argue for both possibilities. Similarly, it makes no sense to have any more arguments (either required or optional) after a `&rest' argument. Here are some examples of argument lists and proper calls: ((lambda (n) (1+ n)) ; One required: 1) ; requires exactly one argument. => 2 ((lambda (n &optional n1) ; One required and one optional: (if n1 (+ n n1) (1+ n))) ; 1 or 2 arguments. 1 2) => 3 ((lambda (n &rest ns) ; One required and one rest: (+ n (apply '+ ns))) ; 1 or more arguments. 1 2 3 4 5) => 15  File: elisp, Node: Function Documentation, Prev: Argument List, Up: Lambda Expressions 12.2.4 Documentation Strings of Functions ----------------------------------------- A lambda expression may optionally have a "documentation string" just after the lambda list. This string does not affect execution of the function; it is a kind of comment, but a systematized comment which actually appears inside the Lisp world and can be used by the Emacs help facilities. *Note Documentation::, for how the DOCUMENTATION-STRING is accessed. It is a good idea to provide documentation strings for all the functions in your program, even those that are called only from within your program. Documentation strings are like comments, except that they are easier to access. The first line of the documentation string should stand on its own, because `apropos' displays just this first line. It should consist of one or two complete sentences that summarize the function's purpose. The start of the documentation string is usually indented in the source file, but since these spaces come before the starting double-quote, they are not part of the string. Some people make a practice of indenting any additional lines of the string so that the text lines up in the program source. _That is a mistake._ The indentation of the following lines is inside the string; what looks nice in the source code will look ugly when displayed by the help commands. You may wonder how the documentation string could be optional, since there are required components of the function that follow it (the body). Since evaluation of a string returns that string, without any side effects, it has no effect if it is not the last form in the body. Thus, in practice, there is no confusion between the first form of the body and the documentation string; if the only body form is a string then it serves both as the return value and as the documentation. The last line of the documentation string can specify calling conventions different from the actual function arguments. Write text like this: \(fn ARGLIST) following a blank line, at the beginning of the line, with no newline following it inside the documentation string. (The `\' is used to avoid confusing the Emacs motion commands.) The calling convention specified in this way appears in help messages in place of the one derived from the actual arguments of the function. This feature is particularly useful for macro definitions, since the arguments written in a macro definition often do not correspond to the way users think of the parts of the macro call.  File: elisp, Node: Function Names, Next: Defining Functions, Prev: Lambda Expressions, Up: Functions 12.3 Naming a Function ====================== In most computer languages, every function has a name; the idea of a function without a name is nonsensical. In Lisp, a function in the strictest sense has no name. It is simply a list whose first element is `lambda', a byte-code function object, or a primitive subr-object. However, a symbol can serve as the name of a function. This happens when you put the function in the symbol's "function cell" (*note Symbol Components::). Then the symbol itself becomes a valid, callable function, equivalent to the list or subr-object that its function cell refers to. The contents of the function cell are also called the symbol's "function definition". The procedure of using a symbol's function definition in place of the symbol is called "symbol function indirection"; see *note Function Indirection::. In practice, nearly all functions are given names in this way and referred to through their names. For example, the symbol `car' works as a function and does what it does because the primitive subr-object `#' is stored in its function cell. We give functions names because it is convenient to refer to them by their names in Lisp expressions. For primitive subr-objects such as `#', names are the only way you can refer to them: there is no read syntax for such objects. For functions written in Lisp, the name is more convenient to use in a call than an explicit lambda expression. Also, a function with a name can refer to itself--it can be recursive. Writing the function's name in its own definition is much more convenient than making the function definition point to itself (something that is not impossible but that has various disadvantages in practice). We often identify functions with the symbols used to name them. For example, we often speak of "the function `car'," not distinguishing between the symbol `car' and the primitive subr-object that is its function definition. For most purposes, the distinction is not important. Even so, keep in mind that a function need not have a unique name. While a given function object _usually_ appears in the function cell of only one symbol, this is just a matter of convenience. It is easy to store it in several symbols using `fset'; then each of the symbols is equally well a name for the same function. A symbol used as a function name may also be used as a variable; these two uses of a symbol are independent and do not conflict. (Some Lisp dialects, such as Scheme, do not distinguish between a symbol's value and its function definition; a symbol's value as a variable is also its function definition.) If you have not given a symbol a function definition, you cannot use it as a function; whether the symbol has a value as a variable makes no difference to this.  File: elisp, Node: Defining Functions, Next: Calling Functions, Prev: Function Names, Up: Functions 12.4 Defining Functions ======================= We usually give a name to a function when it is first created. This is called "defining a function", and it is done with the `defun' special form. -- Special Form: defun name argument-list body-forms `defun' is the usual way to define new Lisp functions. It defines the symbol NAME as a function that looks like this: (lambda ARGUMENT-LIST . BODY-FORMS) `defun' stores this lambda expression in the function cell of NAME. It returns the value NAME, but usually we ignore this value. As described previously, ARGUMENT-LIST is a list of argument names and may include the keywords `&optional' and `&rest' (*note Lambda Expressions::). Also, the first two of the BODY-FORMS may be a documentation string and an interactive declaration. There is no conflict if the same symbol NAME is also used as a variable, since the symbol's value cell is independent of the function cell. *Note Symbol Components::. Here are some examples: (defun foo () 5) => foo (foo) => 5 (defun bar (a &optional b &rest c) (list a b c)) => bar (bar 1 2 3 4 5) => (1 2 (3 4 5)) (bar 1) => (1 nil nil) (bar) error--> Wrong number of arguments. (defun capitalize-backwards () "Upcase the last letter of a word." (interactive) (backward-word 1) (forward-word 1) (backward-char 1) (capitalize-word 1)) => capitalize-backwards Be careful not to redefine existing functions unintentionally. `defun' redefines even primitive functions such as `car' without any hesitation or notification. Redefining a function already defined is often done deliberately, and there is no way to distinguish deliberate redefinition from unintentional redefinition. -- Function: defalias name definition &optional docstring This special form defines the symbol NAME as a function, with definition DEFINITION (which can be any valid Lisp function). It returns DEFINITION. If DOCSTRING is non-`nil', it becomes the function documentation of NAME. Otherwise, any documentation provided by DEFINITION is used. The proper place to use `defalias' is where a specific function name is being defined--especially where that name appears explicitly in the source file being loaded. This is because `defalias' records which file defined the function, just like `defun' (*note Unloading::). By contrast, in programs that manipulate function definitions for other purposes, it is better to use `fset', which does not keep such records. *Note Function Cells::. You cannot create a new primitive function with `defun' or `defalias', but you can use them to change the function definition of any symbol, even one such as `car' or `x-popup-menu' whose normal definition is a primitive. However, this is risky: for instance, it is next to impossible to redefine `car' without breaking Lisp completely. Redefining an obscure function such as `x-popup-menu' is less dangerous, but it still may not work as you expect. If there are calls to the primitive from C code, they call the primitive's C definition directly, so changing the symbol's definition will have no effect on them. See also `defsubst', which defines a function like `defun' and tells the Lisp compiler to open-code it. *Note Inline Functions::.  File: elisp, Node: Calling Functions, Next: Mapping Functions, Prev: Defining Functions, Up: Functions 12.5 Calling Functions ====================== Defining functions is only half the battle. Functions don't do anything until you "call" them, i.e., tell them to run. Calling a function is also known as "invocation". The most common way of invoking a function is by evaluating a list. For example, evaluating the list `(concat "a" "b")' calls the function `concat' with arguments `"a"' and `"b"'. *Note Evaluation::, for a description of evaluation. When you write a list as an expression in your program, you specify which function to call, and how many arguments to give it, in the text of the program. Usually that's just what you want. Occasionally you need to compute at run time which function to call. To do that, use the function `funcall'. When you also need to determine at run time how many arguments to pass, use `apply'. -- Function: funcall function &rest arguments `funcall' calls FUNCTION with ARGUMENTS, and returns whatever FUNCTION returns. Since `funcall' is a function, all of its arguments, including FUNCTION, are evaluated before `funcall' is called. This means that you can use any expression to obtain the function to be called. It also means that `funcall' does not see the expressions you write for the ARGUMENTS, only their values. These values are _not_ evaluated a second time in the act of calling FUNCTION; the operation of `funcall' is like the normal procedure for calling a function, once its arguments have already been evaluated. The argument FUNCTION must be either a Lisp function or a primitive function. Special forms and macros are not allowed, because they make sense only when given the "unevaluated" argument expressions. `funcall' cannot provide these because, as we saw above, it never knows them in the first place. (setq f 'list) => list (funcall f 'x 'y 'z) => (x y z) (funcall f 'x 'y '(z)) => (x y (z)) (funcall 'and t nil) error--> Invalid function: # Compare these examples with the examples of `apply'. -- Function: apply function &rest arguments `apply' calls FUNCTION with ARGUMENTS, just like `funcall' but with one difference: the last of ARGUMENTS is a list of objects, which are passed to FUNCTION as separate arguments, rather than a single list. We say that `apply' "spreads" this list so that each individual element becomes an argument. `apply' returns the result of calling FUNCTION. As with `funcall', FUNCTION must either be a Lisp function or a primitive function; special forms and macros do not make sense in `apply'. (setq f 'list) => list (apply f 'x 'y 'z) error--> Wrong type argument: listp, z (apply '+ 1 2 '(3 4)) => 10 (apply '+ '(1 2 3 4)) => 10 (apply 'append '((a b c) nil (x y z) nil)) => (a b c x y z) For an interesting example of using `apply', see *note Definition of mapcar::. Sometimes it is useful to fix some of the function's arguments at certain values, and leave the rest of arguments for when the function is actually called. The act of fixing some of the function's arguments is called "partial application" of the function(1). The result is a new function that accepts the rest of arguments and calls the original function with all the arguments combined. Here's how to do partial application in Emacs Lisp: -- Function: apply-partially func &rest args This function returns a new function which, when called, will call FUNC with the list of arguments composed from ARGS and additional arguments specified at the time of the call. If FUNC accepts N arguments, then a call to `apply-partially' with `M < N' arguments will produce a new function of `N - M' arguments. Here's how we could define the built-in function `1+', if it didn't exist, using `apply-partially' and `+', another built-in function: (defalias '1+ (apply-partially '+ 1) "Increment argument by one.") (1+ 10) => 11 It is common for Lisp functions to accept functions as arguments or find them in data structures (especially in hook variables and property lists) and call them using `funcall' or `apply'. Functions that accept function arguments are often called "functionals". Sometimes, when you call a functional, it is useful to supply a no-op function as the argument. Here are two different kinds of no-op function: -- Function: identity arg This function returns ARG and has no side effects. -- Function: ignore &rest args This function ignores any arguments and returns `nil'. ---------- Footnotes ---------- (1) This is related to, but different from "currying", which transforms a function that takes multiple arguments in such a way that it can be called as a chain of functions, each one with a single argument.  File: elisp, Node: Mapping Functions, Next: Anonymous Functions, Prev: Calling Functions, Up: Functions 12.6 Mapping Functions ====================== A "mapping function" applies a given function (_not_ a special form or macro) to each element of a list or other collection. Emacs Lisp has several such functions; `mapcar' and `mapconcat', which scan a list, are described here. *Note Definition of mapatoms::, for the function `mapatoms' which maps over the symbols in an obarray. *Note Definition of maphash::, for the function `maphash' which maps over key/value associations in a hash table. These mapping functions do not allow char-tables because a char-table is a sparse array whose nominal range of indices is very large. To map over a char-table in a way that deals properly with its sparse nature, use the function `map-char-table' (*note Char-Tables::). -- Function: mapcar function sequence `mapcar' applies FUNCTION to each element of SEQUENCE in turn, and returns a list of the results. The argument SEQUENCE can be any kind of sequence except a char-table; that is, a list, a vector, a bool-vector, or a string. The result is always a list. The length of the result is the same as the length of SEQUENCE. For example: (mapcar 'car '((a b) (c d) (e f))) => (a c e) (mapcar '1+ [1 2 3]) => (2 3 4) (mapcar 'char-to-string "abc") => ("a" "b" "c") ;; Call each function in `my-hooks'. (mapcar 'funcall my-hooks) (defun mapcar* (function &rest args) "Apply FUNCTION to successive cars of all ARGS. Return the list of results." ;; If no list is exhausted, (if (not (memq nil args)) ;; apply function to CARs. (cons (apply function (mapcar 'car args)) (apply 'mapcar* function ;; Recurse for rest of elements. (mapcar 'cdr args))))) (mapcar* 'cons '(a b c) '(1 2 3 4)) => ((a . 1) (b . 2) (c . 3)) -- Function: mapc function sequence `mapc' is like `mapcar' except that FUNCTION is used for side-effects only--the values it returns are ignored, not collected into a list. `mapc' always returns SEQUENCE. -- Function: mapconcat function sequence separator `mapconcat' applies FUNCTION to each element of SEQUENCE: the results, which must be strings, are concatenated. Between each pair of result strings, `mapconcat' inserts the string SEPARATOR. Usually SEPARATOR contains a space or comma or other suitable punctuation. The argument FUNCTION must be a function that can take one argument and return a string. The argument SEQUENCE can be any kind of sequence except a char-table; that is, a list, a vector, a bool-vector, or a string. (mapconcat 'symbol-name '(The cat in the hat) " ") => "The cat in the hat" (mapconcat (function (lambda (x) (format "%c" (1+ x)))) "HAL-8000" "") => "IBM.9111"  File: elisp, Node: Anonymous Functions, Next: Function Cells, Prev: Mapping Functions, Up: Functions 12.7 Anonymous Functions ======================== In Lisp, a function is a list that starts with `lambda', a byte-code function compiled from such a list, or alternatively a primitive subr-object; names are "extra." Although functions are usually defined with `defun' and given names at the same time, it is occasionally more concise to use an explicit lambda expression--an anonymous function. Such a list is valid wherever a function name is. Any method of creating such a list makes a valid function. Even this: (setq silly (append '(lambda (x)) (list (list '+ (* 3 4) 'x)))) => (lambda (x) (+ 12 x)) This computes a list that looks like `(lambda (x) (+ 12 x))' and makes it the value (_not_ the function definition!) of `silly'. Here is how we might call this function: (funcall silly 1) => 13 It does _not_ work to write `(silly 1)', because this function is not the _function definition_ of `silly'. We have not given `silly' any function definition, just a value as a variable. Most of the time, anonymous functions are constants that appear in your program. For instance, you might want to pass one as an argument to the function `mapcar', which applies any given function to each element of a list (*note Mapping Functions::). *Note describe-symbols example::, for a realistic example of this. In the following example, we define a `change-property' function that takes a function as its third argument, followed by a `double-property' function that makes use of `change-property' by passing it an anonymous function: (defun change-property (symbol prop function) (let ((value (get symbol prop))) (put symbol prop (funcall function value)))) (defun double-property (symbol prop) (change-property symbol prop (lambda (x) (* 2 x)))) In the `double-property' function, we did not quote the `lambda' form. This is permissible, because a `lambda' form is "self-quoting": evaluating the form yields the form itself. Whether or not you quote a `lambda' form makes a difference if you compile the code (*note Byte Compilation::). If the `lambda' form is unquoted, as in the above example, the anonymous function is also compiled. Suppose, however, that we quoted the `lambda' form: (defun double-property (symbol prop) (change-property symbol prop '(lambda (x) (* 2 x)))) If you compile this, the argument passed to `change-property' is the precise list shown: (lambda (x) (* x 2)) The Lisp compiler cannot assume this list is a function, even though it looks like one, since it does not know what `change-property' will do with the list. Perhaps it will check whether the CAR of the third element is the symbol `*'! The `function' special form explicitly tells the byte-compiler that its argument is a function: -- Special Form: function function-object This special form returns FUNCTION-OBJECT without evaluating it. In this, it is equivalent to `quote'. However, it serves as a note to the Emacs Lisp compiler that FUNCTION-OBJECT is intended to be used only as a function, and therefore can safely be compiled. Contrast this with `quote', in *note Quoting::. The read syntax `#'' is a short-hand for using `function'. Generally, it is not necessary to use either `#'' or `function'; just use an unquoted `lambda' form instead. (Actually, `lambda' is a macro defined using `function'.) The following forms are all equivalent: #'(lambda (x) (* x x)) (function (lambda (x) (* x x))) (lambda (x) (* x x)) We sometimes write `function' instead of `quote' when quoting the name of a function, but this usage is just a sort of comment: (function SYMBOL) == (quote SYMBOL) == 'SYMBOL  File: elisp, Node: Function Cells, Next: Obsolete Functions, Prev: Anonymous Functions, Up: Functions 12.8 Accessing Function Cell Contents ===================================== The "function definition" of a symbol is the object stored in the function cell of the symbol. The functions described here access, test, and set the function cell of symbols. See also the function `indirect-function'. *Note Definition of indirect-function::. -- Function: symbol-function symbol This returns the object in the function cell of SYMBOL. If the symbol's function cell is void, a `void-function' error is signaled. This function does not check that the returned object is a legitimate function. (defun bar (n) (+ n 2)) => bar (symbol-function 'bar) => (lambda (n) (+ n 2)) (fset 'baz 'bar) => bar (symbol-function 'baz) => bar If you have never given a symbol any function definition, we say that that symbol's function cell is "void". In other words, the function cell does not have any Lisp object in it. If you try to call such a symbol as a function, it signals a `void-function' error. Note that void is not the same as `nil' or the symbol `void'. The symbols `nil' and `void' are Lisp objects, and can be stored into a function cell just as any other object can be (and they can be valid functions if you define them in turn with `defun'). A void function cell contains no object whatsoever. You can test the voidness of a symbol's function definition with `fboundp'. After you have given a symbol a function definition, you can make it void once more using `fmakunbound'. -- Function: fboundp symbol This function returns `t' if the symbol has an object in its function cell, `nil' otherwise. It does not check that the object is a legitimate function. -- Function: fmakunbound symbol This function makes SYMBOL's function cell void, so that a subsequent attempt to access this cell will cause a `void-function' error. It returns SYMBOL. (See also `makunbound', in *note Void Variables::.) (defun foo (x) x) => foo (foo 1) =>1 (fmakunbound 'foo) => foo (foo 1) error--> Symbol's function definition is void: foo -- Function: fset symbol definition This function stores DEFINITION in the function cell of SYMBOL. The result is DEFINITION. Normally DEFINITION should be a function or the name of a function, but this is not checked. The argument SYMBOL is an ordinary evaluated argument. There are three normal uses of this function: * Copying one symbol's function definition to another--in other words, making an alternate name for a function. (If you think of this as the definition of the new name, you should use `defalias' instead of `fset'; see *note Definition of defalias::.) * Giving a symbol a function definition that is not a list and therefore cannot be made with `defun'. For example, you can use `fset' to give a symbol `s1' a function definition which is another symbol `s2'; then `s1' serves as an alias for whatever definition `s2' presently has. (Once again use `defalias' instead of `fset' if you think of this as the definition of `s1'.) * In constructs for defining or altering functions. If `defun' were not a primitive, it could be written in Lisp (as a macro) using `fset'. Here are examples of these uses: ;; Save `foo''s definition in `old-foo'. (fset 'old-foo (symbol-function 'foo)) ;; Make the symbol `car' the function definition of `xfirst'. ;; (Most likely, `defalias' would be better than `fset' here.) (fset 'xfirst 'car) => car (xfirst '(1 2 3)) => 1 (symbol-function 'xfirst) => car (symbol-function (symbol-function 'xfirst)) => # ;; Define a named keyboard macro. (fset 'kill-two-lines "\^u2\^k") => "\^u2\^k" ;; Here is a function that alters other functions. (defun copy-function-definition (new old) "Define NEW with the same function definition as OLD." (fset new (symbol-function old))) `fset' is sometimes used to save the old definition of a function before redefining it. That permits the new definition to invoke the old definition. But it is unmodular and unclean for a Lisp file to redefine a function defined elsewhere. If you want to modify a function defined by another package, it is cleaner to use `defadvice' (*note Advising Functions::).  File: elisp, Node: Obsolete Functions, Next: Inline Functions, Prev: Function Cells, Up: Functions 12.9 Declaring Functions Obsolete ================================= You can use `make-obsolete' to declare a function obsolete. This indicates that the function may be removed at some stage in the future. -- Function: make-obsolete obsolete-name current-name &optional when This function makes the byte compiler warn that the function OBSOLETE-NAME is obsolete. If CURRENT-NAME is a symbol, the warning message says to use CURRENT-NAME instead of OBSOLETE-NAME. CURRENT-NAME does not need to be an alias for OBSOLETE-NAME; it can be a different function with similar functionality. If CURRENT-NAME is a string, it is the warning message. If provided, WHEN should be a string indicating when the function was first made obsolete--for example, a date or a release number. You can define a function as an alias and declare it obsolete at the same time using the macro `define-obsolete-function-alias': -- Macro: define-obsolete-function-alias obsolete-name current-name &optional when docstring This macro marks the function OBSOLETE-NAME obsolete and also defines it as an alias for the function CURRENT-NAME. It is equivalent to the following: (defalias OBSOLETE-NAME CURRENT-NAME DOCSTRING) (make-obsolete OBSOLETE-NAME CURRENT-NAME WHEN) In addition, you can mark a certain a particular calling convention for a function as obsolete: -- Function: set-advertised-calling-convention function signature This function specifies the argument list SIGNATURE as the correct way to call FUNCTION. This causes the Emacs byte compiler to issue a warning whenever it comes across an Emacs Lisp program that calls FUNCTION any other way (however, it will still allow the code to be byte compiled). For instance, in old versions of Emacs the `sit-for' function accepted three arguments, like this (sit-for seconds milliseconds nodisp) However, calling `sit-for' this way is considered obsolete (*note Waiting::). The old calling convention is deprecated like this: (set-advertised-calling-convention 'sit-for '(seconds &optional nodisp))  File: elisp, Node: Inline Functions, Next: Declaring Functions, Prev: Obsolete Functions, Up: Functions 12.10 Inline Functions ====================== You can define an "inline function" by using `defsubst' instead of `defun'. An inline function works just like an ordinary function except for one thing: when you compile a call to the function, the function's definition is open-coded into the caller. Making a function inline makes explicit calls run faster. But it also has disadvantages. For one thing, it reduces flexibility; if you change the definition of the function, calls already inlined still use the old definition until you recompile them. Another disadvantage is that making a large function inline can increase the size of compiled code both in files and in memory. Since the speed advantage of inline functions is greatest for small functions, you generally should not make large functions inline. Also, inline functions do not behave well with respect to debugging, tracing, and advising (*note Advising Functions::). Since ease of debugging and the flexibility of redefining functions are important features of Emacs, you should not make a function inline, even if it's small, unless its speed is really crucial, and you've timed the code to verify that using `defun' actually has performance problems. It's possible to define a macro to expand into the same code that an inline function would execute. (*Note Macros::.) But the macro would be limited to direct use in expressions--a macro cannot be called with `apply', `mapcar' and so on. Also, it takes some work to convert an ordinary function into a macro. To convert it into an inline function is very easy; simply replace `defun' with `defsubst'. Since each argument of an inline function is evaluated exactly once, you needn't worry about how many times the body uses the arguments, as you do for macros. (*Note Argument Evaluation::.) Inline functions can be used and open-coded later on in the same file, following the definition, just like macros.  File: elisp, Node: Declaring Functions, Next: Function Safety, Prev: Inline Functions, Up: Functions 12.11 Telling the Compiler that a Function is Defined ===================================================== Byte-compiling a file often produces warnings about functions that the compiler doesn't know about (*note Compiler Errors::). Sometimes this indicates a real problem, but usually the functions in question are defined in other files which would be loaded if that code is run. For example, byte-compiling `fortran.el' used to warn: In end of data: fortran.el:2152:1:Warning: the function `gud-find-c-expr' is not known to be defined. In fact, `gud-find-c-expr' is only used in the function that Fortran mode uses for the local value of `gud-find-expr-function', which is a callback from GUD; if it is called, the GUD functions will be loaded. When you know that such a warning does not indicate a real problem, it is good to suppress the warning. That makes new warnings which might mean real problems more visible. You do that with `declare-function'. All you need to do is add a `declare-function' statement before the first use of the function in question: (declare-function gud-find-c-expr "gud.el" nil) This says that `gud-find-c-expr' is defined in `gud.el' (the `.el' can be omitted). The compiler takes for granted that that file really defines the function, and does not check. The optional third argument specifies the argument list of `gud-find-c-expr'. In this case, it takes no arguments (`nil' is different from not specifying a value). In other cases, this might be something like `(file &optional overwrite)'. You don't have to specify the argument list, but if you do the byte compiler can check that the calls match the declaration. -- Macro: declare-function function file &optional arglist fileonly Tell the byte compiler to assume that FUNCTION is defined, with arguments ARGLIST, and that the definition should come from the file FILE. FILEONLY non-`nil' means only check that FILE exists, not that it actually defines FUNCTION. To verify that these functions really are declared where `declare-function' says they are, use `check-declare-file' to check all `declare-function' calls in one source file, or use `check-declare-directory' check all the files in and under a certain directory. These commands find the file that ought to contain a function's definition using `locate-library'; if that finds no file, they expand the definition file name relative to the directory of the file that contains the `declare-function' call. You can also say that a function is defined by C code by specifying a file name ending in `.c' or `.m'. `check-declare-file' looks for these files in the C source code directory. This is useful only when you call a function that is defined only on certain systems. Most of the primitive functions of Emacs are always defined so they will never give you a warning. Sometimes a file will optionally use functions from an external package. If you prefix the filename in the `declare-function' statement with `ext:', then it will be checked if it is found, otherwise skipped without error. There are some function definitions that `check-declare' does not understand (e.g. `defstruct' and some other macros). In such cases, you can pass a non-`nil' FILEONLY argument to `declare-function', meaning to only check that the file exists, not that it actually defines the function. Note that to do this without having to specify an argument list, you should set the ARGLIST argument to `t' (because `nil' means an empty argument list, as opposed to an unspecified one).  File: elisp, Node: Function Safety, Next: Related Topics, Prev: Declaring Functions, Up: Functions 12.12 Determining whether a Function is Safe to Call ==================================================== Some major modes such as SES call functions that are stored in user files. (*note (ses)Top::, for more information on SES.) User files sometimes have poor pedigrees--you can get a spreadsheet from someone you've just met, or you can get one through email from someone you've never met. So it is risky to call a function whose source code is stored in a user file until you have determined that it is safe. -- Function: unsafep form &optional unsafep-vars Returns `nil' if FORM is a "safe" Lisp expression, or returns a list that describes why it might be unsafe. The argument UNSAFEP-VARS is a list of symbols known to have temporary bindings at this point; it is mainly used for internal recursive calls. The current buffer is an implicit argument, which provides a list of buffer-local bindings. Being quick and simple, `unsafep' does a very light analysis and rejects many Lisp expressions that are actually safe. There are no known cases where `unsafep' returns `nil' for an unsafe expression. However, a "safe" Lisp expression can return a string with a `display' property, containing an associated Lisp expression to be executed after the string is inserted into a buffer. This associated expression can be a virus. In order to be safe, you must delete properties from all strings calculated by user code before inserting them into buffers.  File: elisp, Node: Related Topics, Prev: Function Safety, Up: Functions 12.13 Other Topics Related to Functions ======================================= Here is a table of several functions that do things related to function calling and function definitions. They are documented elsewhere, but we provide cross references here. `apply' See *note Calling Functions::. `autoload' See *note Autoload::. `call-interactively' See *note Interactive Call::. `called-interactively-p' See *note Distinguish Interactive::. `commandp' See *note Interactive Call::. `documentation' See *note Accessing Documentation::. `eval' See *note Eval::. `funcall' See *note Calling Functions::. `function' See *note Anonymous Functions::. `ignore' See *note Calling Functions::. `indirect-function' See *note Function Indirection::. `interactive' See *note Using Interactive::. `interactive-p' See *note Distinguish Interactive::. `mapatoms' See *note Creating Symbols::. `mapcar' See *note Mapping Functions::. `map-char-table' See *note Char-Tables::. `mapconcat' See *note Mapping Functions::. `undefined' See *note Functions for Key Lookup::.  File: elisp, Node: Macros, Next: Customization, Prev: Functions, Up: Top 13 Macros ********* "Macros" enable you to define new control constructs and other language features. A macro is defined much like a function, but instead of telling how to compute a value, it tells how to compute another Lisp expression which will in turn compute the value. We call this expression the "expansion" of the macro. Macros can do this because they operate on the unevaluated expressions for the arguments, not on the argument values as functions do. They can therefore construct an expansion containing these argument expressions or parts of them. If you are using a macro to do something an ordinary function could do, just for the sake of speed, consider using an inline function instead. *Note Inline Functions::. * Menu: * Simple Macro:: A basic example. * Expansion:: How, when and why macros are expanded. * Compiling Macros:: How macros are expanded by the compiler. * Defining Macros:: How to write a macro definition. * Backquote:: Easier construction of list structure. * Problems with Macros:: Don't evaluate the macro arguments too many times. Don't hide the user's variables. * Indenting Macros:: Specifying how to indent macro calls.  File: elisp, Node: Simple Macro, Next: Expansion, Up: Macros 13.1 A Simple Example of a Macro ================================ Suppose we would like to define a Lisp construct to increment a variable value, much like the `++' operator in C. We would like to write `(inc x)' and have the effect of `(setq x (1+ x))'. Here's a macro definition that does the job: (defmacro inc (var) (list 'setq var (list '1+ var))) When this is called with `(inc x)', the argument VAR is the symbol `x'--_not_ the _value_ of `x', as it would be in a function. The body of the macro uses this to construct the expansion, which is `(setq x (1+ x))'. Once the macro definition returns this expansion, Lisp proceeds to evaluate it, thus incrementing `x'.  File: elisp, Node: Expansion, Next: Compiling Macros, Prev: Simple Macro, Up: Macros 13.2 Expansion of a Macro Call ============================== A macro call looks just like a function call in that it is a list which starts with the name of the macro. The rest of the elements of the list are the arguments of the macro. Evaluation of the macro call begins like evaluation of a function call except for one crucial difference: the macro arguments are the actual expressions appearing in the macro call. They are not evaluated before they are given to the macro definition. By contrast, the arguments of a function are results of evaluating the elements of the function call list. Having obtained the arguments, Lisp invokes the macro definition just as a function is invoked. The argument variables of the macro are bound to the argument values from the macro call, or to a list of them in the case of a `&rest' argument. And the macro body executes and returns its value just as a function body does. The second crucial difference between macros and functions is that the value returned by the macro body is not the value of the macro call. Instead, it is an alternate expression for computing that value, also known as the "expansion" of the macro. The Lisp interpreter proceeds to evaluate the expansion as soon as it comes back from the macro. Since the expansion is evaluated in the normal manner, it may contain calls to other macros. It may even be a call to the same macro, though this is unusual. You can see the expansion of a given macro call by calling `macroexpand'. -- Function: macroexpand form &optional environment This function expands FORM, if it is a macro call. If the result is another macro call, it is expanded in turn, until something which is not a macro call results. That is the value returned by `macroexpand'. If FORM is not a macro call to begin with, it is returned as given. Note that `macroexpand' does not look at the subexpressions of FORM (although some macro definitions may do so). Even if they are macro calls themselves, `macroexpand' does not expand them. The function `macroexpand' does not expand calls to inline functions. Normally there is no need for that, since a call to an inline function is no harder to understand than a call to an ordinary function. If ENVIRONMENT is provided, it specifies an alist of macro definitions that shadow the currently defined macros. Byte compilation uses this feature. (defmacro inc (var) (list 'setq var (list '1+ var))) => inc (macroexpand '(inc r)) => (setq r (1+ r)) (defmacro inc2 (var1 var2) (list 'progn (list 'inc var1) (list 'inc var2))) => inc2 (macroexpand '(inc2 r s)) => (progn (inc r) (inc s)) ; `inc' not expanded here. -- Function: macroexpand-all form &optional environment `macroexpand-all' expands macros like `macroexpand', but will look for and expand all macros in FORM, not just at the top-level. If no macros are expanded, the return value is `eq' to FORM. Repeating the example used for `macroexpand' above with `macroexpand-all', we see that `macroexpand-all' _does_ expand the embedded calls to `inc': (macroexpand-all '(inc2 r s)) => (progn (setq r (1+ r)) (setq s (1+ s)))  File: elisp, Node: Compiling Macros, Next: Defining Macros, Prev: Expansion, Up: Macros 13.3 Macros and Byte Compilation ================================ You might ask why we take the trouble to compute an expansion for a macro and then evaluate the expansion. Why not have the macro body produce the desired results directly? The reason has to do with compilation. When a macro call appears in a Lisp program being compiled, the Lisp compiler calls the macro definition just as the interpreter would, and receives an expansion. But instead of evaluating this expansion, it compiles the expansion as if it had appeared directly in the program. As a result, the compiled code produces the value and side effects intended for the macro, but executes at full compiled speed. This would not work if the macro body computed the value and side effects itself--they would be computed at compile time, which is not useful. In order for compilation of macro calls to work, the macros must already be defined in Lisp when the calls to them are compiled. The compiler has a special feature to help you do this: if a file being compiled contains a `defmacro' form, the macro is defined temporarily for the rest of the compilation of that file. Byte-compiling a file also executes any `require' calls at top-level in the file, so you can ensure that necessary macro definitions are available during compilation by requiring the files that define them (*note Named Features::). To avoid loading the macro definition files when someone _runs_ the compiled program, write `eval-when-compile' around the `require' calls (*note Eval During Compile::).  File: elisp, Node: Defining Macros, Next: Backquote, Prev: Compiling Macros, Up: Macros 13.4 Defining Macros ==================== A Lisp macro is a list whose CAR is `macro'. Its CDR should be a function; expansion of the macro works by applying the function (with `apply') to the list of unevaluated argument-expressions from the macro call. It is possible to use an anonymous Lisp macro just like an anonymous function, but this is never done, because it does not make sense to pass an anonymous macro to functionals such as `mapcar'. In practice, all Lisp macros have names, and they are usually defined with the special form `defmacro'. -- Special Form: defmacro name argument-list body-forms... `defmacro' defines the symbol NAME as a macro that looks like this: (macro lambda ARGUMENT-LIST . BODY-FORMS) (Note that the CDR of this list is a function--a lambda expression.) This macro object is stored in the function cell of NAME. The value returned by evaluating the `defmacro' form is NAME, but usually we ignore this value. The shape and meaning of ARGUMENT-LIST is the same as in a function, and the keywords `&rest' and `&optional' may be used (*note Argument List::). Macros may have a documentation string, but any `interactive' declaration is ignored since macros cannot be called interactively. The body of the macro definition can include a `declare' form, which can specify how should indent macro calls, and how to step through them for Edebug. -- Macro: declare SPECS... A `declare' form is used in a macro definition to specify various additional information about it. Two kinds of specification are currently supported: `(debug EDEBUG-FORM-SPEC)' Specify how to step through macro calls for Edebug. *Note Instrumenting Macro Calls::. `(indent INDENT-SPEC)' Specify how to indent calls to this macro. *Note Indenting Macros::, for more details. A `declare' form only has its special effect in the body of a `defmacro' form if it immediately follows the documentation string, if present, or the argument list otherwise. (Strictly speaking, _several_ `declare' forms can follow the documentation string or argument list, but since a `declare' form can have several SPECS, they can always be combined into a single form.) When used at other places in a `defmacro' form, or outside a `defmacro' form, `declare' just returns `nil' without evaluating any SPECS. No macro absolutely needs a `declare' form, because that form has no effect on how the macro expands, on what the macro means in the program. It only affects secondary features: indentation and Edebug.  File: elisp, Node: Backquote, Next: Problems with Macros, Prev: Defining Macros, Up: Macros 13.5 Backquote ============== Macros often need to construct large list structures from a mixture of constants and nonconstant parts. To make this easier, use the ``' syntax (usually called "backquote"). Backquote allows you to quote a list, but selectively evaluate elements of that list. In the simplest case, it is identical to the special form `quote' (*note Quoting::). For example, these two forms yield identical results: `(a list of (+ 2 3) elements) => (a list of (+ 2 3) elements) '(a list of (+ 2 3) elements) => (a list of (+ 2 3) elements) The special marker `,' inside of the argument to backquote indicates a value that isn't constant. Backquote evaluates the argument of `,' and puts the value in the list structure: (list 'a 'list 'of (+ 2 3) 'elements) => (a list of 5 elements) `(a list of ,(+ 2 3) elements) => (a list of 5 elements) Substitution with `,' is allowed at deeper levels of the list structure also. For example: (defmacro t-becomes-nil (variable) `(if (eq ,variable t) (setq ,variable nil))) (t-becomes-nil foo) == (if (eq foo t) (setq foo nil)) You can also "splice" an evaluated value into the resulting list, using the special marker `,@'. The elements of the spliced list become elements at the same level as the other elements of the resulting list. The equivalent code without using ``' is often unreadable. Here are some examples: (setq some-list '(2 3)) => (2 3) (cons 1 (append some-list '(4) some-list)) => (1 2 3 4 2 3) `(1 ,@some-list 4 ,@some-list) => (1 2 3 4 2 3) (setq list '(hack foo bar)) => (hack foo bar) (cons 'use (cons 'the (cons 'words (append (cdr list) '(as elements))))) => (use the words foo bar as elements) `(use the words ,@(cdr list) as elements) => (use the words foo bar as elements)  File: elisp, Node: Problems with Macros, Next: Indenting Macros, Prev: Backquote, Up: Macros 13.6 Common Problems Using Macros ================================= The basic facts of macro expansion have counterintuitive consequences. This section describes some important consequences that can lead to trouble, and rules to follow to avoid trouble. * Menu: * Wrong Time:: Do the work in the expansion, not in the macro. * Argument Evaluation:: The expansion should evaluate each macro arg once. * Surprising Local Vars:: Local variable bindings in the expansion require special care. * Eval During Expansion:: Don't evaluate them; put them in the expansion. * Repeated Expansion:: Avoid depending on how many times expansion is done.  File: elisp, Node: Wrong Time, Next: Argument Evaluation, Up: Problems with Macros 13.6.1 Wrong Time ----------------- The most common problem in writing macros is doing some of the real work prematurely--while expanding the macro, rather than in the expansion itself. For instance, one real package had this macro definition: (defmacro my-set-buffer-multibyte (arg) (if (fboundp 'set-buffer-multibyte) (set-buffer-multibyte arg))) With this erroneous macro definition, the program worked fine when interpreted but failed when compiled. This macro definition called `set-buffer-multibyte' during compilation, which was wrong, and then did nothing when the compiled package was run. The definition that the programmer really wanted was this: (defmacro my-set-buffer-multibyte (arg) (if (fboundp 'set-buffer-multibyte) `(set-buffer-multibyte ,arg))) This macro expands, if appropriate, into a call to `set-buffer-multibyte' that will be executed when the compiled program is actually run.  File: elisp, Node: Argument Evaluation, Next: Surprising Local Vars, Prev: Wrong Time, Up: Problems with Macros 13.6.2 Evaluating Macro Arguments Repeatedly -------------------------------------------- When defining a macro you must pay attention to the number of times the arguments will be evaluated when the expansion is executed. The following macro (used to facilitate iteration) illustrates the problem. This macro allows us to write a simple "for" loop such as one might find in Pascal. (defmacro for (var from init to final do &rest body) "Execute a simple \"for\" loop. For example, (for i from 1 to 10 do (print i))." (list 'let (list (list var init)) (cons 'while (cons (list '<= var final) (append body (list (list 'inc var))))))) => for (for i from 1 to 3 do (setq square (* i i)) (princ (format "\n%d %d" i square))) ==> (let ((i 1)) (while (<= i 3) (setq square (* i i)) (princ (format "\n%d %d" i square)) (inc i))) -|1 1 -|2 4 -|3 9 => nil The arguments `from', `to', and `do' in this macro are "syntactic sugar"; they are entirely ignored. The idea is that you will write noise words (such as `from', `to', and `do') in those positions in the macro call. Here's an equivalent definition simplified through use of backquote: (defmacro for (var from init to final do &rest body) "Execute a simple \"for\" loop. For example, (for i from 1 to 10 do (print i))." `(let ((,var ,init)) (while (<= ,var ,final) ,@body (inc ,var)))) Both forms of this definition (with backquote and without) suffer from the defect that FINAL is evaluated on every iteration. If FINAL is a constant, this is not a problem. If it is a more complex form, say `(long-complex-calculation x)', this can slow down the execution significantly. If FINAL has side effects, executing it more than once is probably incorrect. A well-designed macro definition takes steps to avoid this problem by producing an expansion that evaluates the argument expressions exactly once unless repeated evaluation is part of the intended purpose of the macro. Here is a correct expansion for the `for' macro: (let ((i 1) (max 3)) (while (<= i max) (setq square (* i i)) (princ (format "%d %d" i square)) (inc i))) Here is a macro definition that creates this expansion: (defmacro for (var from init to final do &rest body) "Execute a simple for loop: (for i from 1 to 10 do (print i))." `(let ((,var ,init) (max ,final)) (while (<= ,var max) ,@body (inc ,var)))) Unfortunately, this fix introduces another problem, described in the following section.  File: elisp, Node: Surprising Local Vars, Next: Eval During Expansion, Prev: Argument Evaluation, Up: Problems with Macros 13.6.3 Local Variables in Macro Expansions ------------------------------------------ In the previous section, the definition of `for' was fixed as follows to make the expansion evaluate the macro arguments the proper number of times: (defmacro for (var from init to final do &rest body) "Execute a simple for loop: (for i from 1 to 10 do (print i))." `(let ((,var ,init) (max ,final)) (while (<= ,var max) ,@body (inc ,var)))) The new definition of `for' has a new problem: it introduces a local variable named `max' which the user does not expect. This causes trouble in examples such as the following: (let ((max 0)) (for x from 0 to 10 do (let ((this (frob x))) (if (< max this) (setq max this))))) The references to `max' inside the body of the `for', which are supposed to refer to the user's binding of `max', really access the binding made by `for'. The way to correct this is to use an uninterned symbol instead of `max' (*note Creating Symbols::). The uninterned symbol can be bound and referred to just like any other symbol, but since it is created by `for', we know that it cannot already appear in the user's program. Since it is not interned, there is no way the user can put it into the program later. It will never appear anywhere except where put by `for'. Here is a definition of `for' that works this way: (defmacro for (var from init to final do &rest body) "Execute a simple for loop: (for i from 1 to 10 do (print i))." (let ((tempvar (make-symbol "max"))) `(let ((,var ,init) (,tempvar ,final)) (while (<= ,var ,tempvar) ,@body (inc ,var))))) This creates an uninterned symbol named `max' and puts it in the expansion instead of the usual interned symbol `max' that appears in expressions ordinarily.  File: elisp, Node: Eval During Expansion, Next: Repeated Expansion, Prev: Surprising Local Vars, Up: Problems with Macros 13.6.4 Evaluating Macro Arguments in Expansion ---------------------------------------------- Another problem can happen if the macro definition itself evaluates any of the macro argument expressions, such as by calling `eval' (*note Eval::). If the argument is supposed to refer to the user's variables, you may have trouble if the user happens to use a variable with the same name as one of the macro arguments. Inside the macro body, the macro argument binding is the most local binding of this variable, so any references inside the form being evaluated do refer to it. Here is an example: (defmacro foo (a) (list 'setq (eval a) t)) => foo (setq x 'b) (foo x) ==> (setq b t) => t ; and `b' has been set. ;; but (setq a 'c) (foo a) ==> (setq a t) => t ; but this set `a', not `c'. It makes a difference whether the user's variable is named `a' or `x', because `a' conflicts with the macro argument variable `a'. Another problem with calling `eval' in a macro definition is that it probably won't do what you intend in a compiled program. The byte compiler runs macro definitions while compiling the program, when the program's own computations (which you might have wished to access with `eval') don't occur and its local variable bindings don't exist. To avoid these problems, *don't evaluate an argument expression while computing the macro expansion*. Instead, substitute the expression into the macro expansion, so that its value will be computed as part of executing the expansion. This is how the other examples in this chapter work.  File: elisp, Node: Repeated Expansion, Prev: Eval During Expansion, Up: Problems with Macros 13.6.5 How Many Times is the Macro Expanded? -------------------------------------------- Occasionally problems result from the fact that a macro call is expanded each time it is evaluated in an interpreted function, but is expanded only once (during compilation) for a compiled function. If the macro definition has side effects, they will work differently depending on how many times the macro is expanded. Therefore, you should avoid side effects in computation of the macro expansion, unless you really know what you are doing. One special kind of side effect can't be avoided: constructing Lisp objects. Almost all macro expansions include constructed lists; that is the whole point of most macros. This is usually safe; there is just one case where you must be careful: when the object you construct is part of a quoted constant in the macro expansion. If the macro is expanded just once, in compilation, then the object is constructed just once, during compilation. But in interpreted execution, the macro is expanded each time the macro call runs, and this means a new object is constructed each time. In most clean Lisp code, this difference won't matter. It can matter only if you perform side-effects on the objects constructed by the macro definition. Thus, to avoid trouble, *avoid side effects on objects constructed by macro definitions*. Here is an example of how such side effects can get you into trouble: (defmacro empty-object () (list 'quote (cons nil nil))) (defun initialize (condition) (let ((object (empty-object))) (if condition (setcar object condition)) object)) If `initialize' is interpreted, a new list `(nil)' is constructed each time `initialize' is called. Thus, no side effect survives between calls. If `initialize' is compiled, then the macro `empty-object' is expanded during compilation, producing a single "constant" `(nil)' that is reused and altered each time `initialize' is called. One way to avoid pathological cases like this is to think of `empty-object' as a funny kind of constant, not as a memory allocation construct. You wouldn't use `setcar' on a constant such as `'(nil)', so naturally you won't use it on `(empty-object)' either.  File: elisp, Node: Indenting Macros, Prev: Problems with Macros, Up: Macros 13.7 Indenting Macros ===================== You can use the `declare' form in the macro definition to specify how to should indent calls to the macro. You write it like this: (declare (indent INDENT-SPEC)) Here are the possibilities for INDENT-SPEC: `nil' This is the same as no property--use the standard indentation pattern. `defun' Handle this function like a `def' construct: treat the second line as the start of a "body". an integer, NUMBER The first NUMBER arguments of the function are "distinguished" arguments; the rest are considered the body of the expression. A line in the expression is indented according to whether the first argument on it is distinguished or not. If the argument is part of the body, the line is indented `lisp-body-indent' more columns than the open-parenthesis starting the containing expression. If the argument is distinguished and is either the first or second argument, it is indented _twice_ that many extra columns. If the argument is distinguished and not the first or second argument, the line uses the standard pattern. a symbol, SYMBOL SYMBOL should be a function name; that function is called to calculate the indentation of a line within this expression. The function receives two arguments: STATE The value returned by `parse-partial-sexp' (a Lisp primitive for indentation and nesting computation) when it parses up to the beginning of this line. POS The position at which the line being indented begins. It should return either a number, which is the number of columns of indentation for that line, or a list whose car is such a number. The difference between returning a number and returning a list is that a number says that all following lines at the same nesting level should be indented just like this one; a list says that following lines might call for different indentations. This makes a difference when the indentation is being computed by `C-M-q'; if the value is a number, `C-M-q' need not recalculate indentation for the following lines until the end of the list.  File: elisp, Node: Customization, Next: Loading, Prev: Macros, Up: Top 14 Writing Customization Definitions ************************************ This chapter describes how to declare user options for customization, and also customization groups for classifying them. We use the term "customization item" to include both kinds of customization definitions--as well as face definitions (*note Defining Faces::). * Menu: * Common Keywords:: Common keyword arguments for all kinds of customization declarations. * Group Definitions:: Writing customization group definitions. * Variable Definitions:: Declaring user options. * Customization Types:: Specifying the type of a user option.  File: elisp, Node: Common Keywords, Next: Group Definitions, Up: Customization 14.1 Common Item Keywords ========================= All kinds of customization declarations (for variables and groups, and for faces) accept keyword arguments for specifying various information. This section describes some keywords that apply to all kinds. All of these keywords, except `:tag', can be used more than once in a given item. Each use of the keyword has an independent effect. The keyword `:tag' is an exception because any given item can only display one name. `:tag LABEL' Use LABEL, a string, instead of the item's name, to label the item in customization menus and buffers. *Don't use a tag which is substantially different from the item's real name; that would cause confusion.* `:group GROUP' Put this customization item in group GROUP. When you use `:group' in a `defgroup', it makes the new group a subgroup of GROUP. If you use this keyword more than once, you can put a single item into more than one group. Displaying any of those groups will show this item. Please don't overdo this, since the result would be annoying. `:link LINK-DATA' Include an external link after the documentation string for this item. This is a sentence containing an active field which references some other documentation. There are several alternatives you can use for LINK-DATA: `(custom-manual INFO-NODE)' Link to an Info node; INFO-NODE is a string which specifies the node name, as in `"(emacs)Top"'. The link appears as `[Manual]' in the customization buffer and enters the built-in Info reader on INFO-NODE. `(info-link INFO-NODE)' Like `custom-manual' except that the link appears in the customization buffer with the Info node name. `(url-link URL)' Link to a web page; URL is a string which specifies the URL. The link appears in the customization buffer as URL and invokes the WWW browser specified by `browse-url-browser-function'. `(emacs-commentary-link LIBRARY)' Link to the commentary section of a library; LIBRARY is a string which specifies the library name. `(emacs-library-link LIBRARY)' Link to an Emacs Lisp library file; LIBRARY is a string which specifies the library name. `(file-link FILE)' Link to a file; FILE is a string which specifies the name of the file to visit with `find-file' when the user invokes this link. `(function-link FUNCTION)' Link to the documentation of a function; FUNCTION is a string which specifies the name of the function to describe with `describe-function' when the user invokes this link. `(variable-link VARIABLE)' Link to the documentation of a variable; VARIABLE is a string which specifies the name of the variable to describe with `describe-variable' when the user invokes this link. `(custom-group-link GROUP)' Link to another customization group. Invoking it creates a new customization buffer for GROUP. You can specify the text to use in the customization buffer by adding `:tag NAME' after the first element of the LINK-DATA; for example, `(info-link :tag "foo" "(emacs)Top")' makes a link to the Emacs manual which appears in the buffer as `foo'. An item can have more than one external link; however, most items have none at all. `:load FILE' Load file FILE (a string) before displaying this customization item (*note Loading::). Loading is done with `load', and only if the file is not already loaded. `:require FEATURE' Execute `(require 'FEATURE)' when your saved customizations set the value of this item. FEATURE should be a symbol. The most common reason to use `:require' is when a variable enables a feature such as a minor mode, and just setting the variable won't have any effect unless the code which implements the mode is loaded. `:version VERSION' This keyword specifies that the item was first introduced in Emacs version VERSION, or that its default value was changed in that version. The value VERSION must be a string. `:package-version '(PACKAGE . VERSION)' This keyword specifies that the item was first introduced in PACKAGE version VERSION, or that its meaning or default value was changed in that version. The value of PACKAGE is a symbol and VERSION is a string. This keyword takes priority over `:version'. PACKAGE should be the official name of the package, such as MH-E or Gnus. If the package PACKAGE is released as part of Emacs, PACKAGE and VERSION should appear in the value of `customize-package-emacs-version-alist'. Packages distributed as part of Emacs that use the `:package-version' keyword must also update the `customize-package-emacs-version-alist' variable. -- Variable: customize-package-emacs-version-alist This alist provides a mapping for the versions of Emacs that are associated with versions of a package listed in the `:package-version' keyword. Its elements look like this: (PACKAGE (PVERSION . EVERSION)...) For each PACKAGE, which is a symbol, there are one or more elements that contain a package version PVERSION with an associated Emacs version EVERSION. These versions are strings. For example, the MH-E package updates this alist with the following: (add-to-list 'customize-package-emacs-version-alist '(MH-E ("6.0" . "22.1") ("6.1" . "22.1") ("7.0" . "22.1") ("7.1" . "22.1") ("7.2" . "22.1") ("7.3" . "22.1") ("7.4" . "22.1") ("8.0" . "22.1"))) The value of PACKAGE needs to be unique and it needs to match the PACKAGE value appearing in the `:package-version' keyword. Since the user might see the value in a error message, a good choice is the official name of the package, such as MH-E or Gnus.  File: elisp, Node: Group Definitions, Next: Variable Definitions, Prev: Common Keywords, Up: Customization 14.2 Defining Customization Groups ================================== Each Emacs Lisp package should have one main customization group which contains all the options, faces and other groups in the package. If the package has a small number of options and faces, use just one group and put everything in it. When there are more than twelve or so options and faces, then you should structure them into subgroups, and put the subgroups under the package's main customization group. It is OK to put some of the options and faces in the package's main group alongside the subgroups. The package's main or only group should be a member of one or more of the standard customization groups. (To display the full list of them, use `M-x customize'.) Choose one or more of them (but not too many), and add your group to each of them using the `:group' keyword. The way to declare new customization groups is with `defgroup'. -- Macro: defgroup group members doc [keyword value]... Declare GROUP as a customization group containing MEMBERS. Do not quote the symbol GROUP. The argument DOC specifies the documentation string for the group. The argument MEMBERS is a list specifying an initial set of customization items to be members of the group. However, most often MEMBERS is `nil', and you specify the group's members by using the `:group' keyword when defining those members. If you want to specify group members through MEMBERS, each element should have the form `(NAME WIDGET)'. Here NAME is a symbol, and WIDGET is a widget type for editing that symbol. Useful widgets are `custom-variable' for a variable, `custom-face' for a face, and `custom-group' for a group. When you introduce a new group into Emacs, use the `:version' keyword in the `defgroup'; then you need not use it for the individual members of the group. In addition to the common keywords (*note Common Keywords::), you can also use this keyword in `defgroup': `:prefix PREFIX' If the name of an item in the group starts with PREFIX, then the tag for that item is constructed (by default) by omitting PREFIX. One group can have any number of prefixes. The prefix-discarding feature is currently turned off, which means that `:prefix' currently has no effect. We did this because we found that discarding the specified prefixes often led to confusing names for options. This happened because the people who wrote the `defgroup' definitions for various groups added `:prefix' keywords whenever they make logical sense--that is, whenever the variables in the library have a common prefix. In order to obtain good results with `:prefix', it would be necessary to check the specific effects of discarding a particular prefix, given the specific items in a group and their names and documentation. If the resulting text is not clear, then `:prefix' should not be used in that case. It should be possible to recheck all the customization groups, delete the `:prefix' specifications which give unclear results, and then turn this feature back on, if someone would like to do the work.  File: elisp, Node: Variable Definitions, Next: Customization Types, Prev: Group Definitions, Up: Customization 14.3 Defining Customization Variables ===================================== Use `defcustom' to declare user-customizable variables. -- Macro: defcustom option standard doc [keyword value]... This macro declares OPTION as a customizable "user option". You should not quote OPTION. This causes the function `user-variable-p' to return `t' when given OPTION as an argument. *Note Defining Variables::. The argument DOC specifies the documentation string for the variable. (Note that there is no need to start DOC with a `*'.) The argument STANDARD is an expression that specifies the standard value for OPTION. Evaluating the `defcustom' form evaluates STANDARD, but does not necessarily install the standard value. If OPTION already has a default value, `defcustom' does not change it. If the user has saved a customization for OPTION, `defcustom' installs the user's customized value as OPTION's default value. If neither of those cases applies, `defcustom' installs the result of evaluating STANDARD as the default value. The expression STANDARD can be evaluated at various other times, too--whenever the customization facility needs to know OPTION's standard value. So be sure to use an expression which is harmless to evaluate at any time. We recommend avoiding backquotes in STANDARD, because they are not expanded when editing the value, so list values will appear to have the wrong structure. Every `defcustom' should specify `:group' at least once. If you specify the `:set' keyword, to make the variable take other special actions when set through the customization buffer, the variable's documentation string should tell the user specifically how to do the same job in hand-written Lisp code. When you evaluate a `defcustom' form with `C-M-x' in Emacs Lisp mode (`eval-defun'), a special feature of `eval-defun' arranges to set the variable unconditionally, without testing whether its value is void. (The same feature applies to `defvar'.) *Note Defining Variables::. If you put a `defcustom' in a file that is preloaded at dump time (*note Building Emacs::), and the standard value installed for the variable at that time might not be correct, use `custom-reevaluate-setting', described below, to re-evaluate the standard value during or after Emacs startup. `defcustom' accepts the following additional keywords: `:type TYPE' Use TYPE as the data type for this option. It specifies which values are legitimate, and how to display the value. *Note Customization Types::, for more information. `:options VALUE-LIST' Specify the list of reasonable values for use in this option. The user is not restricted to using only these values, but they are offered as convenient alternatives. This is meaningful only for certain types, currently including `hook', `plist' and `alist'. See the definition of the individual types for a description of how to use `:options'. `:set SETFUNCTION' Specify SETFUNCTION as the way to change the value of this option. The function SETFUNCTION should take two arguments, a symbol (the option name) and the new value, and should do whatever is necessary to update the value properly for this option (which may not mean simply setting the option as a Lisp variable). The default for SETFUNCTION is `set-default'. `:get GETFUNCTION' Specify GETFUNCTION as the way to extract the value of this option. The function GETFUNCTION should take one argument, a symbol, and should return whatever customize should use as the "current value" for that symbol (which need not be the symbol's Lisp value). The default is `default-value'. You have to really understand the workings of Custom to use `:get' correctly. It is meant for values that are treated in Custom as variables but are not actually stored in Lisp variables. It is almost surely a mistake to specify `getfunction' for a value that really is stored in a Lisp variable. `:initialize FUNCTION' FUNCTION should be a function used to initialize the variable when the `defcustom' is evaluated. It should take two arguments, the option name (a symbol) and the value. Here are some predefined functions meant for use in this way: `custom-initialize-set' Use the variable's `:set' function to initialize the variable, but do not reinitialize it if it is already non-void. `custom-initialize-default' Like `custom-initialize-set', but use the function `set-default' to set the variable, instead of the variable's `:set' function. This is the usual choice for a variable whose `:set' function enables or disables a minor mode; with this choice, defining the variable will not call the minor mode function, but customizing the variable will do so. `custom-initialize-reset' Always use the `:set' function to initialize the variable. If the variable is already non-void, reset it by calling the `:set' function using the current value (returned by the `:get' method). This is the default `:initialize' function. `custom-initialize-changed' Use the `:set' function to initialize the variable, if it is already set or has been customized; otherwise, just use `set-default'. `custom-initialize-safe-set' `custom-initialize-safe-default' These functions behave like `custom-initialize-set' (`custom-initialize-default', respectively), but catch errors. If an error occurs during initialization, they set the variable to `nil' using `set-default', and throw no error. These two functions are only meant for options defined in pre-loaded files, where some variables or functions used to compute the option's value may not yet be defined. The option normally gets updated in `startup.el', ignoring the previously computed value. Because of this typical usage, the value which these two functions compute normally only matters when, after startup, one unsets the option's value and then reevaluates the defcustom. By that time, the necessary variables and functions will be defined, so there will not be an error. `:risky VALUE' Set the variable's `risky-local-variable' property to VALUE (*note File Local Variables::). `:safe FUNCTION' Set the variable's `safe-local-variable' property to FUNCTION (*note File Local Variables::). `:set-after VARIABLES' When setting variables according to saved customizations, make sure to set the variables VARIABLES before this one; in other words, delay setting this variable until after those others have been handled. Use `:set-after' if setting this variable won't work properly unless those other variables already have their intended values. It is useful to specify the `:require' keyword for an option that "turns on" a certain feature. This causes Emacs to load the feature, if it is not already loaded, whenever the option is set. *Note Common Keywords::. Here is an example, from the library `saveplace.el': (defcustom save-place nil "Non-nil means automatically save place in each file..." :type 'boolean :require 'saveplace :group 'save-place) If a customization item has a type such as `hook' or `alist', which supports `:options', you can add additional values to the list from outside the `defcustom' declaration by calling `custom-add-frequent-value'. For example, if you define a function `my-lisp-mode-initialization' intended to be called from `emacs-lisp-mode-hook', you might want to add that to the list of reasonable values for `emacs-lisp-mode-hook', but not by editing its definition. You can do it thus: (custom-add-frequent-value 'emacs-lisp-mode-hook 'my-lisp-mode-initialization) -- Function: custom-add-frequent-value symbol value For the customization option SYMBOL, add VALUE to the list of reasonable values. The precise effect of adding a value depends on the customization type of SYMBOL. Internally, `defcustom' uses the symbol property `standard-value' to record the expression for the standard value, `saved-value' to record the value saved by the user with the customization buffer, and `customized-value' to record the value set by the user with the customization buffer, but not saved. *Note Property Lists::. These properties are lists, the car of which is an expression that evaluates to the value. -- Function: custom-reevaluate-setting symbol This function re-evaluates the standard value of SYMBOL, which should be a user option declared via `defcustom'. (If the variable was customized, this function re-evaluates the saved value instead.) This is useful for customizable options that are defined before their value could be computed correctly, such as variables defined in packages that are loaded at dump time, but depend on the run-time information. For example, the value could be a file whose precise name depends on the hierarchy of files when Emacs runs, or a name of a program that needs to be searched at run time. A good place to put calls to this function is in the function `command-line' that is run during startup (*note Startup Summary::) or in the various hooks it calls.  File: elisp, Node: Customization Types, Prev: Variable Definitions, Up: Customization 14.4 Customization Types ======================== When you define a user option with `defcustom', you must specify its "customization type". That is a Lisp object which describes (1) which values are legitimate and (2) how to display the value in the customization buffer for editing. You specify the customization type in `defcustom' with the `:type' keyword. The argument of `:type' is evaluated, but only once when the `defcustom' is executed, so it isn't useful for the value to vary. Normally we use a quoted constant. For example: (defcustom diff-command "diff" "The command to use to run diff." :type '(string) :group 'diff) In general, a customization type is a list whose first element is a symbol, one of the customization type names defined in the following sections. After this symbol come a number of arguments, depending on the symbol. Between the type symbol and its arguments, you can optionally write keyword-value pairs (*note Type Keywords::). Some type symbols do not use any arguments; those are called "simple types". For a simple type, if you do not use any keyword-value pairs, you can omit the parentheses around the type symbol. For example just `string' as a customization type is equivalent to `(string)'. All customization types are implemented as widgets; see *note Introduction: (widget)Top, for details. * Menu: * Simple Types:: Simple customization types: sexp, integer, number, string, file, directory, alist. * Composite Types:: Build new types from other types or data. * Splicing into Lists:: Splice elements into list with `:inline'. * Type Keywords:: Keyword-argument pairs in a customization type. * Defining New Types:: Give your type a name.