2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1998 Free Software Foundation, Inc.
4 @c See the file elisp.texi for copying conditions.
5 @setfilename ../info/variables
6 @node Variables, Functions, Control Structures, Top
10 A @dfn{variable} is a name used in a program to stand for a value.
11 Nearly all programming languages have variables of some sort. In the
12 text of a Lisp program, variables are written using the syntax for
15 In Lisp, unlike most programming languages, programs are represented
16 primarily as Lisp objects and only secondarily as text. The Lisp
17 objects used for variables are symbols: the symbol name is the variable
18 name, and the variable's value is stored in the value cell of the
19 symbol. The use of a symbol as a variable is independent of its use as
20 a function name. @xref{Symbol Components}.
22 The Lisp objects that constitute a Lisp program determine the textual
23 form of the program---it is simply the read syntax for those Lisp
24 objects. This is why, for example, a variable in a textual Lisp program
25 is written using the read syntax for the symbol that represents the
29 * Global Variables:: Variable values that exist permanently, everywhere.
30 * Constant Variables:: Certain "variables" have values that never change.
31 * Local Variables:: Variable values that exist only temporarily.
32 * Void Variables:: Symbols that lack values.
33 * Defining Variables:: A definition says a symbol is used as a variable.
34 * Tips for Defining:: How to avoid bad results from quitting
35 within the code to initialize a variable.
36 * Accessing Variables:: Examining values of variables whose names
37 are known only at run time.
38 * Setting Variables:: Storing new values in variables.
39 * Variable Scoping:: How Lisp chooses among local and global values.
40 * Buffer-Local Variables:: Variable values in effect only in one buffer.
41 * Frame-Local Variables:: Variable values in effect only in one frame.
42 * Future Local Variables:: New kinds of local values we might add some day.
45 @node Global Variables
46 @section Global Variables
47 @cindex global variable
49 The simplest way to use a variable is @dfn{globally}. This means that
50 the variable has just one value at a time, and this value is in effect
51 (at least for the moment) throughout the Lisp system. The value remains
52 in effect until you specify a new one. When a new value replaces the
53 old one, no trace of the old value remains in the variable.
55 You specify a value for a symbol with @code{setq}. For example,
62 gives the variable @code{x} the value @code{(a b)}. Note that
63 @code{setq} does not evaluate its first argument, the name of the
64 variable, but it does evaluate the second argument, the new value.
66 Once the variable has a value, you can refer to it by using the symbol
67 by itself as an expression. Thus,
76 assuming the @code{setq} form shown above has already been executed.
78 If you do set the same variable again, the new value replaces the old
96 @node Constant Variables
97 @section Variables that Never Change
100 @kindex setting-constant
102 In Emacs Lisp, certain symbols normally evaluate to themselves. These
103 include @code{nil} and @code{t}, as well as any symbol whose name starts
104 with @samp{:}. These symbols cannot be rebound, nor can their values be
105 changed. Any attempt to set or bind @code{nil} or @code{t} signals a
106 @code{setting-constant} error. The same is true for a symbol whose name
107 starts with @samp{:} (if it is interned in the standard obarray), except
108 that you are allowed to set such a symbol to itself.
117 @error{} Attempt to set constant symbol: nil
121 @defvar keyword-symbols-constant-flag
122 @tindex keyword-symbols-constant-flag
123 If this variable is @code{nil}, you are allowed to set and bind symbols
124 whose names start with @samp{:} as you wish. This is to make it
125 possible to run old Lisp programs which do that.
128 @node Local Variables
129 @section Local Variables
130 @cindex binding local variables
131 @cindex local variables
132 @cindex local binding
133 @cindex global binding
135 Global variables have values that last until explicitly superseded
136 with new values. Sometimes it is useful to create variable values that
137 exist temporarily---only until a certain part of the program finishes.
138 These values are called @dfn{local}, and the variables so used are
139 called @dfn{local variables}.
141 For example, when a function is called, its argument variables receive
142 new local values that last until the function exits. The @code{let}
143 special form explicitly establishes new local values for specified
144 variables; these last until exit from the @code{let} form.
146 @cindex shadowing of variables
147 Establishing a local value saves away the previous value (or lack of
148 one) of the variable. When the life span of the local value is over,
149 the previous value is restored. In the mean time, we say that the
150 previous value is @dfn{shadowed} and @dfn{not visible}. Both global and
151 local values may be shadowed (@pxref{Scope}).
153 If you set a variable (such as with @code{setq}) while it is local,
154 this replaces the local value; it does not alter the global value, or
155 previous local values, that are shadowed. To model this behavior, we
156 speak of a @dfn{local binding} of the variable as well as a local value.
158 The local binding is a conceptual place that holds a local value.
159 Entry to a function, or a special form such as @code{let}, creates the
160 local binding; exit from the function or from the @code{let} removes the
161 local binding. As long as the local binding lasts, the variable's value
162 is stored within it. Use of @code{setq} or @code{set} while there is a
163 local binding stores a different value into the local binding; it does
164 not create a new binding.
166 We also speak of the @dfn{global binding}, which is where
167 (conceptually) the global value is kept.
169 @cindex current binding
170 A variable can have more than one local binding at a time (for
171 example, if there are nested @code{let} forms that bind it). In such a
172 case, the most recently created local binding that still exists is the
173 @dfn{current binding} of the variable. (This rule is called
174 @dfn{dynamic scoping}; see @ref{Variable Scoping}.) If there are no
175 local bindings, the variable's global binding is its current binding.
176 We sometimes call the current binding the @dfn{most-local existing
177 binding}, for emphasis. Ordinary evaluation of a symbol always returns
178 the value of its current binding.
180 The special forms @code{let} and @code{let*} exist to create
183 @defspec let (bindings@dots{}) forms@dots{}
184 This special form binds variables according to @var{bindings} and then
185 evaluates all of the @var{forms} in textual order. The @code{let}-form
186 returns the value of the last form in @var{forms}.
188 Each of the @var{bindings} is either @w{(i) a} symbol, in which case
189 that symbol is bound to @code{nil}; or @w{(ii) a} list of the form
190 @code{(@var{symbol} @var{value-form})}, in which case @var{symbol} is
191 bound to the result of evaluating @var{value-form}. If @var{value-form}
192 is omitted, @code{nil} is used.
194 All of the @var{value-form}s in @var{bindings} are evaluated in the
195 order they appear and @emph{before} binding any of the symbols to them.
196 Here is an example of this: @code{Z} is bound to the old value of
197 @code{Y}, which is 2, not the new value of @code{Y}, which is 1.
213 @defspec let* (bindings@dots{}) forms@dots{}
214 This special form is like @code{let}, but it binds each variable right
215 after computing its local value, before computing the local value for
216 the next variable. Therefore, an expression in @var{bindings} can
217 reasonably refer to the preceding symbols bound in this @code{let*}
218 form. Compare the following example with the example above for
228 (Z Y)) ; @r{Use the just-established value of @code{Y}.}
235 Here is a complete list of the other facilities that create local
240 Function calls (@pxref{Functions}).
243 Macro calls (@pxref{Macros}).
246 @code{condition-case} (@pxref{Errors}).
249 Variables can also have buffer-local bindings (@pxref{Buffer-Local
250 Variables}) and frame-local bindings (@pxref{Frame-Local Variables}); a
251 few variables have terminal-local bindings (@pxref{Multiple Displays}).
252 These kinds of bindings work somewhat like ordinary local bindings, but
253 they are localized depending on ``where'' you are in Emacs, rather than
256 @defvar max-specpdl-size
257 @cindex variable limit error
258 @cindex evaluation error
259 @cindex infinite recursion
260 This variable defines the limit on the total number of local variable
261 bindings and @code{unwind-protect} cleanups (@pxref{Nonlocal Exits})
262 that are allowed before signaling an error (with data @code{"Variable
263 binding depth exceeds max-specpdl-size"}).
265 This limit, with the associated error when it is exceeded, is one way
266 that Lisp avoids infinite recursion on an ill-defined function.
267 @code{max-lisp-eval-depth} provides another limit on depth of nesting.
270 The default value is 600. Entry to the Lisp debugger increases the
271 value, if there is little room left, to make sure the debugger itself
276 @section When a Variable is ``Void''
277 @kindex void-variable
278 @cindex void variable
280 If you have never given a symbol any value as a global variable, we
281 say that that symbol's global value is @dfn{void}. In other words, the
282 symbol's value cell does not have any Lisp object in it. If you try to
283 evaluate the symbol, you get a @code{void-variable} error rather than
286 Note that a value of @code{nil} is not the same as void. The symbol
287 @code{nil} is a Lisp object and can be the value of a variable just as any
288 other object can be; but it is @emph{a value}. A void variable does not
291 After you have given a variable a value, you can make it void once more
292 using @code{makunbound}.
294 @defun makunbound symbol
295 This function makes the current variable binding of @var{symbol} void.
296 Subsequent attempts to use this symbol's value as a variable will signal
297 the error @code{void-variable}, unless and until you set it again.
299 @code{makunbound} returns @var{symbol}.
303 (makunbound 'x) ; @r{Make the global value of @code{x} void.}
308 @error{} Symbol's value as variable is void: x
312 If @var{symbol} is locally bound, @code{makunbound} affects the most
313 local existing binding. This is the only way a symbol can have a void
314 local binding, since all the constructs that create local bindings
315 create them with values. In this case, the voidness lasts at most as
316 long as the binding does; when the binding is removed due to exit from
317 the construct that made it, the previous local or global binding is
318 reexposed as usual, and the variable is no longer void unless the newly
319 reexposed binding was void all along.
323 (setq x 1) ; @r{Put a value in the global binding.}
325 (let ((x 2)) ; @r{Locally bind it.}
326 (makunbound 'x) ; @r{Void the local binding.}
328 @error{} Symbol's value as variable is void: x
331 x ; @r{The global binding is unchanged.}
334 (let ((x 2)) ; @r{Locally bind it.}
335 (let ((x 3)) ; @r{And again.}
336 (makunbound 'x) ; @r{Void the innermost-local binding.}
337 x)) ; @r{And refer: it's void.}
338 @error{} Symbol's value as variable is void: x
344 (makunbound 'x)) ; @r{Void inner binding, then remove it.}
345 x) ; @r{Now outer @code{let} binding is visible.}
351 A variable that has been made void with @code{makunbound} is
352 indistinguishable from one that has never received a value and has
355 You can use the function @code{boundp} to test whether a variable is
358 @defun boundp variable
359 @code{boundp} returns @code{t} if @var{variable} (a symbol) is not void;
360 more precisely, if its current binding is not void. It returns
361 @code{nil} otherwise.
365 (boundp 'abracadabra) ; @r{Starts out void.}
369 (let ((abracadabra 5)) ; @r{Locally bind it.}
370 (boundp 'abracadabra))
374 (boundp 'abracadabra) ; @r{Still globally void.}
378 (setq abracadabra 5) ; @r{Make it globally nonvoid.}
382 (boundp 'abracadabra)
388 @node Defining Variables
389 @section Defining Global Variables
390 @cindex variable definition
392 You may announce your intention to use a symbol as a global variable
393 with a @dfn{variable definition}: a special form, either @code{defconst}
396 In Emacs Lisp, definitions serve three purposes. First, they inform
397 people who read the code that certain symbols are @emph{intended} to be
398 used a certain way (as variables). Second, they inform the Lisp system
399 of these things, supplying a value and documentation. Third, they
400 provide information to utilities such as @code{etags} and
401 @code{make-docfile}, which create data bases of the functions and
402 variables in a program.
404 The difference between @code{defconst} and @code{defvar} is primarily
405 a matter of intent, serving to inform human readers of whether the value
406 should ever change. Emacs Lisp does not restrict the ways in which a
407 variable can be used based on @code{defconst} or @code{defvar}
408 declarations. However, it does make a difference for initialization:
409 @code{defconst} unconditionally initializes the variable, while
410 @code{defvar} initializes it only if it is void.
413 One would expect user option variables to be defined with
414 @code{defconst}, since programs do not change them. Unfortunately, this
415 has bad results if the definition is in a library that is not preloaded:
416 @code{defconst} would override any prior value when the library is
417 loaded. Users would like to be able to set user options in their init
418 files, and override the default values given in the definitions. For
419 this reason, user options must be defined with @code{defvar}.
422 @defspec defvar symbol [value [doc-string]]
423 This special form defines @var{symbol} as a variable and can also
424 initialize and document it. The definition informs a person reading
425 your code that @var{symbol} is used as a variable that might be set or
426 changed. Note that @var{symbol} is not evaluated; the symbol to be
427 defined must appear explicitly in the @code{defvar}.
429 If @var{symbol} is void and @var{value} is specified, @code{defvar}
430 evaluates it and sets @var{symbol} to the result. But if @var{symbol}
431 already has a value (i.e., it is not void), @var{value} is not even
432 evaluated, and @var{symbol}'s value remains unchanged. If @var{value}
433 is omitted, the value of @var{symbol} is not changed in any case.
435 If @var{symbol} has a buffer-local binding in the current buffer,
436 @code{defvar} operates on the default value, which is buffer-independent,
437 not the current (buffer-local) binding. It sets the default value if
438 the default value is void. @xref{Buffer-Local Variables}.
440 When you evaluate a top-level @code{defvar} form with @kbd{C-M-x} in
441 Emacs Lisp mode (@code{eval-defun}), a special feature of
442 @code{eval-defun} arranges to set the variable unconditionally, without
443 testing whether its value is void.
445 If the @var{doc-string} argument appears, it specifies the documentation
446 for the variable. (This opportunity to specify documentation is one of
447 the main benefits of defining the variable.) The documentation is
448 stored in the symbol's @code{variable-documentation} property. The
449 Emacs help functions (@pxref{Documentation}) look for this property.
451 If the first character of @var{doc-string} is @samp{*}, it means that
452 this variable is considered a user option. This lets users set the
453 variable conveniently using the commands @code{set-variable} and
454 @code{edit-options}. However, it is better to use @code{defcustom}
455 instead of @code{defvar} for user option variables, so you can specify
456 customization information. @xref{Customization}.
458 Here are some examples. This form defines @code{foo} but does not
468 This example initializes the value of @code{bar} to @code{23}, and gives
469 it a documentation string:
474 "The normal weight of a bar.")
479 The following form changes the documentation string for @code{bar},
480 making it a user option, but does not change the value, since @code{bar}
481 already has a value. (The addition @code{(1+ nil)} would get an error
482 if it were evaluated, but since it is not evaluated, there is no error.)
487 "*The normal weight of a bar.")
496 Here is an equivalent expression for the @code{defvar} special form:
500 (defvar @var{symbol} @var{value} @var{doc-string})
503 (if (not (boundp '@var{symbol}))
504 (setq @var{symbol} @var{value}))
505 (if '@var{doc-string}
506 (put '@var{symbol} 'variable-documentation '@var{doc-string}))
511 The @code{defvar} form returns @var{symbol}, but it is normally used
512 at top level in a file where its value does not matter.
515 @defspec defconst symbol [value [doc-string]]
516 This special form defines @var{symbol} as a value and initializes it.
517 It informs a person reading your code that @var{symbol} has a standard
518 global value, established here, that should not be changed by the user
519 or by other programs. Note that @var{symbol} is not evaluated; the
520 symbol to be defined must appear explicitly in the @code{defconst}.
522 @code{defconst} always evaluates @var{value}, and sets the value of
523 @var{symbol} to the result if @var{value} is given. If @var{symbol}
524 does have a buffer-local binding in the current buffer, @code{defconst}
525 sets the default value, not the buffer-local value. (But you should not
526 be making buffer-local bindings for a symbol that is defined with
529 Here, @code{pi} is a constant that presumably ought not to be changed
530 by anyone (attempts by the Indiana State Legislature notwithstanding).
531 As the second form illustrates, however, this is only advisory.
535 (defconst pi 3.1415 "Pi to five places.")
549 @defun user-variable-p variable
551 This function returns @code{t} if @var{variable} is a user option---a
552 variable intended to be set by the user for customization---and
553 @code{nil} otherwise. (Variables other than user options exist for the
554 internal purposes of Lisp programs, and users need not know about them.)
556 User option variables are distinguished from other variables by the
557 first character of the @code{variable-documentation} property. If the
558 property exists and is a string, and its first character is @samp{*},
559 then the variable is a user option.
562 @kindex variable-interactive
563 If a user option variable has a @code{variable-interactive} property,
564 the @code{set-variable} command uses that value to control reading the
565 new value for the variable. The property's value is used as if it were
566 specified in @code{interactive} (@pxref{Using Interactive}). However,
567 this feature is largely obsoleted by @code{defcustom}
568 (@pxref{Customization}).
570 @strong{Warning:} If the @code{defconst} and @code{defvar} special
571 forms are used while the variable has a local binding, they set the
572 local binding's value; the global binding is not changed. This is not
573 what we really want. To prevent it, use these special forms at top
574 level in a file, where normally no local binding is in effect, and make
575 sure to load the file before making a local binding for the variable.
577 @node Tips for Defining
578 @section Tips for Defining Variables Robustly
580 When defining and initializing a variable that holds a complicated
581 value (such as a keymap with bindings in it), it's best to put the
582 entire computation of the value into the @code{defvar}, like this:
586 (let ((map (make-sparse-keymap)))
587 (define-key map "\C-c\C-a" 'my-command)
594 This method has several benefits. First, if the user quits while
595 loading the file, the variable is either still uninitialized or
596 initialized properly, never in-between. If it is still uninitialized,
597 reloading the file will initialize it properly. Second, reloading the
598 file once the variable is initialized will not alter it; that is
599 important if the user has run hooks to alter part of the contents (such
600 as, to rebind keys). Third, evaluating the @code{defvar} form with
601 @kbd{C-M-x} @emph{will} reinitialize the map completely.
603 Putting so much code in the @code{defvar} form has one disadvantage:
604 it puts the documentation string far away from the line which names the
605 variable. Here's a safe way to avoid that:
608 (defvar my-mode-map nil
611 (let ((map (make-sparse-keymap)))
612 (define-key my-mode-map "\C-c\C-a" 'my-command)
614 (setq my-mode-map map)))
618 This has all the same advantages as putting the initialization inside
619 the @code{defvar}, except that you must type @kbd{C-M-x} twice, once on
620 each form, if you do want to reinitialize the variable.
622 But be careful not to write the code like this:
625 (defvar my-mode-map nil
628 (setq my-mode-map (make-sparse-keymap))
629 (define-key my-mode-map "\C-c\C-a" 'my-command)
634 This code sets the variable, then alters it, but it does so in more than
635 one step. If the user quits just after the @code{setq}, that leaves the
636 variable neither correctly initialized nor void nor @code{nil}. Once
637 that happens, reloading the file will not initialize the variable; it
638 will remain incomplete.
640 @node Accessing Variables
641 @section Accessing Variable Values
643 The usual way to reference a variable is to write the symbol which
644 names it (@pxref{Symbol Forms}). This requires you to specify the
645 variable name when you write the program. Usually that is exactly what
646 you want to do. Occasionally you need to choose at run time which
647 variable to reference; then you can use @code{symbol-value}.
649 @defun symbol-value symbol
650 This function returns the value of @var{symbol}. This is the value in
651 the innermost local binding of the symbol, or its global value if it
652 has no local bindings.
665 ;; @r{Here the symbol @code{abracadabra}}
666 ;; @r{is the symbol whose value is examined.}
667 (let ((abracadabra 'foo))
668 (symbol-value 'abracadabra))
673 ;; @r{Here the value of @code{abracadabra},}
674 ;; @r{which is @code{foo},}
675 ;; @r{is the symbol whose value is examined.}
676 (let ((abracadabra 'foo))
677 (symbol-value abracadabra))
682 (symbol-value 'abracadabra)
687 A @code{void-variable} error is signaled if the current binding of
688 @var{symbol} is void.
691 @node Setting Variables
692 @section How to Alter a Variable Value
694 The usual way to change the value of a variable is with the special
695 form @code{setq}. When you need to compute the choice of variable at
696 run time, use the function @code{set}.
698 @defspec setq [symbol form]@dots{}
699 This special form is the most common method of changing a variable's
700 value. Each @var{symbol} is given a new value, which is the result of
701 evaluating the corresponding @var{form}. The most-local existing
702 binding of the symbol is changed.
704 @code{setq} does not evaluate @var{symbol}; it sets the symbol that you
705 write. We say that this argument is @dfn{automatically quoted}. The
706 @samp{q} in @code{setq} stands for ``quoted.''
708 The value of the @code{setq} form is the value of the last @var{form}.
715 x ; @r{@code{x} now has a global value.}
719 (setq x 6) ; @r{The local binding of @code{x} is set.}
723 x ; @r{The global value is unchanged.}
727 Note that the first @var{form} is evaluated, then the first
728 @var{symbol} is set, then the second @var{form} is evaluated, then the
729 second @var{symbol} is set, and so on:
733 (setq x 10 ; @r{Notice that @code{x} is set before}
734 y (1+ x)) ; @r{the value of @code{y} is computed.}
740 @defun set symbol value
741 This function sets @var{symbol}'s value to @var{value}, then returns
742 @var{value}. Since @code{set} is a function, the expression written for
743 @var{symbol} is evaluated to obtain the symbol to set.
745 The most-local existing binding of the variable is the binding that is
746 set; shadowed bindings are not affected.
751 @error{} Symbol's value as variable is void: one
762 (set two 2) ; @r{@code{two} evaluates to symbol @code{one}.}
766 one ; @r{So it is @code{one} that was set.}
768 (let ((one 1)) ; @r{This binding of @code{one} is set,}
769 (set 'one 3) ; @r{not the global value.}
779 If @var{symbol} is not actually a symbol, a @code{wrong-type-argument}
784 @error{} Wrong type argument: symbolp, (x y)
787 Logically speaking, @code{set} is a more fundamental primitive than
788 @code{setq}. Any use of @code{setq} can be trivially rewritten to use
789 @code{set}; @code{setq} could even be defined as a macro, given the
790 availability of @code{set}. However, @code{set} itself is rarely used;
791 beginners hardly need to know about it. It is useful only for choosing
792 at run time which variable to set. For example, the command
793 @code{set-variable}, which reads a variable name from the user and then
794 sets the variable, needs to use @code{set}.
796 @cindex CL note---@code{set} local
798 @b{Common Lisp note:} In Common Lisp, @code{set} always changes the
799 symbol's ``special'' or dynamic value, ignoring any lexical bindings.
800 In Emacs Lisp, all variables and all bindings are dynamic, so @code{set}
801 always affects the most local existing binding.
805 One other function for setting a variable is designed to add
806 an element to a list if it is not already present in the list.
808 @defun add-to-list symbol element
809 This function sets the variable @var{symbol} by consing @var{element}
810 onto the old value, if @var{element} is not already a member of that
811 value. It returns the resulting list, whether updated or not. The
812 value of @var{symbol} had better be a list already before the call.
814 The argument @var{symbol} is not implicitly quoted; @code{add-to-list}
815 is an ordinary function, like @code{set} and unlike @code{setq}. Quote
816 the argument yourself if that is what you want.
819 Here's a scenario showing how to use @code{add-to-list}:
825 (add-to-list 'foo 'c) ;; @r{Add @code{c}.}
828 (add-to-list 'foo 'b) ;; @r{No effect.}
831 foo ;; @r{@code{foo} was changed.}
835 An equivalent expression for @code{(add-to-list '@var{var}
836 @var{value})} is this:
839 (or (member @var{value} @var{var})
840 (setq @var{var} (cons @var{value} @var{var})))
843 @node Variable Scoping
844 @section Scoping Rules for Variable Bindings
846 A given symbol @code{foo} can have several local variable bindings,
847 established at different places in the Lisp program, as well as a global
848 binding. The most recently established binding takes precedence over
853 @cindex dynamic scoping
854 Local bindings in Emacs Lisp have @dfn{indefinite scope} and
855 @dfn{dynamic extent}. @dfn{Scope} refers to @emph{where} textually in
856 the source code the binding can be accessed. ``Indefinite scope'' means
857 that any part of the program can potentially access the variable
858 binding. @dfn{Extent} refers to @emph{when}, as the program is
859 executing, the binding exists. ``Dynamic extent'' means that the binding
860 lasts as long as the activation of the construct that established it.
862 The combination of dynamic extent and indefinite scope is called
863 @dfn{dynamic scoping}. By contrast, most programming languages use
864 @dfn{lexical scoping}, in which references to a local variable must be
865 located textually within the function or block that binds the variable.
867 @cindex CL note---special variables
869 @b{Common Lisp note:} Variables declared ``special'' in Common Lisp are
870 dynamically scoped, like all variables in Emacs Lisp.
874 * Scope:: Scope means where in the program a value is visible.
875 Comparison with other languages.
876 * Extent:: Extent means how long in time a value exists.
877 * Impl of Scope:: Two ways to implement dynamic scoping.
878 * Using Scoping:: How to use dynamic scoping carefully and avoid problems.
884 Emacs Lisp uses @dfn{indefinite scope} for local variable bindings.
885 This means that any function anywhere in the program text might access a
886 given binding of a variable. Consider the following function
891 (defun binder (x) ; @r{@code{x} is bound in @code{binder}.}
892 (foo 5)) ; @r{@code{foo} is some other function.}
896 (defun user () ; @r{@code{x} is used ``free'' in @code{user}.}
901 In a lexically scoped language, the binding of @code{x} in
902 @code{binder} would never be accessible in @code{user}, because
903 @code{user} is not textually contained within the function
904 @code{binder}. However, in dynamically-scoped Emacs Lisp, @code{user}
905 may or may not refer to the binding of @code{x} established in
906 @code{binder}, depending on the circumstances:
910 If we call @code{user} directly without calling @code{binder} at all,
911 then whatever binding of @code{x} is found, it cannot come from
915 If we define @code{foo} as follows and then call @code{binder}, then the
916 binding made in @code{binder} will be seen in @code{user}:
926 However, if we define @code{foo} as follows and then call @code{binder},
927 then the binding made in @code{binder} @emph{will not} be seen in
936 Here, when @code{foo} is called by @code{binder}, it binds @code{x}.
937 (The binding in @code{foo} is said to @dfn{shadow} the one made in
938 @code{binder}.) Therefore, @code{user} will access the @code{x} bound
939 by @code{foo} instead of the one bound by @code{binder}.
942 Emacs Lisp uses dynamic scoping because simple implementations of
943 lexical scoping are slow. In addition, every Lisp system needs to offer
944 dynamic scoping at least as an option; if lexical scoping is the norm,
945 there must be a way to specify dynamic scoping instead for a particular
946 variable. It might not be a bad thing for Emacs to offer both, but
947 implementing it with dynamic scoping only was much easier.
952 @dfn{Extent} refers to the time during program execution that a
953 variable name is valid. In Emacs Lisp, a variable is valid only while
954 the form that bound it is executing. This is called @dfn{dynamic
955 extent}. ``Local'' or ``automatic'' variables in most languages,
956 including C and Pascal, have dynamic extent.
958 One alternative to dynamic extent is @dfn{indefinite extent}. This
959 means that a variable binding can live on past the exit from the form
960 that made the binding. Common Lisp and Scheme, for example, support
961 this, but Emacs Lisp does not.
963 To illustrate this, the function below, @code{make-add}, returns a
964 function that purports to add @var{n} to its own argument @var{m}. This
965 would work in Common Lisp, but it does not do the job in Emacs Lisp,
966 because after the call to @code{make-add} exits, the variable @code{n}
967 is no longer bound to the actual argument 2.
971 (function (lambda (m) (+ n m)))) ; @r{Return a function.}
973 (fset 'add2 (make-add 2)) ; @r{Define function @code{add2}}
974 ; @r{with @code{(make-add 2)}.}
975 @result{} (lambda (m) (+ n m))
976 (add2 4) ; @r{Try to add 2 to 4.}
977 @error{} Symbol's value as variable is void: n
980 @cindex closures not available
981 Some Lisp dialects have ``closures'', objects that are like functions
982 but record additional variable bindings. Emacs Lisp does not have
986 @subsection Implementation of Dynamic Scoping
989 A simple sample implementation (which is not how Emacs Lisp actually
990 works) may help you understand dynamic binding. This technique is
991 called @dfn{deep binding} and was used in early Lisp systems.
993 Suppose there is a stack of bindings, which are variable-value pairs.
994 At entry to a function or to a @code{let} form, we can push bindings
995 onto the stack for the arguments or local variables created there. We
996 can pop those bindings from the stack at exit from the binding
999 We can find the value of a variable by searching the stack from top to
1000 bottom for a binding for that variable; the value from that binding is
1001 the value of the variable. To set the variable, we search for the
1002 current binding, then store the new value into that binding.
1004 As you can see, a function's bindings remain in effect as long as it
1005 continues execution, even during its calls to other functions. That is
1006 why we say the extent of the binding is dynamic. And any other function
1007 can refer to the bindings, if it uses the same variables while the
1008 bindings are in effect. That is why we say the scope is indefinite.
1010 @cindex shallow binding
1011 The actual implementation of variable scoping in GNU Emacs Lisp uses a
1012 technique called @dfn{shallow binding}. Each variable has a standard
1013 place in which its current value is always found---the value cell of the
1016 In shallow binding, setting the variable works by storing a value in
1017 the value cell. Creating a new binding works by pushing the old value
1018 (belonging to a previous binding) onto a stack, and storing the new
1019 local value in the value cell. Eliminating a binding works by popping
1020 the old value off the stack, into the value cell.
1022 We use shallow binding because it has the same results as deep
1023 binding, but runs faster, since there is never a need to search for a
1027 @subsection Proper Use of Dynamic Scoping
1029 Binding a variable in one function and using it in another is a
1030 powerful technique, but if used without restraint, it can make programs
1031 hard to understand. There are two clean ways to use this technique:
1035 Use or bind the variable only in a few related functions, written close
1036 together in one file. Such a variable is used for communication within
1039 You should write comments to inform other programmers that they can see
1040 all uses of the variable before them, and to advise them not to add uses
1044 Give the variable a well-defined, documented meaning, and make all
1045 appropriate functions refer to it (but not bind it or set it) wherever
1046 that meaning is relevant. For example, the variable
1047 @code{case-fold-search} is defined as ``non-@code{nil} means ignore case
1048 when searching''; various search and replace functions refer to it
1049 directly or through their subroutines, but do not bind or set it.
1051 Then you can bind the variable in other programs, knowing reliably what
1055 In either case, you should define the variable with @code{defvar}.
1056 This helps other people understand your program by telling them to look
1057 for inter-function usage. It also avoids a warning from the byte
1058 compiler. Choose the variable's name to avoid name conflicts---don't
1059 use short names like @code{x}.
1061 @node Buffer-Local Variables
1062 @section Buffer-Local Variables
1063 @cindex variables, buffer-local
1064 @cindex buffer-local variables
1066 Global and local variable bindings are found in most programming
1067 languages in one form or another. Emacs, however, also supports additional,
1068 unusual kinds of variable binding: @dfn{buffer-local} bindings, which
1069 apply only in one buffer, and @dfn{frame-local} bindings, which apply only in
1070 one frame. Having different values for a variable in different buffers
1071 and/or frames is an important customization method.
1073 This section describes buffer-local bindings; for frame-local
1074 bindings, see the following section, @ref{Frame-Local Variables}. (A few
1075 variables have bindings that are local to each terminal; see
1076 @ref{Multiple Displays}.)
1079 * Intro to Buffer-Local:: Introduction and concepts.
1080 * Creating Buffer-Local:: Creating and destroying buffer-local bindings.
1081 * Default Value:: The default value is seen in buffers
1082 that don't have their own buffer-local values.
1085 @node Intro to Buffer-Local
1086 @subsection Introduction to Buffer-Local Variables
1088 A buffer-local variable has a buffer-local binding associated with a
1089 particular buffer. The binding is in effect when that buffer is
1090 current; otherwise, it is not in effect. If you set the variable while
1091 a buffer-local binding is in effect, the new value goes in that binding,
1092 so its other bindings are unchanged. This means that the change is
1093 visible only in the buffer where you made it.
1095 The variable's ordinary binding, which is not associated with any
1096 specific buffer, is called the @dfn{default binding}. In most cases,
1097 this is the global binding.
1099 A variable can have buffer-local bindings in some buffers but not in
1100 other buffers. The default binding is shared by all the buffers that
1101 don't have their own bindings for the variable. (This includes all
1102 newly-created buffers.) If you set the variable in a buffer that does
1103 not have a buffer-local binding for it, this sets the default binding
1104 (assuming there are no frame-local bindings to complicate the matter),
1105 so the new value is visible in all the buffers that see the default
1108 The most common use of buffer-local bindings is for major modes to change
1109 variables that control the behavior of commands. For example, C mode and
1110 Lisp mode both set the variable @code{paragraph-start} to specify that only
1111 blank lines separate paragraphs. They do this by making the variable
1112 buffer-local in the buffer that is being put into C mode or Lisp mode, and
1113 then setting it to the new value for that mode. @xref{Major Modes}.
1115 The usual way to make a buffer-local binding is with
1116 @code{make-local-variable}, which is what major mode commands typically
1117 use. This affects just the current buffer; all other buffers (including
1118 those yet to be created) will continue to share the default value unless
1119 they are explicitly given their own buffer-local bindings.
1121 @cindex automatically buffer-local
1122 A more powerful operation is to mark the variable as
1123 @dfn{automatically buffer-local} by calling
1124 @code{make-variable-buffer-local}. You can think of this as making the
1125 variable local in all buffers, even those yet to be created. More
1126 precisely, the effect is that setting the variable automatically makes
1127 the variable local to the current buffer if it is not already so. All
1128 buffers start out by sharing the default value of the variable as usual,
1129 but setting the variable creates a buffer-local binding for the current
1130 buffer. The new value is stored in the buffer-local binding, leaving
1131 the default binding untouched. This means that the default value cannot
1132 be changed with @code{setq} in any buffer; the only way to change it is
1133 with @code{setq-default}.
1135 @strong{Warning:} When a variable has buffer-local values in one or
1136 more buffers, you can get Emacs very confused by binding the variable
1137 with @code{let}, changing to a different current buffer in which a
1138 different binding is in effect, and then exiting the @code{let}. This
1139 can scramble the values of the buffer-local and default bindings.
1141 To preserve your sanity, avoid using a variable in that way. If you
1142 use @code{save-excursion} around each piece of code that changes to a
1143 different current buffer, you will not have this problem
1144 (@pxref{Excursions}). Here is an example of what to avoid:
1150 (make-local-variable 'foo)
1157 foo @result{} 'a ; @r{The old buffer-local value from buffer @samp{a}}
1158 ; @r{is now the default value.}
1162 foo @result{} 'temp ; @r{The local @code{let} value that should be gone}
1163 ; @r{is now the buffer-local value in buffer @samp{a}.}
1168 But @code{save-excursion} as shown here avoids the problem:
1179 Note that references to @code{foo} in @var{body} access the
1180 buffer-local binding of buffer @samp{b}.
1182 When a file specifies local variable values, these become buffer-local
1183 values when you visit the file. @xref{File Variables,,, emacs, The
1186 @node Creating Buffer-Local
1187 @subsection Creating and Deleting Buffer-Local Bindings
1189 @deffn Command make-local-variable variable
1190 This function creates a buffer-local binding in the current buffer for
1191 @var{variable} (a symbol). Other buffers are not affected. The value
1192 returned is @var{variable}.
1195 The buffer-local value of @var{variable} starts out as the same value
1196 @var{variable} previously had. If @var{variable} was void, it remains
1201 ;; @r{In buffer @samp{b1}:}
1202 (setq foo 5) ; @r{Affects all buffers.}
1206 (make-local-variable 'foo) ; @r{Now it is local in @samp{b1}.}
1210 foo ; @r{That did not change}
1211 @result{} 5 ; @r{the value.}
1214 (setq foo 6) ; @r{Change the value}
1215 @result{} 6 ; @r{in @samp{b1}.}
1223 ;; @r{In buffer @samp{b2}, the value hasn't changed.}
1231 Making a variable buffer-local within a @code{let}-binding for that
1232 variable does not work reliably, unless the buffer in which you do this
1233 is not current either on entry to or exit from the @code{let}. This is
1234 because @code{let} does not distinguish between different kinds of
1235 bindings; it knows only which variable the binding was made for.
1237 If the variable is terminal-local, this function signals an error. Such
1238 variables cannot have buffer-local bindings as well. @xref{Multiple
1241 @strong{Note:} Do not use @code{make-local-variable} for a hook
1242 variable. Instead, use @code{make-local-hook}. @xref{Hooks}.
1245 @deffn Command make-variable-buffer-local variable
1246 This function marks @var{variable} (a symbol) automatically
1247 buffer-local, so that any subsequent attempt to set it will make it
1248 local to the current buffer at the time.
1250 A peculiar wrinkle of this feature is that binding the variable (with
1251 @code{let} or other binding constructs) does not create a buffer-local
1252 binding for it. Only setting the variable (with @code{set} or
1253 @code{setq}) does so.
1255 The value returned is @var{variable}.
1257 @strong{Warning:} Don't assume that you should use
1258 @code{make-variable-buffer-local} for user-option variables, simply
1259 because users @emph{might} want to customize them differently in
1260 different buffers. Users can make any variable local, when they wish
1261 to. It is better to leave the choice to them.
1263 The time to use @code{make-variable-buffer-local} is when it is crucial
1264 that no two buffers ever share the same binding. For example, when a
1265 variable is used for internal purposes in a Lisp program which depends
1266 on having separate values in separate buffers, then using
1267 @code{make-variable-buffer-local} can be the best solution.
1270 @defun local-variable-p variable &optional buffer
1271 This returns @code{t} if @var{variable} is buffer-local in buffer
1272 @var{buffer} (which defaults to the current buffer); otherwise,
1276 @defun buffer-local-variables &optional buffer
1277 This function returns a list describing the buffer-local variables in
1278 buffer @var{buffer}. (If @var{buffer} is omitted, the current buffer is
1279 used.) It returns an association list (@pxref{Association Lists}) in
1280 which each element contains one buffer-local variable and its value.
1281 However, when a variable's buffer-local binding in @var{buffer} is void,
1282 then the variable appears directly in the resulting list.
1286 (make-local-variable 'foobar)
1287 (makunbound 'foobar)
1288 (make-local-variable 'bind-me)
1291 (setq lcl (buffer-local-variables))
1292 ;; @r{First, built-in variables local in all buffers:}
1293 @result{} ((mark-active . nil)
1294 (buffer-undo-list . nil)
1295 (mode-name . "Fundamental")
1298 ;; @r{Next, non-built-in buffer-local variables.}
1299 ;; @r{This one is buffer-local and void:}
1301 ;; @r{This one is buffer-local and nonvoid:}
1306 Note that storing new values into the @sc{cdr}s of cons cells in this
1307 list does @emph{not} change the buffer-local values of the variables.
1310 @deffn Command kill-local-variable variable
1311 This function deletes the buffer-local binding (if any) for
1312 @var{variable} (a symbol) in the current buffer. As a result, the
1313 default binding of @var{variable} becomes visible in this buffer. This
1314 typically results in a change in the value of @var{variable}, since the
1315 default value is usually different from the buffer-local value just
1318 If you kill the buffer-local binding of a variable that automatically
1319 becomes buffer-local when set, this makes the default value visible in
1320 the current buffer. However, if you set the variable again, that will
1321 once again create a buffer-local binding for it.
1323 @code{kill-local-variable} returns @var{variable}.
1325 This function is a command because it is sometimes useful to kill one
1326 buffer-local variable interactively, just as it is useful to create
1327 buffer-local variables interactively.
1330 @defun kill-all-local-variables
1331 This function eliminates all the buffer-local variable bindings of the
1332 current buffer except for variables marked as ``permanent''. As a
1333 result, the buffer will see the default values of most variables.
1335 This function also resets certain other information pertaining to the
1336 buffer: it sets the local keymap to @code{nil}, the syntax table to the
1337 value of @code{(standard-syntax-table)}, the case table to
1338 @code{(standard-case-table)}, and the abbrev table to the value of
1339 @code{fundamental-mode-abbrev-table}.
1341 The very first thing this function does is run the normal hook
1342 @code{change-major-mode-hook} (see below).
1344 Every major mode command begins by calling this function, which has the
1345 effect of switching to Fundamental mode and erasing most of the effects
1346 of the previous major mode. To ensure that this does its job, the
1347 variables that major modes set should not be marked permanent.
1349 @code{kill-all-local-variables} returns @code{nil}.
1352 @defvar change-major-mode-hook
1353 The function @code{kill-all-local-variables} runs this normal hook
1354 before it does anything else. This gives major modes a way to arrange
1355 for something special to be done if the user switches to a different
1356 major mode. For best results, make this variable buffer-local, so that
1357 it will disappear after doing its job and will not interfere with the
1358 subsequent major mode. @xref{Hooks}.
1362 @cindex permanent local variable
1363 A buffer-local variable is @dfn{permanent} if the variable name (a
1364 symbol) has a @code{permanent-local} property that is non-@code{nil}.
1365 Permanent locals are appropriate for data pertaining to where the file
1366 came from or how to save it, rather than with how to edit the contents.
1369 @subsection The Default Value of a Buffer-Local Variable
1370 @cindex default value
1372 The global value of a variable with buffer-local bindings is also
1373 called the @dfn{default} value, because it is the value that is in
1374 effect whenever neither the current buffer nor the selected frame has
1375 its own binding for the variable.
1377 The functions @code{default-value} and @code{setq-default} access and
1378 change a variable's default value regardless of whether the current
1379 buffer has a buffer-local binding. For example, you could use
1380 @code{setq-default} to change the default setting of
1381 @code{paragraph-start} for most buffers; and this would work even when
1382 you are in a C or Lisp mode buffer that has a buffer-local value for
1386 The special forms @code{defvar} and @code{defconst} also set the
1387 default value (if they set the variable at all), rather than any
1388 buffer-local or frame-local value.
1390 @defun default-value symbol
1391 This function returns @var{symbol}'s default value. This is the value
1392 that is seen in buffers and frames that do not have their own values for
1393 this variable. If @var{symbol} is not buffer-local, this is equivalent
1394 to @code{symbol-value} (@pxref{Accessing Variables}).
1398 @defun default-boundp symbol
1399 The function @code{default-boundp} tells you whether @var{symbol}'s
1400 default value is nonvoid. If @code{(default-boundp 'foo)} returns
1401 @code{nil}, then @code{(default-value 'foo)} would get an error.
1403 @code{default-boundp} is to @code{default-value} as @code{boundp} is to
1404 @code{symbol-value}.
1407 @defspec setq-default [symbol form]@dots{}
1408 This special form gives each @var{symbol} a new default value, which is
1409 the result of evaluating the corresponding @var{form}. It does not
1410 evaluate @var{symbol}, but does evaluate @var{form}. The value of the
1411 @code{setq-default} form is the value of the last @var{form}.
1413 If a @var{symbol} is not buffer-local for the current buffer, and is not
1414 marked automatically buffer-local, @code{setq-default} has the same
1415 effect as @code{setq}. If @var{symbol} is buffer-local for the current
1416 buffer, then this changes the value that other buffers will see (as long
1417 as they don't have a buffer-local value), but not the value that the
1418 current buffer sees.
1422 ;; @r{In buffer @samp{foo}:}
1423 (make-local-variable 'buffer-local)
1424 @result{} buffer-local
1427 (setq buffer-local 'value-in-foo)
1428 @result{} value-in-foo
1431 (setq-default buffer-local 'new-default)
1432 @result{} new-default
1436 @result{} value-in-foo
1439 (default-value 'buffer-local)
1440 @result{} new-default
1444 ;; @r{In (the new) buffer @samp{bar}:}
1446 @result{} new-default
1449 (default-value 'buffer-local)
1450 @result{} new-default
1453 (setq buffer-local 'another-default)
1454 @result{} another-default
1457 (default-value 'buffer-local)
1458 @result{} another-default
1462 ;; @r{Back in buffer @samp{foo}:}
1464 @result{} value-in-foo
1465 (default-value 'buffer-local)
1466 @result{} another-default
1471 @defun set-default symbol value
1472 This function is like @code{setq-default}, except that @var{symbol} is
1473 an ordinary evaluated argument.
1477 (set-default (car '(a b c)) 23)
1487 @node Frame-Local Variables
1488 @section Frame-Local Variables
1490 Just as variables can have buffer-local bindings, they can also have
1491 frame-local bindings. These bindings belong to one frame, and are in
1492 effect when that frame is selected. Frame-local bindings are actually
1493 frame parameters: you create a frame-local binding in a specific frame
1494 by calling @code{modify-frame-parameters} and specifying the variable
1495 name as the parameter name.
1497 To enable frame-local bindings for a certain variable, call the function
1498 @code{make-variable-frame-local}.
1500 @deffn Command make-variable-frame-local variable
1501 Enable the use of frame-local bindings for @var{variable}. This does
1502 not in itself create any frame-local bindings for the variable; however,
1503 if some frame already has a value for @var{variable} as a frame
1504 parameter, that value automatically becomes a frame-local binding.
1506 If the variable is terminal-local, this function signals an error,
1507 because such variables cannot have frame-local bindings as well.
1508 @xref{Multiple Displays}. A few variables that are implemented
1509 specially in Emacs can be (and usually are) buffer-local, but can never
1513 Buffer-local bindings take precedence over frame-local bindings. Thus,
1514 consider a variable @code{foo}: if the current buffer has a buffer-local
1515 binding for @code{foo}, that binding is active; otherwise, if the
1516 selected frame has a frame-local binding for @code{foo}, that binding is
1517 active; otherwise, the default binding of @code{foo} is active.
1519 Here is an example. First we prepare a few bindings for @code{foo}:
1522 (setq f1 (selected-frame))
1523 (make-variable-frame-local 'foo)
1525 ;; @r{Make a buffer-local binding for @code{foo} in @samp{b1}.}
1526 (set-buffer (get-buffer-create "b1"))
1527 (make-local-variable 'foo)
1530 ;; @r{Make a frame-local binding for @code{foo} in a new frame.}
1531 ;; @r{Store that frame in @code{f2}.}
1532 (setq f2 (make-frame))
1533 (modify-frame-parameters f2 '((foo . (f 2))))
1536 Now we examine @code{foo} in various contexts. Whenever the
1537 buffer @samp{b1} is current, its buffer-local binding is in effect,
1538 regardless of the selected frame:
1542 (set-buffer (get-buffer-create "b1"))
1547 (set-buffer (get-buffer-create "b1"))
1553 Otherwise, the frame gets a chance to provide the binding; when frame
1554 @code{f2} is selected, its frame-local binding is in effect:
1558 (set-buffer (get-buffer "*scratch*"))
1564 When neither the current buffer nor the selected frame provides
1565 a binding, the default binding is used:
1569 (set-buffer (get-buffer "*scratch*"))
1575 When the active binding of a variable is a frame-local binding, setting
1576 the variable changes that binding. You can observe the result with
1577 @code{frame-parameters}:
1581 (set-buffer (get-buffer "*scratch*"))
1583 (assq 'foo (frame-parameters f2))
1584 @result{} (foo . nobody)
1587 @node Future Local Variables
1588 @section Possible Future Local Variables
1590 We have considered the idea of bindings that are local to a category
1591 of frames---for example, all color frames, or all frames with dark
1592 backgrounds. We have not implemented them because it is not clear that
1593 this feature is really useful. You can get more or less the same
1594 results by adding a function to @code{after-make-frame-hook}, set up to
1595 define a particular frame parameter according to the appropriate
1596 conditions for each frame.
1598 It would also be possible to implement window-local bindings. We
1599 don't know of many situations where they would be useful, and it seems
1600 that indirect buffers (@pxref{Indirect Buffers}) with buffer-local
1601 bindings offer a way to handle these situations more robustly.
1603 If sufficient application is found for either of these two kinds of
1604 local bindings, we will provide it in a subsequent Emacs version.