A variable is a name used in a program to stand for a value. Nearly all programming languages have variables of some sort. In the text of a Lisp program, variables are written using the syntax for symbols.
In Lisp, unlike most programming languages, programs are represented primarily as Lisp objects and only secondarily as text. The Lisp objects used for variables are symbols: the symbol name is the variable name, and the variable's value is stored in the value cell of the symbol. The use of a symbol as a variable is independent of its use as a function name. See section Symbol Components.
The Lisp objects that constitute a Lisp program determine the textual form of the program--it is simply the read syntax for those Lisp objects. This is why, for example, a variable in a textual Lisp program is written using the read syntax for the symbol that represents the variable.
The simplest way to use a variable is globally. This means that the variable has just one value at a time, and this value is in effect (at least for the moment) throughout the Lisp system. The value remains in effect until you specify a new one. When a new value replaces the old one, no trace of the old value remains in the variable.
You specify a value for a symbol with setq
. For example,
(setq x '(a b))
gives the variable x
the value (a b)
. Note that
setq
does not evaluate its first argument, the name of the
variable, but it does evaluate the second argument, the new value.
Once the variable has a value, you can refer to it by using the symbol by itself as an expression. Thus,
x => (a b)
assuming the setq
form shown above has already been executed.
If you do another setq
, the new value replaces the old one:
x => (a b) (setq x 4) => 4 x => 4
Emacs Lisp has two special symbols, nil
and t
, that
always evaluate to themselves. These symbols cannot be rebound, nor can
their value cells be changed. An attempt to change the value of
nil
or t
signals a setting-constant
error.
nil == 'nil => nil (setq nil 500) error--> Attempt to set constant symbol: nil
Global variables have values that last until explicitly superseded with new values. Sometimes it is useful to create variable values that exist temporarily--only while within a certain part of the program. These values are called local, and the variables so used are called local variables.
For example, when a function is called, its argument variables receive
new local values that last until the function exits. The let
special form explicitly establishes new local values for specified
variables; these last until exit from the let
form.
Establishing a local value saves away the previous value (or lack of one) of the variable. When the life span of the local value is over, the previous value is restored. In the mean time, we say that the previous value is shadowed and not visible. Both global and local values may be shadowed (see section Scope).
If you set a variable (such as with setq
) while it is local,
this replaces the local value; it does not alter the global value, or
previous local values that are shadowed. To model this behavior, we
speak of a local binding of the variable as well as a local value.
The local binding is a conceptual place that holds a local value.
Entry to a function, or a special form such as let
, creates the
local binding; exit from the function or from the let
removes the
local binding. As long as the local binding lasts, the variable's value
is stored within it. Use of setq
or set
while there is a
local binding stores a different value into the local binding; it does
not create a new binding.
We also speak of the global binding, which is where (conceptually) the global value is kept.
A variable can have more than one local binding at a time (for
example, if there are nested let
forms that bind it). In such a
case, the most recently created local binding that still exists is the
current binding of the variable. (This is called dynamic
scoping; see section Scoping Rules for Variable Bindings.) If there are no local bindings,
the variable's global binding is its current binding. We also 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.
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 any of the symbols are bound. Here
is an example of this: Z
is bound to the old value of Y
,
which is 2, not the new value, 1.
(setq Y 2) => 2 (let ((Y 1) (Z Y)) (list Y Z)) => (1 2)
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:
condition-case
(see section Errors).
unwind-protect
cleanups (see section Nonlocal Exits)
that are allowed before signaling an error (with data "Variable
binding depth exceeds max-specpdl-size"
).
This limit, with the associated error when it is exceeded, is one way that Lisp avoids infinite recursion on an ill-defined function.
The default value is 600.
max-lisp-eval-depth
provides another limit on depth of nesting.
See section Eval.
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
.
void-variable
, unless or 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 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.
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
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 programs
will change the variable. 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.
One would expect user option variables to be defined with
defconst
, since programs do not change them. Unfortunately, this
has bad results if the definition is in a library that is not preloaded:
defconst
would override any prior value when the library is
loaded. Users would like to be able to set user options in their init
files, and override the default values given in the definitions. For
this reason, user options must be defined with defvar
.
defvar
.
If symbol already has a value (i.e., it is not void), value
is not even evaluated, and symbol's value remains unchanged. If
symbol is void and value is specified, defvar
evaluates it and sets symbol to the result. (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
sets the default value, not the local value.
See section Buffer-Local Variables.
If the doc-string argument appears, it specifies the documentation
for the variable. (This opportunity to specify documentation is one of
the main benefits of defining the variable.) The documentation is
stored in the symbol's variable-documentation
property. The
Emacs help functions (see section Documentation) look for this property.
If the first character of doc-string is `*', it means that
this variable is considered a user option. This lets users set the
variable conventiently using the commands set-variable
and
edit-options
.
For example, this form defines foo
but does not set its value:
(defvar foo) => foo
The following example sets 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+ 23)
is not even
performed.)
(defvar bar (1+ 23) "*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)) (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.
defconst
.
defconst
always evaluates value and sets the global value
of symbol to the result, provided value is given. If
symbol has a buffer-local binding in the current buffer,
defconst
sets the default value, not the local value.
Please note: don't use defconst
for user option
variables in libraries that are not standardly preloaded. The user
should be able to specify a value for such a variable in the
`.emacs' file, so that it will be in effect if and when the library
is loaded later.
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
t
if variable is a user option--a
variable intended to be set by the user for customization--and
nil
otherwise. (Variables other than user options exist for the
internal purposes of Lisp programs, and users need not know about them.)
User option variables are distinguished from other variables by the
first character of the variable-documentation
property. If the
property exists and is a string, and its first character is `*',
then the variable is a user option.
If a user option variable has a variable-interactive
property,
set-variable
uses that value to control reading the new value for
the variable. The property's value is used as if it were the argument
to interactive
.
Warning: if the defconst
and defvar
special
forms are used while the variable has a local binding, they set the
local binding's value; the global binding is not changed. This is not
what we really want. To prevent it, use these special forms at top
level in a file, where normally no local binding is in effect, and make
sure to load the file before making a local binding for the variable.
The usual way to reference a variable is to write the symbol which
names it (see section Symbol Forms). This requires you to specify the
variable name when you write the program. Usually that is exactly what
you want to do. Occasionally you need to choose at run time which
variable to reference; then you can use symbol-value
.
(setq abracadabra 5) => 5 (setq foo 9) => 9 ;; Here the symbolabracadabra
;; is the symbol whose value is examined. (let ((abracadabra 'foo)) (symbol-value 'abracadabra)) => foo ;; Here the value ofabracadabra
, ;; which isfoo
, ;; 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 symbol has neither a
local binding nor a global 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
.
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 ofx
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 thatx
is set before y (1+ x)) ; the value ofy
is computed. => 11
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 symbolone
. => 2 one ; So it isone
that was set. => 2 (let ((one 1)) ; This binding ofone
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 value, ignoring any lexical bindings. In Emacs Lisp, all variables and all bindings are (in effect) special, soset
always affects the most local existing binding.
A given symbol foo
may 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 variables in Emacs Lisp.
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 inbinder
. (foo 5)) ;foo
is some other function. (defun user () ;x
is used inuser
. (list x))
In a lexically scoped language, the binding of x
in
binder
would never be accessible in user
, because
user
is not textually contained within the function
binder
. However, in dynamically scoped Emacs Lisp, user
may or may not refer to the binding of x
established in
binder
, depending on circumstances:
user
directly without calling binder
at all,
then whatever binding of x
is found, it cannot come from
binder
.
foo
as follows and call binder
, then the
binding made in binder
will be seen in user
:
(defun foo (lose) (user))
foo
as follows and 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
.
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 work as intended 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 functionadd2
; 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.
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: variable-value pairs. At entry
to a function or to a let
form, we can push bindings on 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) on a stack, and storing the 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.
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:
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.
Global and local variable bindings are found in most programming languages in one form or another. Emacs also supports another, unusual kind of variable binding: buffer-local bindings, which apply only to one buffer. Emacs Lisp is meant for programming editing commands, and having different values for a variable in different buffers is an important customization method.
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 the global binding is unchanged; this means that the change is visible in that buffer alone.
A variable may have buffer-local bindings in some buffers but not in
others. The global binding is shared by all the buffers that don't have
their own bindings. Thus, if you set the variable in a buffer that does
not have a buffer-local binding for it, the new value is visible in all
buffers except those with buffer-local bindings. (Here we are assuming
that there are no let
-style local bindings to complicate the issue.)
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.
The usual way to make a buffer-local binding is with
make-local-variable
, which is what major mode commands use. This
affects just the current buffer; all other buffers (including those yet to
be created) continue to share the global value.
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 global value of the variable as usual,
but any setq
creates a buffer-local binding for the current
buffer. The new value is stored in the buffer-local binding, leaving
the (default) global binding untouched. The global value can no longer
be changed with setq
; you need to use setq-default
to do
that.
Warning: when a variable has local values in one or more
buffers, you can get Emacs very confused by binding the variable with
let
, changing to a different current buffer in which a different
binding is in effect, and then exiting the let
. This can
scramble the values of the global and local bindings.
To preserve your sanity, avoid that series of actions. If you use
save-excursion
around each piece of code that changes to a
different current buffer, you will not have this problem. Here is an
example of what to avoid:
(setq foo 'b) (set-buffer "a") (make-local-variable 'foo) (setq foo 'a) (let ((foo 'temp)) (set-buffer "b") ...) foo => 'a ; The old buffer-local value from buffer `a' ; is now the default value. (set-buffer "a") foo => 'temp ; The local value that should be gone ; is now the buffer-local value in buffer `a'.
But save-excursion
as shown here avoids the problem:
(let ((foo 'temp)) (save-excursion (set-buffer "b") body...))
Note that references to foo
in body access the
buffer-local binding of buffer `b'.
When a file specifies local variable values, these become buffer-local values when you visit the file. See section How Emacs Chooses a Major Mode.
The buffer-local value of variable starts out as the same value variable previously had. If variable was void, it remains void.
;; In buffer `b1': (setq foo 5) ; Affects all buffers. => 5 (make-local-variable 'foo) ; Now it is local in `b1'. => foo foo ; That did not change => 5 ; the value. (setq foo 6) ; Change the value => 6 ; in `b1'. foo => 6 ;; In buffer `b2', the value hasn't changed. (save-excursion (set-buffer "b2") foo) => 5
The value returned is variable.
(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 local variables. ;; This one is local and void: foobar ;; This one is local and nonvoid: (bind-me . 69))
Note that storing new values into the CDRs of cons cells in this list does not change the local values of the variables.
If you kill the local binding of a variable that automatically becomes local when set, this makes the global value visible in the current buffer. However, if you set the variable again, that will once again create a 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.
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
, and the abbrev table to the value
of fundamental-mode-abbrev-table
.
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
.
A local variable is permanent if the variable name (a symbol) has a
permanent-local
property that is non-nil
. Permanent
locals are appropriate for data pertaining to where the file came from
or how to save it, rather than with how to edit the contents.
The global value of a variable with buffer-local bindings is also called the default value, because it is the value that is in effect except when specifically overridden.
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 local
value.
symbol-value
(see section Accessing Variable Values).
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
.
setq-default
form is value.
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 'local) => local (setq local 'value-in-foo) => value-in-foo (setq-default local 'new-default) => new-default local => value-in-foo (default-value 'local) => new-default ;; In (the new) buffer `bar': local => new-default (default-value 'local) => new-default (setq local 'another-default) => another-default (default-value 'local) => another-default ;; Back in buffer `foo': local => value-in-foo (default-value 'local) => another-default
setq-default
, except that symbol is
evaluated.
(set-default (car '(a b c)) 23) => 23 (default-value 'a) => 23