aboutsummaryrefslogtreecommitdiffstats
path: root/doc
diff options
context:
space:
mode:
authorChong Yidong2012-01-25 00:08:00 +0800
committerChong Yidong2012-01-25 00:08:00 +0800
commit1021c7615d4aab121e657d3cc5c4f1e036f8901f (patch)
tree0a3076c4a911c10df809072a7783bd2329f3367a /doc
parent6725d21a1be13cfad897dab54509928c3f5b5d1e (diff)
downloademacs-1021c7615d4aab121e657d3cc5c4f1e036f8901f.tar.gz
emacs-1021c7615d4aab121e657d3cc5c4f1e036f8901f.zip
Update Variables chapter of Lisp manual to handle lexical binding.
* doc/lispref/variables.texi (Variables, Local Variables, Void Variables): Edit to make the descriptions less specific to dynamic binding. (Local Variables): Default max-specpdl-size is now 1300. (Defining Variables): Edits for lexical scoping. Delete information about starting docstrings with *. De-document user-variable-p. (Tips for Defining): Remove an unimportant discussion of quitting in the middle of a load. (Accessing Variables, Setting Variables): Discuss lexical binding. (Variable Scoping): Rewrite. (Scope, Extent, Impl of Scope): Nodes deleted. (Dynamic Binding): New node, with material from Scope, Extent, and Impl of Scope nodes. (Dynamic Binding Tips): Rename from Using Scoping. (Lexical Binding): Rewrite. (Using Lexical Binding): Rename from Converting to Lexical Binding. Convert to subsection. * doc/lispref/customize.texi (Variable Definitions): Add custom-variable-p. Move user-variable-p documentation here.
Diffstat (limited to 'doc')
-rw-r--r--doc/lispref/ChangeLog23
-rw-r--r--doc/lispref/customize.texi25
-rw-r--r--doc/lispref/elisp.texi10
-rw-r--r--doc/lispref/objects.texi6
-rw-r--r--doc/lispref/variables.texi988
5 files changed, 502 insertions, 550 deletions
diff --git a/doc/lispref/ChangeLog b/doc/lispref/ChangeLog
index b66f82c5738..9e4d50943fe 100644
--- a/doc/lispref/ChangeLog
+++ b/doc/lispref/ChangeLog
@@ -1,3 +1,26 @@
12012-01-24 Chong Yidong <cyd@gnu.org>
2
3 * variables.texi (Variables, Local Variables, Void Variables):
4 Edit to make the descriptions less specific to dynamic binding.
5 (Local Variables): Default max-specpdl-size is now 1300.
6 (Defining Variables): Edits for lexical scoping. Delete
7 information about starting docstrings with *. De-document
8 user-variable-p.
9 (Tips for Defining): Remove an unimportant discussion of quitting
10 in the middle of a load.
11 (Accessing Variables, Setting Variables): Discuss lexical binding.
12 (Variable Scoping): Rewrite.
13 (Scope, Extent, Impl of Scope): Nodes deleted.
14 (Dynamic Binding): New node, with material from Scope, Extent, and
15 Impl of Scope nodes.
16 (Dynamic Binding Tips): Rename from Using Scoping.
17 (Lexical Binding): Rewrite.
18 (Using Lexical Binding): Rename from Converting to Lexical
19 Binding. Convert to subsection.
20
21 * customize.texi (Variable Definitions): Add custom-variable-p.
22 Move user-variable-p documentation here.
23
12012-01-23 Chong Yidong <cyd@gnu.org> 242012-01-23 Chong Yidong <cyd@gnu.org>
2 25
3 * strings.texi (Text Comparison): Minor qualification. 26 * strings.texi (Text Comparison): Minor qualification.
diff --git a/doc/lispref/customize.texi b/doc/lispref/customize.texi
index f8495513be4..6d6c5df10ed 100644
--- a/doc/lispref/customize.texi
+++ b/doc/lispref/customize.texi
@@ -262,12 +262,6 @@ turn this feature back on, if someone would like to do the work.
262This macro declares @var{option} as a customizable @dfn{user option}. 262This macro declares @var{option} as a customizable @dfn{user option}.
263You should not quote @var{option}. 263You should not quote @var{option}.
264 264
265This causes the function @code{user-variable-p} to return @code{t}
266when given @var{option} as an argument. @xref{Defining Variables}.
267The argument @var{doc} specifies the documentation string for the
268variable. (Note that there is no need to start @var{doc} with a
269@samp{*}.)
270
271The argument @var{standard} is an expression that specifies the 265The argument @var{standard} is an expression that specifies the
272standard value for @var{option}. Evaluating the @code{defcustom} form 266standard value for @var{option}. Evaluating the @code{defcustom} form
273evaluates @var{standard}, but does not necessarily install the 267evaluates @var{standard}, but does not necessarily install the
@@ -285,6 +279,9 @@ evaluate at any time. We recommend avoiding backquotes in
285@var{standard}, because they are not expanded when editing the value, 279@var{standard}, because they are not expanded when editing the value,
286so list values will appear to have the wrong structure. 280so list values will appear to have the wrong structure.
287 281
282The argument @var{doc} specifies the documentation string for the
283variable.
284
288Every @code{defcustom} should specify @code{:group} at least once. 285Every @code{defcustom} should specify @code{:group} at least once.
289 286
290If you specify the @code{:set} keyword, to make the variable take other 287If you specify the @code{:set} keyword, to make the variable take other
@@ -474,6 +471,22 @@ A good place to put calls to this function is in the function
474or in the various hooks it calls. 471or in the various hooks it calls.
475@end defun 472@end defun
476 473
474@defun custom-variable-p arg
475This function returns non-@code{nil} if @var{arg} is a customizable
476variable. A customizable variable is either a variable that has a
477@code{standard-value} or @code{custom-autoload} property (usually
478meaning it was declared with @code{defcustom}), or an alias for
479another customizable variable.
480@end defun
481
482@defun user-variable-p arg
483This function is like @code{custom-variable-p}, except it also returns
484@code{t} if the first character of the variable's documentation string
485is the character @samp{*}. That is an obsolete way of indicating a
486user option, so for most purposes you may consider
487@code{user-variable-p} as equivalent to @code{custom-variable-p}.
488@end defun
489
477@node Customization Types 490@node Customization Types
478@section Customization Types 491@section Customization Types
479 492
diff --git a/doc/lispref/elisp.texi b/doc/lispref/elisp.texi
index 1555b98e7fb..31e887ea68b 100644
--- a/doc/lispref/elisp.texi
+++ b/doc/lispref/elisp.texi
@@ -436,12 +436,10 @@ Variables
436 436
437Scoping Rules for Variable Bindings 437Scoping Rules for Variable Bindings
438 438
439* Scope:: Scope means where in the program a value 439* Dynamic Binding:: The default for binding local variables in Emacs.
440 is visible. Comparison with other languages. 440* Dynamic Binding Tips:: Avoiding problems with dynamic binding.
441* Extent:: Extent means how long in time a value exists. 441* Lexical Binding:: A different type of local variable binding.
442* Impl of Scope:: Two ways to implement dynamic scoping. 442* Using Lexical Binding:: How to enable lexical binding.
443* Using Scoping:: How to use dynamic scoping carefully and
444 avoid problems.
445 443
446Buffer-Local Variables 444Buffer-Local Variables
447 445
diff --git a/doc/lispref/objects.texi b/doc/lispref/objects.texi
index 87bcc20daba..445cb800d33 100644
--- a/doc/lispref/objects.texi
+++ b/doc/lispref/objects.texi
@@ -1795,6 +1795,9 @@ with references to further information.
1795@item consp 1795@item consp
1796@xref{List-related Predicates, consp}. 1796@xref{List-related Predicates, consp}.
1797 1797
1798@item custom-variable-p
1799@xref{Variable Definitions, custom-variable-p}.
1800
1798@item display-table-p 1801@item display-table-p
1799@xref{Display Tables, display-table-p}. 1802@xref{Display Tables, display-table-p}.
1800 1803
@@ -1870,9 +1873,6 @@ with references to further information.
1870@item syntax-table-p 1873@item syntax-table-p
1871@xref{Syntax Tables, syntax-table-p}. 1874@xref{Syntax Tables, syntax-table-p}.
1872 1875
1873@item user-variable-p
1874@xref{Defining Variables, user-variable-p}.
1875
1876@item vectorp 1876@item vectorp
1877@xref{Vectors, vectorp}. 1877@xref{Vectors, vectorp}.
1878 1878
diff --git a/doc/lispref/variables.texi b/doc/lispref/variables.texi
index a8f75f5a160..ec52d4ab9ea 100644
--- a/doc/lispref/variables.texi
+++ b/doc/lispref/variables.texi
@@ -8,20 +8,23 @@
8@cindex variable 8@cindex variable
9 9
10 A @dfn{variable} is a name used in a program to stand for a value. 10 A @dfn{variable} is a name used in a program to stand for a value.
11Nearly all programming languages have variables of some sort. In the 11In Lisp, each variable is represented by a Lisp symbol
12text of a Lisp program, variables are written using the syntax for 12(@pxref{Symbols}). The symbol's name serves as the variable name, and
13symbols. 13the symbol's value cell holds the variable's value@footnote{Strictly
14 14speaking, the symbol's value cell always holds the variable's current
15 In Lisp, unlike most programming languages, programs are represented 15value under the default @dfn{dynamic binding} rules. Under
16primarily as Lisp objects and only secondarily as text. The Lisp 16@dfn{lexical binding} rules, the value cell holds the variable's
17objects used for variables are symbols: the symbol name is the 17@dfn{global value}. @xref{Variable Scoping}, for details.}.
18variable name, and the variable's value is stored in the value cell of 18@xref{Symbol Components}.
19the symbol. The use of a symbol as a variable is independent of its 19
20use as a function name. @xref{Symbol Components}. 20 In Emacs Lisp, the use of a symbol as a variable is independent of
21 21its use as a function name.
22 The textual form of a Lisp program is given by the read syntax of 22
23the Lisp objects that constitute the program. Hence, a variable in a 23 As previously noted in this manual, a Lisp program is represented
24textual Lisp program is written using the read syntax for the symbol 24primarily by Lisp objects, and only secondarily as text. The textual
25form of a Lisp program is given by the read syntax of the Lisp objects
26that constitute the program. Hence, the textual form of a variable in
27a Lisp program is written using the read syntax for the symbol
25representing the variable. 28representing the variable.
26 29
27@menu 30@menu
@@ -145,63 +148,63 @@ does not raise an error if you actually change it.
145@cindex global binding 148@cindex global binding
146 149
147 Global variables have values that last until explicitly superseded 150 Global variables have values that last until explicitly superseded
148with new values. Sometimes it is useful to create variable values that 151with new values. Sometimes it is useful to give a variable a
149exist temporarily---only until a certain part of the program finishes. 152@dfn{local value}---a value that takes effect only within a certain
150These values are called @dfn{local}, and the variables so used are 153part of a Lisp program. When a variable has a local value, we say
151called @dfn{local variables}. 154that it has a @dfn{local binding}, or that it is a @dfn{local
152 155variable}.
153 For example, when a function is called, its argument variables receive 156
154new local values that last until the function exits. The @code{let} 157 For example, when a function is called, its argument variables
155special form explicitly establishes new local values for specified 158receive local values, which are the actual arguments supplied to the
156variables; these last until exit from the @code{let} form. 159function call; these local bindings take effect within the body of the
157 160function. To take another example, the @code{let} special form
158@cindex shadowing of variables 161explicitly establishes local bindings for specific variables, which
159 Establishing a local value saves away the variable's previous value 162take effect within the body of the @code{let} form.
160(or lack of one). We say that the previous value is @dfn{shadowed}
161and @dfn{not visible}. Both global and local values may be shadowed
162(@pxref{Scope}). After the life span of the local value is over, the
163previous value (or lack of one) is restored.
164
165 If you set a variable (such as with @code{setq}) while it is local,
166this replaces the local value; it does not alter the global value, or
167previous local values, that are shadowed. To model this behavior, we
168speak of a @dfn{local binding} of the variable as well as a local value.
169
170 The local binding is a conceptual place that holds a local value.
171Entering a function, or a special form such as @code{let}, creates the
172local binding; exiting the function or the @code{let} removes the
173local binding. While the local binding lasts, the variable's value is
174stored within it. Using @code{setq} or @code{set} while there is a
175local binding stores a different value into the local binding; it does
176not create a new binding.
177 163
178 We also speak of the @dfn{global binding}, which is where 164 We also speak of the @dfn{global binding}, which is where
179(conceptually) the global value is kept. 165(conceptually) the global value is kept.
180 166
167@cindex shadowing of variables
168 Establishing a local binding saves away the variable's previous
169value (or lack of one). We say that the previous value is
170@dfn{shadowed}. Both global and local values may be shadowed. If a
171local binding is in effect, using @code{setq} on the local variable
172stores the specified value in the local binding. When that local
173binding is no longer in effect, the previously shadowed value (or lack
174of one) comes back.
175
181@cindex current binding 176@cindex current binding
182 A variable can have more than one local binding at a time (for 177 A variable can have more than one local binding at a time (e.g.@: if
183example, if there are nested @code{let} forms that bind it). In such a 178there are nested @code{let} forms that bind the variable). The
184case, the most recently created local binding that still exists is the 179@dfn{current binding} is the local binding that is actually in effect.
185@dfn{current binding} of the variable. (This rule is called 180It determines the value returned by evaluating the variable symbol,
186@dfn{dynamic scoping}; see @ref{Variable Scoping}.) If there are no 181and it is the binding acted on by @code{setq}.
187local bindings, the variable's global binding is its current binding. 182
188We sometimes call the current binding the @dfn{most-local existing 183 For most purposes, you can think of the current binding as the
189binding}, for emphasis. Ordinary evaluation of a symbol always returns 184``innermost'' local binding, or the global binding if there is no
190the value of its current binding. 185local binding. To be more precise, a rule called the @dfn{scoping
191 186rule} determines where in a program a local binding takes effect. The
192 The special forms @code{let} and @code{let*} exist to create 187default scoping rule in Emacs Lisp is called @dfn{dynamic scoping},
193local bindings. 188which simply states that the current binding at any given point in the
189execution of a program is the most recently-created local binding for
190that variable that still exists. For details about dynamic scoping,
191and an alternative scoping rule called @dfn{lexical scoping},
192@xref{Variable Scoping}.
193
194 The special forms @code{let} and @code{let*} exist to create local
195bindings:
194 196
195@defspec let (bindings@dots{}) forms@dots{} 197@defspec let (bindings@dots{}) forms@dots{}
196This special form binds variables according to @var{bindings} and then 198This special form sets up local bindings for a certain set of
197evaluates all of the @var{forms} in textual order. The @code{let}-form 199variables, as specified by @var{bindings}, and then evaluates all of
198returns the value of the last form in @var{forms}. 200the @var{forms} in textual order. Its return value is the value of
201the last form in @var{forms}.
199 202
200Each of the @var{bindings} is either @w{(i) a} symbol, in which case 203Each of the @var{bindings} is either @w{(i) a} symbol, in which case
201that symbol is bound to @code{nil}; or @w{(ii) a} list of the form 204that symbol is locally bound to @code{nil}; or @w{(ii) a} list of the
202@code{(@var{symbol} @var{value-form})}, in which case @var{symbol} is 205form @code{(@var{symbol} @var{value-form})}, in which case
203bound to the result of evaluating @var{value-form}. If @var{value-form} 206@var{symbol} is locally bound to the result of evaluating
204is omitted, @code{nil} is used. 207@var{value-form}. If @var{value-form} is omitted, @code{nil} is used.
205 208
206All of the @var{value-form}s in @var{bindings} are evaluated in the 209All of the @var{value-form}s in @var{bindings} are evaluated in the
207order they appear and @emph{before} binding any of the symbols to them. 210order they appear and @emph{before} binding any of the symbols to them.
@@ -213,6 +216,7 @@ Here is an example of this: @code{z} is bound to the old value of
213(setq y 2) 216(setq y 2)
214 @result{} 2 217 @result{} 2
215@end group 218@end group
219
216@group 220@group
217(let ((y 1) 221(let ((y 1)
218 (z y)) 222 (z y))
@@ -226,15 +230,15 @@ Here is an example of this: @code{z} is bound to the old value of
226This special form is like @code{let}, but it binds each variable right 230This special form is like @code{let}, but it binds each variable right
227after computing its local value, before computing the local value for 231after computing its local value, before computing the local value for
228the next variable. Therefore, an expression in @var{bindings} can 232the next variable. Therefore, an expression in @var{bindings} can
229reasonably refer to the preceding symbols bound in this @code{let*} 233refer to the preceding symbols bound in this @code{let*} form.
230form. Compare the following example with the example above for 234Compare the following example with the example above for @code{let}.
231@code{let}.
232 235
233@example 236@example
234@group 237@group
235(setq y 2) 238(setq y 2)
236 @result{} 2 239 @result{} 2
237@end group 240@end group
241
238@group 242@group
239(let* ((y 1) 243(let* ((y 1)
240 (z y)) ; @r{Use the just-established value of @code{y}.} 244 (z y)) ; @r{Use the just-established value of @code{y}.}
@@ -262,7 +266,7 @@ Macro calls (@pxref{Macros}).
262Variables}); a few variables have terminal-local bindings 266Variables}); a few variables have terminal-local bindings
263(@pxref{Multiple Terminals}). These kinds of bindings work somewhat 267(@pxref{Multiple Terminals}). These kinds of bindings work somewhat
264like ordinary local bindings, but they are localized depending on 268like ordinary local bindings, but they are localized depending on
265``where'' you are in Emacs, rather than localized in time. 269``where'' you are in Emacs.
266 270
267@defopt max-specpdl-size 271@defopt max-specpdl-size
268@anchor{Definition of max-specpdl-size} 272@anchor{Definition of max-specpdl-size}
@@ -280,7 +284,7 @@ that Lisp avoids infinite recursion on an ill-defined function.
280@code{max-lisp-eval-depth} provides another limit on depth of nesting. 284@code{max-lisp-eval-depth} provides another limit on depth of nesting.
281@xref{Definition of max-lisp-eval-depth,, Eval}. 285@xref{Definition of max-lisp-eval-depth,, Eval}.
282 286
283The default value is 1000. Entry to the Lisp debugger increases the 287The default value is 1300. Entry to the Lisp debugger increases the
284value, if there is little room left, to make sure the debugger itself 288value, if there is little room left, to make sure the debugger itself
285has room to execute. 289has room to execute.
286@end defopt 290@end defopt
@@ -291,45 +295,32 @@ has room to execute.
291@cindex void variable 295@cindex void variable
292 296
293 If you have never given a symbol any value as a global variable, we 297 If you have never given a symbol any value as a global variable, we
294say that that symbol's global value is @dfn{void}. In other words, the 298say that that symbol's global value is @dfn{void}. Note that this
295symbol's value cell does not have any Lisp object in it. If you try to 299does @emph{not} mean the value is @code{nil}. The symbol @code{nil}
296evaluate the symbol, you get a @code{void-variable} error rather than 300is a Lisp object and can be the value of a variable, just as any other
297a value. 301object can be; but it is still a value.
298 302
299 Note that a value of @code{nil} is not the same as void. The symbol 303 More precisely, a variable is void if its symbol has an unassigned
300@code{nil} is a Lisp object and can be the value of a variable just as any 304value cell (@pxref{Symbol Components}). Under Emacs Lisp's default
301other object can be; but it is @emph{a value}. A void variable does not 305dynamic binding rules, the value cell stores the variable's current
302have any value. 306(local or global) value; if a variable is void, trying to evaluate the
303 307variable signals a @code{void-variable} error rather than a value.
304 After you have given a variable a value, you can make it void once more 308But when a variable is lexically bound, it can have a local value
305using @code{makunbound}. 309which is determined by the lexical environment, even if the value cell
310is empty and the variable is technically void. @xref{Variable
311Scoping}.
306 312
307@defun makunbound symbol 313@defun makunbound symbol
308This function makes the current variable binding of @var{symbol} void. 314This function empties out the value cell of @var{symbol}, making the
309Subsequent attempts to use this symbol's value as a variable will signal 315variable void. It returns @var{symbol}.
310the error @code{void-variable}, unless and until you set it again.
311 316
312@code{makunbound} returns @var{symbol}. 317If @var{symbol} has a (dynamic) local binding, @code{makunbound} voids
318the current binding, and this voidness lasts only as long as the local
319binding is in effect. Afterwards, the previously shadowed local or
320global binding is reexposed; then the variable will no longer be void,
321unless the reexposed binding is void too.
313 322
314@example 323Here are some examples (assuming dynamic binding is in effect):
315@group
316(makunbound 'x) ; @r{Make the global value of @code{x} void.}
317 @result{} x
318@end group
319@group
320x
321@error{} Symbol's value as variable is void: x
322@end group
323@end example
324
325If @var{symbol} is locally bound, @code{makunbound} affects the most
326local existing binding. This is the only way a symbol can have a void
327local binding, since all the constructs that create local bindings
328create them with values. In this case, the voidness lasts at most as
329long as the binding does; when the binding is removed due to exit from
330the construct that made it, the previous local or global binding is
331reexposed as usual, and the variable is no longer void unless the newly
332reexposed binding was void all along.
333 324
334@smallexample 325@smallexample
335@group 326@group
@@ -361,17 +352,11 @@ x ; @r{The global binding is unchanged.}
361@end smallexample 352@end smallexample
362@end defun 353@end defun
363 354
364 A variable that has been made void with @code{makunbound} is
365indistinguishable from one that has never received a value and has
366always been void.
367
368 You can use the function @code{boundp} to test whether a variable is
369currently void.
370
371@defun boundp variable 355@defun boundp variable
372@code{boundp} returns @code{t} if @var{variable} (a symbol) is not void; 356This function returns @code{t} if @var{variable} (a symbol) is not
373more precisely, if its current binding is not void. It returns 357void, and @code{nil} if it is void.
374@code{nil} otherwise. 358
359Here are some examples (assuming dynamic binding is in effect):
375 360
376@smallexample 361@smallexample
377@group 362@group
@@ -402,52 +387,41 @@ more precisely, if its current binding is not void. It returns
402@section Defining Global Variables 387@section Defining Global Variables
403@cindex variable definition 388@cindex variable definition
404 389
405 You may announce your intention to use a symbol as a global variable 390 A @dfn{variable definition} is a construct that announces your
406with a @dfn{variable definition}: a special form, either @code{defconst} 391intention to use a symbol as a global variable. It uses the special
407or @code{defvar}. 392forms @code{defvar} or @code{defconst}, which are documented below.
408 393
409 In Emacs Lisp, definitions serve three purposes. First, they inform 394 A variable definition serves three purposes. First, it informs
410people who read the code that certain symbols are @emph{intended} to be 395people who read the code that the symbol is @emph{intended} to be used
411used a certain way (as variables). Second, they inform the Lisp system 396a certain way (as a variable). Second, it informs the Lisp system of
412of these things, supplying a value and documentation. Third, they 397this, optionally supplying an initial value and a documentation
413provide information to utilities such as @code{etags} and 398string. Third, it provides information to programming tools such as
414@code{make-docfile}, which create data bases of the functions and 399@command{etags}, allowing them to find where the variable was defined.
415variables in a program. 400
416 401 The difference between @code{defconst} and @code{defvar} is mainly a
417 The difference between @code{defconst} and @code{defvar} is primarily 402matter of intent, serving to inform human readers of whether the value
418a matter of intent, serving to inform human readers of whether the value 403should ever change. Emacs Lisp does not actually prevent you from
419should ever change. Emacs Lisp does not restrict the ways in which a 404changing the value of a variable defined with @code{defconst}. One
420variable can be used based on @code{defconst} or @code{defvar} 405notable difference between the two forms is that @code{defconst}
421declarations. However, it does make a difference for initialization: 406unconditionally initializes the variable, whereas @code{defvar}
422@code{defconst} unconditionally initializes the variable, while 407initializes it only if it is originally void.
423@code{defvar} initializes it only if it is void. 408
424 409 To define a customizable variable, you should use @code{defcustom}
425@ignore 410(which calls @code{defvar} as a subroutine). @xref{Customization}.
426 One would expect user option variables to be defined with
427@code{defconst}, since programs do not change them. Unfortunately, this
428has bad results if the definition is in a library that is not preloaded:
429@code{defconst} would override any prior value when the library is
430loaded. Users would like to be able to set user options in their init
431files, and override the default values given in the definitions. For
432this reason, user options must be defined with @code{defvar}.
433@end ignore
434 411
435@defspec defvar symbol [value [doc-string]] 412@defspec defvar symbol [value [doc-string]]
436This special form defines @var{symbol} as a variable and can also 413This special form defines @var{symbol} as a variable. Note that
437initialize and document it. The definition informs a person reading 414@var{symbol} is not evaluated; the symbol to be defined should appear
438your code that @var{symbol} is used as a variable that might be set or 415explicitly in the @code{defvar} form. The variable is marked as
439changed. It also declares this variable as @dfn{special}, meaning that it 416@dfn{special}, meaning that it should always be dynamically bound
440should always use dynamic scoping rules. Note that @var{symbol} is not 417(@pxref{Variable Scoping}).
441evaluated; the symbol to be defined must appear explicitly in the
442@code{defvar}.
443 418
444If @var{symbol} is void and @var{value} is specified, @code{defvar} 419If @var{symbol} is void and @var{value} is specified, @code{defvar}
445evaluates it and sets @var{symbol} to the result. But if @var{symbol} 420evaluates @var{value} and sets @var{symbol} to the result. But if
446already has a value (i.e., it is not void), @var{value} is not even 421@var{symbol} already has a value (i.e.@: it is not void), @var{value}
447evaluated, and @var{symbol}'s value remains unchanged. 422is not even evaluated, and @var{symbol}'s value remains unchanged. If
448If @var{value} is omitted, the value of @var{symbol} is not changed in any 423@var{value} is omitted, the value of @var{symbol} is not changed in
449case; instead, the only effect of @code{defvar} is to declare locally that this 424any case.
450variable exists elsewhere and should hence always use dynamic scoping rules.
451 425
452If @var{symbol} has a buffer-local binding in the current buffer, 426If @var{symbol} has a buffer-local binding in the current buffer,
453@code{defvar} operates on the default value, which is buffer-independent, 427@code{defvar} operates on the default value, which is buffer-independent,
@@ -459,19 +433,9 @@ Emacs Lisp mode (@code{eval-defun}), a special feature of
459@code{eval-defun} arranges to set the variable unconditionally, without 433@code{eval-defun} arranges to set the variable unconditionally, without
460testing whether its value is void. 434testing whether its value is void.
461 435
462If the @var{doc-string} argument appears, it specifies the documentation 436If the @var{doc-string} argument is supplied, it specifies the
463for the variable. (This opportunity to specify documentation is one of 437documentation string for the variable (stored in the symbol's
464the main benefits of defining the variable.) The documentation is 438@code{variable-documentation} property). @xref{Documentation}.
465stored in the symbol's @code{variable-documentation} property. The
466Emacs help functions (@pxref{Documentation}) look for this property.
467
468If the documentation string begins with the character @samp{*}, Emacs
469allows users to set it interactively using the @code{set-variable}
470command. However, you should nearly always use @code{defcustom}
471instead of @code{defvar} to define such variables, so that users can
472use @kbd{M-x customize} and related commands to set them. In that
473case, it is not necessary to begin the documentation string with
474@samp{*}. @xref{Customization}.
475 439
476Here are some examples. This form defines @code{foo} but does not 440Here are some examples. This form defines @code{foo} but does not
477initialize it: 441initialize it:
@@ -494,38 +458,6 @@ it a documentation string:
494@end group 458@end group
495@end example 459@end example
496 460
497The following form changes the documentation string for @code{bar},
498making it a user option, but does not change the value, since @code{bar}
499already has a value. (The addition @code{(1+ nil)} would get an error
500if it were evaluated, but since it is not evaluated, there is no error.)
501
502@example
503@group
504(defvar bar (1+ nil)
505 "*The normal weight of a bar.")
506 @result{} bar
507@end group
508@group
509bar
510 @result{} 23
511@end group
512@end example
513
514Here is an equivalent expression for the @code{defvar} special form:
515
516@example
517@group
518(defvar @var{symbol} @var{value} @var{doc-string})
519@equiv{}
520(progn
521 (if (not (boundp '@var{symbol}))
522 (setq @var{symbol} @var{value}))
523 (if '@var{doc-string}
524 (put '@var{symbol} 'variable-documentation '@var{doc-string}))
525 '@var{symbol})
526@end group
527@end example
528
529The @code{defvar} form returns @var{symbol}, but it is normally used 461The @code{defvar} form returns @var{symbol}, but it is normally used
530at top level in a file where its value does not matter. 462at top level in a file where its value does not matter.
531@end defspec 463@end defspec
@@ -538,6 +470,11 @@ global value, established here, that should not be changed by the user
538or by other programs. Note that @var{symbol} is not evaluated; the 470or by other programs. Note that @var{symbol} is not evaluated; the
539symbol to be defined must appear explicitly in the @code{defconst}. 471symbol to be defined must appear explicitly in the @code{defconst}.
540 472
473The @code{defconst} form, like @code{defvar}, marks the variable as
474@dfn{special}, meaning that it should always be dynamically bound
475(@pxref{Variable Scoping}). In addition, it marks the variable as
476risky (@pxref{File Local Variables}).
477
541@code{defconst} always evaluates @var{value}, and sets the value of 478@code{defconst} always evaluates @var{value}, and sets the value of
542@var{symbol} to the result. If @var{symbol} does have a buffer-local 479@var{symbol} to the result. If @var{symbol} does have a buffer-local
543binding in the current buffer, @code{defconst} sets the default value, 480binding in the current buffer, @code{defconst} sets the default value,
@@ -567,37 +504,13 @@ float-pi
567@end example 504@end example
568@end defspec 505@end defspec
569 506
570@defun user-variable-p variable 507 @strong{Warning:} If you use a @code{defconst} or @code{defvar}
571@cindex user option 508special form while the variable has a local binding (made with
572This function returns @code{t} if @var{variable} is a user option---a 509@code{let}, or a function argument), it sets the local binding rather
573variable intended to be set by the user for customization---and 510than the global binding. This is not what you usually want. To
574@code{nil} otherwise. (Variables other than user options exist for the 511prevent this, use these special forms at top level in a file, where
575internal purposes of Lisp programs, and users need not know about them.) 512normally no local binding is in effect, and make sure to load the file
576 513before making a local binding for the variable.
577User option variables are distinguished from other variables either
578though being declared using @code{defcustom}@footnote{They may also be
579declared equivalently in @file{cus-start.el}.} or by the first character
580of their @code{variable-documentation} property. If the property exists
581and is a string, and its first character is @samp{*}, then the variable
582is a user option. Aliases of user options are also user options.
583@end defun
584
585@cindex @code{variable-interactive} property
586@findex set-variable
587 If a user option variable has a @code{variable-interactive} property,
588the @code{set-variable} command uses that value to control reading the
589new value for the variable. The property's value is used as if it were
590specified in @code{interactive} (@pxref{Using Interactive}). However,
591this feature is largely obsoleted by @code{defcustom}
592(@pxref{Customization}).
593
594 @strong{Warning:} If the @code{defconst} and @code{defvar} special
595forms are used while the variable has a local binding (made with
596@code{let}, or a function argument), they set the local-binding's
597value; the top-level binding is not changed. This is not what you
598usually want. To prevent it, use these special forms at top level in
599a file, where normally no local binding is in effect, and make sure to
600load the file before making a local binding for the variable.
601 514
602@node Tips for Defining 515@node Tips for Defining
603@section Tips for Defining Variables Robustly 516@section Tips for Defining Variables Robustly
@@ -667,9 +580,9 @@ loading the file, the variable is either still uninitialized or
667initialized properly, never in-between. If it is still uninitialized, 580initialized properly, never in-between. If it is still uninitialized,
668reloading the file will initialize it properly. Second, reloading the 581reloading the file will initialize it properly. Second, reloading the
669file once the variable is initialized will not alter it; that is 582file once the variable is initialized will not alter it; that is
670important if the user has run hooks to alter part of the contents (such 583important if the user has run hooks to alter part of the contents
671as, to rebind keys). Third, evaluating the @code{defvar} form with 584(such as, to rebind keys). Third, evaluating the @code{defvar} form
672@kbd{C-M-x} @emph{will} reinitialize the map completely. 585with @kbd{C-M-x} will reinitialize the map completely.
673 586
674 Putting so much code in the @code{defvar} form has one disadvantage: 587 Putting so much code in the @code{defvar} form has one disadvantage:
675it puts the documentation string far away from the line which names the 588it puts the documentation string far away from the line which names the
@@ -690,37 +603,27 @@ This has all the same advantages as putting the initialization inside
690the @code{defvar}, except that you must type @kbd{C-M-x} twice, once on 603the @code{defvar}, except that you must type @kbd{C-M-x} twice, once on
691each form, if you do want to reinitialize the variable. 604each form, if you do want to reinitialize the variable.
692 605
693 But be careful not to write the code like this:
694
695@example
696(defvar my-mode-map nil
697 @var{docstring})
698(unless my-mode-map
699 (setq my-mode-map (make-sparse-keymap))
700 (define-key my-mode-map "\C-c\C-a" 'my-command)
701 @dots{})
702@end example
703
704@noindent
705This code sets the variable, then alters it, but it does so in more than
706one step. If the user quits just after the @code{setq}, that leaves the
707variable neither correctly initialized nor void nor @code{nil}. Once
708that happens, reloading the file will not initialize the variable; it
709will remain incomplete.
710
711@node Accessing Variables 606@node Accessing Variables
712@section Accessing Variable Values 607@section Accessing Variable Values
713 608
714 The usual way to reference a variable is to write the symbol which 609 The usual way to reference a variable is to write the symbol which
715names it (@pxref{Symbol Forms}). This requires you to specify the 610names it. @xref{Symbol Forms}.
716variable name when you write the program. Usually that is exactly what 611
717you want to do. Occasionally you need to choose at run time which 612 Occasionally, you may want to reference a variable which is only
718variable to reference; then you can use @code{symbol-value}. 613determined at run time. In that case, you cannot specify the variable
614name in the text of the program. You can use the @code{symbol-value}
615function to extract the value.
719 616
720@defun symbol-value symbol 617@defun symbol-value symbol
721This function returns the value of @var{symbol}. This is the value in 618This function returns the value of @var{symbol}. This is the value in
722the innermost local binding of the symbol, or its global value if it 619the symbol's value cell, which is where the variable's current
723has no local bindings. 620(dynamic) value is stored. If the variable has no local binding, this
621is simply its global value.
622
623If the variable is lexically bound, the value reported by
624@code{symbol-value} is the dynamic value, and not the local lexical
625value (which is determined by the lexical environment rather than the
626symbol's value cell). @xref{Variable Scoping}.
724 627
725@example 628@example
726@group 629@group
@@ -755,12 +658,12 @@ has no local bindings.
755@end group 658@end group
756@end example 659@end example
757 660
758A @code{void-variable} error is signaled if the current binding of 661A @code{void-variable} error is signaled if @var{symbol} is void as a
759@var{symbol} is void. 662variable.
760@end defun 663@end defun
761 664
762@node Setting Variables 665@node Setting Variables
763@section How to Alter a Variable Value 666@section Setting Variable Values
764 667
765 The usual way to change the value of a variable is with the special 668 The usual way to change the value of a variable is with the special
766form @code{setq}. When you need to compute the choice of variable at 669form @code{setq}. When you need to compute the choice of variable at
@@ -769,8 +672,8 @@ run time, use the function @code{set}.
769@defspec setq [symbol form]@dots{} 672@defspec setq [symbol form]@dots{}
770This special form is the most common method of changing a variable's 673This special form is the most common method of changing a variable's
771value. Each @var{symbol} is given a new value, which is the result of 674value. Each @var{symbol} is given a new value, which is the result of
772evaluating the corresponding @var{form}. The most-local existing 675evaluating the corresponding @var{form}. The current binding of the
773binding of the symbol is changed. 676symbol is changed.
774 677
775@code{setq} does not evaluate @var{symbol}; it sets the symbol that you 678@code{setq} does not evaluate @var{symbol}; it sets the symbol that you
776write. We say that this argument is @dfn{automatically quoted}. The 679write. We say that this argument is @dfn{automatically quoted}. The
@@ -809,12 +712,17 @@ second @var{symbol} is set, and so on:
809@end defspec 712@end defspec
810 713
811@defun set symbol value 714@defun set symbol value
812This function sets @var{symbol}'s value to @var{value}, then returns 715This function puts @var{value} in the value cell of @var{symbol}.
813@var{value}. Since @code{set} is a function, the expression written for 716Since it is a function rather than a special form, the expression
814@var{symbol} is evaluated to obtain the symbol to set. 717written for @var{symbol} is evaluated to obtain the symbol to set.
815 718The return value is @var{value}.
816The most-local existing binding of the variable is the binding that is 719
817set; shadowed bindings are not affected. 720When dynamic variable binding is in effect (the default), @code{set}
721has the same effect as @code{setq}, apart from the fact that
722@code{set} evaluates its @var{symbol} argument whereas @code{setq}
723does not. But when a variable is lexically bound, @code{set} affects
724its @emph{dynamic} value, whereas @code{setq} affects its current
725(lexical) value. @xref{Variable Scoping}.
818 726
819@example 727@example
820@group 728@group
@@ -854,327 +762,337 @@ error is signaled.
854(set '(x y) 'z) 762(set '(x y) 'z)
855@error{} Wrong type argument: symbolp, (x y) 763@error{} Wrong type argument: symbolp, (x y)
856@end example 764@end example
857
858Logically speaking, @code{set} is a more fundamental primitive than
859@code{setq}. Any use of @code{setq} can be trivially rewritten to use
860@code{set}; @code{setq} could even be defined as a macro, given the
861availability of @code{set}. However, @code{set} itself is rarely used;
862beginners hardly need to know about it. It is useful only for choosing
863at run time which variable to set. For example, the command
864@code{set-variable}, which reads a variable name from the user and then
865sets the variable, needs to use @code{set}.
866
867@cindex CL note---@code{set} local
868@quotation
869@b{Common Lisp note:} In Common Lisp, @code{set} always changes the
870symbol's ``special'' or dynamic value, ignoring any lexical bindings.
871In Emacs Lisp, all variables and all bindings are dynamic, so @code{set}
872always affects the most local existing binding.
873@end quotation
874@end defun 765@end defun
875 766
876@node Variable Scoping 767@node Variable Scoping
877@section Scoping Rules for Variable Bindings 768@section Scoping Rules for Variable Bindings
878 769
879 A given symbol @code{foo} can have several local variable bindings, 770 When you create a local binding for a variable, that binding takes
880established at different places in the Lisp program, as well as a global 771effect only within a limited portion of the program (@pxref{Local
881binding. The most recently established binding takes precedence over 772Variables}). This section describes exactly what this means.
882the others.
883 773
884@cindex scope 774@cindex scope
885@cindex extent 775@cindex extent
886@cindex dynamic scoping 776 Each local binding has a certain @dfn{scope} and @dfn{extent}.
887@cindex lexical scoping 777@dfn{Scope} refers to @emph{where} in the textual source code the
888 By default, local bindings in Emacs Lisp have @dfn{indefinite scope} and 778binding can be accessed. @dfn{Extent} refers to @emph{when}, as the
889@dfn{dynamic extent}. @dfn{Scope} refers to @emph{where} textually in 779program is executing, the binding exists.
890the source code the binding can be accessed. ``Indefinite scope'' means 780
891that any part of the program can potentially access the variable 781@cindex dynamic binding
892binding. @dfn{Extent} refers to @emph{when}, as the program is 782@cindex indefinite scope
893executing, the binding exists. ``Dynamic extent'' means that the binding 783@cindex dynamic extent
894lasts as long as the activation of the construct that established it. 784 By default, the local bindings that Emacs creates are @dfn{dynamic
895 785bindings}. Such a binding has @dfn{indefinite scope}, meaning that
896 The combination of dynamic extent and indefinite scope is called 786any part of the program can potentially access the variable binding.
897@dfn{dynamic scoping}. By contrast, most programming languages use 787It also has @dfn{dynamic extent}, meaning that the binding lasts only
898@dfn{lexical scoping}, in which references to a local variable must be 788while the binding construct (such as the body of a @code{let} form) is
899located textually within the function or block that binds the variable. 789being executed.
900Emacs can also support lexical scoping, upon request (@pxref{Lexical 790
901Binding}). 791@cindex lexical binding
902 792@cindex lexical scope
903@cindex CL note---special variables 793@cindex indefinite extent
904@quotation 794 Emacs can optionally create @dfn{lexical bindings}. A lexical
905@b{Common Lisp note:} Variables declared ``special'' in Common Lisp are 795binding has @dfn{lexical scope}, meaning that any reference to the
906dynamically scoped, like all variables in Emacs Lisp. 796variable must be located textually within the binding construct. It
907@end quotation 797also has @dfn{indefinite extent}, meaning that under some
798circumstances the binding can live on even after the binding construct
799has finished executing, by means of special objects called
800@dfn{closures}.
801
802 The following subsections describe dynamic binding and lexical
803binding in greater detail, and how to enable lexical binding in Emacs
804Lisp programs.
908 805
909@menu 806@menu
910* Scope:: Scope means where in the program a value is visible. 807* Dynamic Binding:: The default for binding local variables in Emacs.
911 Comparison with other languages. 808* Dynamic Binding Tips:: Avoiding problems with dynamic binding.
912* Extent:: Extent means how long in time a value exists. 809* Lexical Binding:: A different type of local variable binding.
913* Impl of Scope:: Two ways to implement dynamic scoping. 810* Using Lexical Binding:: How to enable lexical binding.
914* Using Scoping:: How to use dynamic scoping carefully and avoid problems.
915* Lexical Binding:: Use of lexical scoping.
916@end menu 811@end menu
917 812
918@node Scope 813@node Dynamic Binding
919@subsection Scope 814@subsection Dynamic Binding
920 815
921 Emacs Lisp uses @dfn{indefinite scope} for local variable bindings. 816 By default, the local variable bindings made by Emacs are dynamic
922This means that any function anywhere in the program text might access a 817bindings. When a variable is dynamically bound, its current binding
923given binding of a variable. Consider the following function 818at any point in the execution of the Lisp program is simply the most
924definitions: 819recently-created dynamic local binding for that symbol, or the global
820binding if there is no such local binding.
821
822 Dynamic bindings have indefinite scope and dynamic extent, as shown
823by the following example:
925 824
926@example 825@example
927@group 826@group
928(defun binder (x) ; @r{@code{x} is bound in @code{binder}.} 827(defvar x -99) ; @r{@code{x} receives an initial value of -99.}
929 (foo 5)) ; @r{@code{foo} is some other function.}
930@end group
931 828
932@group 829(defun getx ()
933(defun user () ; @r{@code{x} is used ``free'' in @code{user}.} 830 x) ; @r{@code{x} is used ``free'' in this function.}
934 (list x)) 831
832(let ((x 1)) ; @r{@code{x} is dynamically bound.}
833 (getx))
834 @result{} 1
835
836;; @r{After the @code{let} form finishes, @code{x} reverts to its}
837;; @r{previous value, which is -99.}
838
839(getx)
840 @result{} -99
935@end group 841@end group
936@end example 842@end example
937 843
938 In a lexically scoped language, the binding of @code{x} in 844@noindent
939@code{binder} would never be accessible in @code{user}, because 845The function @code{getx} refers to @code{x}. This is a ``free''
940@code{user} is not textually contained within the function 846reference, in the sense that there is no binding for @code{x} within
941@code{binder}. However, in dynamically-scoped Emacs Lisp, @code{user} 847that @code{defun} construct itself. When we call @code{getx} from
942may or may not refer to the binding of @code{x} established in 848within a @code{let} form in which @code{x} is (dynamically) bound, it
943@code{binder}, depending on the circumstances: 849retrieves the local value of @code{x} (i.e.@: 1). But when we call
944 850@code{getx} outside the @code{let} form, it retrieves the global value
945@itemize @bullet 851of @code{x} (i.e.@: -99).
946@item
947If we call @code{user} directly without calling @code{binder} at all,
948then whatever binding of @code{x} is found, it cannot come from
949@code{binder}.
950 852
951@item 853 Here is another example, which illustrates setting a dynamically
952If we define @code{foo} as follows and then call @code{binder}, then the 854bound variable using @code{setq}:
953binding made in @code{binder} will be seen in @code{user}:
954 855
955@example 856@example
956@group 857@group
957(defun foo (lose) 858(defvar x -99) ; @r{@code{x} receives an initial value of -99.}
958 (user)) 859
860(defun addx ()
861 (setq x (1+ x))) ; @r{Add 1 to @code{x} and return its new value.}
862
863(let ((x 1))
864 (addx)
865 (addx))
866 @result{} 3 ; @r{The two @code{addx} calls add to @code{x} twice.}
867
868;; @r{After the @code{let} form finishes, @code{x} reverts to its}
869;; @r{previous value, which is -99.}
870
871(addx)
872 @result{} -98
959@end group 873@end group
960@end example 874@end example
961 875
962@item 876 Dynamic binding is implemented in Emacs Lisp in a simple way. Each
963However, if we define @code{foo} as follows and then call @code{binder}, 877symbol has a value cell, which specifies its current dynamic value (or
964then the binding made in @code{binder} @emph{will not} be seen in 878absence of value). @xref{Symbol Components}. When a symbol is given
965@code{user}: 879a dynamic local binding, Emacs records the contents of the value cell
880(or absence thereof) in a stack, and stores the new local value in the
881value cell. When the binding construct finishes executing, Emacs pops
882the old value off the stack, and puts it in the value cell.
966 883
967@example 884@node Dynamic Binding Tips
968(defun foo (x) 885@subsection Proper Use of Dynamic Binding
969 (user))
970@end example
971 886
972@noindent 887 Dynamic binding is a powerful feature, as it allows programs to
973Here, when @code{foo} is called by @code{binder}, it binds @code{x}. 888refer to variables that are not defined within their local textual
974(The binding in @code{foo} is said to @dfn{shadow} the one made in 889scope. However, if used without restraint, this can also make
975@code{binder}.) Therefore, @code{user} will access the @code{x} bound 890programs hard to understand. There are two clean ways to use this
976by @code{foo} instead of the one bound by @code{binder}. 891technique:
977@end itemize
978 892
979Emacs Lisp used dynamic scoping by default because simple implementations of 893@itemize @bullet
980lexical scoping are slow. In addition, every Lisp system needs to offer 894@item
981dynamic scoping at least as an option; if lexical scoping is the norm, there 895If a variable has no global definition, use it as a local variable
982must be a way to specify dynamic scoping instead for a particular variable. 896only within a binding construct, e.g.@: the body of the @code{let}
983Nowadays, Emacs offers both, but the default is still to use exclusively 897form where the variable was bound, or the body of the function for an
984dynamic scoping. 898argument variable. If this convention is followed consistently
985 899throughout a program, the value of the variable will not affect, nor
986@node Extent 900be affected by, any uses of the same variable symbol elsewhere in the
987@subsection Extent 901program.
988 902
989 @dfn{Extent} refers to the time during program execution that a 903@item
990variable name is valid. In Emacs Lisp, a variable is valid only while 904Otherwise, define the variable with @code{defvar}, @code{defconst}, or
991the form that bound it is executing. This is called @dfn{dynamic 905@code{defcustom}. @xref{Defining Variables}. Usually, the definition
992extent}. ``Local'' or ``automatic'' variables in most languages, 906should be at top-level in an Emacs Lisp file. As far as possible, it
993including C and Pascal, have dynamic extent. 907should include a documentation string which explains the meaning and
994 908purpose of the variable. You should also choose the variable's name
995 One alternative to dynamic extent is @dfn{indefinite extent}. This 909to avoid name conflicts (@pxref{Coding Conventions}).
996means that a variable binding can live on past the exit from the form 910
997that made the binding. Common Lisp and Scheme, for example, support 911Then you can bind the variable anywhere in a program, knowing reliably
998this, but Emacs Lisp does not. 912what the effect will be. Wherever you encounter the variable, it will
999 913be easy to refer back to the definition, e.g.@: via the @kbd{C-h v}
1000 To illustrate this, the function below, @code{make-add}, returns a 914command (provided the variable definition has been loaded into Emacs).
1001function that purports to add @var{n} to its own argument @var{m}. This 915@xref{Name Help,,, emacs, The GNU Emacs Manual}.
1002would work in Common Lisp, but it does not do the job in Emacs Lisp, 916
1003because after the call to @code{make-add} exits, the variable @code{n} 917For example, it is common to use local bindings for customizable
1004is no longer bound to the actual argument 2. 918variables like @code{case-fold-search}:
1005 919
1006@example 920@example
1007(defun make-add (n) 921@group
1008 (function (lambda (m) (+ n m)))) ; @r{Return a function.} 922(defun search-for-abc ()
1009 @result{} make-add 923 "Search for the string \"abc\", ignoring case differences."
1010(fset 'add2 (make-add 2)) ; @r{Define function @code{add2}} 924 (let ((case-fold-search nil))
1011 ; @r{with @code{(make-add 2)}.} 925 (re-search-forward "abc")))
1012 @result{} (lambda (m) (+ n m)) 926@end group
1013(add2 4) ; @r{Try to add 2 to 4.}
1014@error{} Symbol's value as variable is void: n
1015@end example 927@end example
928@end itemize
1016 929
1017@cindex closures not available 930@node Lexical Binding
1018 Some Lisp dialects have ``closures,'' objects that are like functions 931@subsection Lexical Binding
1019but record additional variable bindings. Emacs Lisp does not have
1020closures.
1021 932
1022@node Impl of Scope 933Optionally, you can create lexical bindings in Emacs Lisp. A
1023@subsection Implementation of Dynamic Scoping 934lexically bound variable has @dfn{lexical scope}, meaning that any
1024@cindex deep binding 935reference to the variable must be located textually within the binding
936construct.
1025 937
1026 A simple sample implementation (which is not how Emacs Lisp actually 938 Here is an example
1027works) may help you understand dynamic binding. This technique is 939@iftex
1028called @dfn{deep binding} and was used in early Lisp systems. 940(see the next subsection, for how to actually enable lexical binding):
941@end iftex
942@ifnottex
943(@pxref{Using Lexical Binding}, for how to actually enable lexical binding):
944@end ifnottex
1029 945
1030 Suppose there is a stack of bindings, which are variable-value pairs. 946@example
1031At entry to a function or to a @code{let} form, we can push bindings 947@group
1032onto the stack for the arguments or local variables created there. We 948(defun getx ()
1033can pop those bindings from the stack at exit from the binding 949 x) ; @r{@code{x} is used ``free'' in this function.}
1034construct.
1035 950
1036 We can find the value of a variable by searching the stack from top to 951(let ((x 1)) ; @r{@code{x} is lexically bound.}
1037bottom for a binding for that variable; the value from that binding is 952 (+ x 3))
1038the value of the variable. To set the variable, we search for the 953 @result{} 4
1039current binding, then store the new value into that binding.
1040
1041 As you can see, a function's bindings remain in effect as long as it
1042continues execution, even during its calls to other functions. That is
1043why we say the extent of the binding is dynamic. And any other function
1044can refer to the bindings, if it uses the same variables while the
1045bindings are in effect. That is why we say the scope is indefinite.
1046
1047@cindex shallow binding
1048 The actual implementation of variable scoping in GNU Emacs Lisp uses a
1049technique called @dfn{shallow binding}. Each variable has a standard
1050place in which its current value is always found---the value cell of the
1051symbol.
1052
1053 In shallow binding, setting the variable works by storing a value in
1054the value cell. Creating a new binding works by pushing the old value
1055(belonging to a previous binding) onto a stack, and storing the new
1056local value in the value cell. Eliminating a binding works by popping
1057the old value off the stack, into the value cell.
1058
1059 We use shallow binding because it has the same results as deep
1060binding, but runs faster, since there is never a need to search for a
1061binding.
1062 954
1063@node Using Scoping 955(let ((x 1)) ; @r{@code{x} is lexically bound.}
1064@subsection Proper Use of Dynamic Scoping 956 (getx))
957@error{} Symbol's value as variable is void: x
958@end group
959@end example
1065 960
1066 Binding a variable in one function and using it in another is a 961@noindent
1067powerful technique, but if used without restraint, it can make programs 962Here, the variable @code{x} has no global value. When it is lexically
1068hard to understand. There are two clean ways to use this technique: 963bound within a @code{let} form, it can be used in the textual confines
964of that @code{let} form. But it can @emph{not} be used from within a
965@code{getx} function called from the @code{let} form, since the
966function definition of @code{getx} occurs outside the @code{let} form
967itself.
968
969@cindex lexical environment
970 Here is how lexical binding works. Each binding construct defines a
971@dfn{lexical environment}, specifying the symbols that are bound
972within the construct and their local values. When the Lisp evaluator
973wants the current value of a variable, it looks first in the lexical
974environment; if the variable is not specified in there, it looks in
975the symbol's value cell, where the dynamical value is stored.
976
977@cindex closures
978 Lexical bindings have indefinite extent. Even after a binding
979construct has finished executing, its lexical environment can be
980``kept around'' in Lisp objects called @dfn{closures}. A closure is
981created whenever you evaluate a lambda expression (@pxref{Lambda
982Expressions}) with lexical binding enabled. It is represented by a
983list whose @sc{car} is the symbol @code{closure}. It is a function,
984in the sense that it can be passed as an argument to @code{funcall};
985when called as a function, any lexical variable references within its
986definition will use the retained lexical environment.
987
988 Here is an example which illustrates the use of a closure:
1069 989
1070@itemize @bullet 990@example
1071@item 991(defvar my-ticker nil) ; @r{We will use this dynamically bound}
1072Use or bind the variable only in a few related functions, written close 992 ; @r{variable to store a closure.}
1073together in one file. Such a variable is used for communication within
1074one program.
1075 993
1076You should write comments to inform other programmers that they can see 994(let ((x 0)) ; @r{@code{x} is lexically bound.}
1077all uses of the variable before them, and to advise them not to add uses 995 (setq my-ticker (lambda ()
1078elsewhere. 996 (setq x (1+ x)))))
997 @result{} (closure ((x . 0) t) ()
998 (1+ x))
1079 999
1080@item 1000(funcall my-ticker)
1081Give the variable a well-defined, documented meaning, and make all 1001 @result{} 1
1082appropriate functions refer to it (but not bind it or set it) wherever
1083that meaning is relevant. For example, the variable
1084@code{case-fold-search} is defined as ``non-@code{nil} means ignore case
1085when searching''; various search and replace functions refer to it
1086directly or through their subroutines, but do not bind or set it.
1087
1088Then you can bind the variable in other programs, knowing reliably what
1089the effect will be.
1090@end itemize
1091 1002
1092 In either case, you should define the variable with @code{defvar}. 1003(funcall my-ticker)
1093This helps other people understand your program by telling them to look 1004 @result{} 2
1094for inter-function usage. It also avoids a warning from the byte
1095compiler. Choose the variable's name to avoid name conflicts---don't
1096use short names like @code{x}.
1097 1005
1006(funcall my-ticker)
1007 @result{} 3
1098 1008
1099@node Lexical Binding 1009x ; @r{Note that @code{x} has no global value.}
1100@subsection Use of Lexical Scoping 1010@error{} Symbol's value as variable is void: x
1011@end example
1101 1012
1102Emacs Lisp can be evaluated in two different modes: in dynamic binding 1013@noindent
1103mode or lexical binding mode. In dynamic binding mode, all local 1014The @code{let} binding defines a lexical environment in which the
1104variables use dynamic scoping, whereas in lexical binding mode 1015variable @code{x} is locally bound to 0. Within this binding
1105variables that have been declared @dfn{special} (i.e., declared with 1016construct, we define a lambda expression which increments @code{x} by
1106@code{defvar}, @code{defcustom} or @code{defconst}) use dynamic 1017one and returns the incremented value. This lambda expression is
1107scoping and all others use lexical scoping. 1018automatically turned into a closure, in which the lexical environment
1019lives on even after the @code{let} binding construct has exited. Each
1020time we evaluate the closure, it increments @code{x}, using the
1021binding of @code{x} in that lexical environment.
1022
1023 Note that functions like @code{symbol-value}, @code{boundp}, and
1024@code{set} only retrieve or modify a variable's dynamic binding
1025(i.e.@: the contents of its symbol's value cell). Also, the code in
1026the body of a @code{defun} or @code{defmacro} cannot refer to
1027surrounding lexical variables.
1028
1029 Currently, lexical binding is not much used within the Emacs
1030sources. However, we expect its importance to increase in the future.
1031Lexical binding opens up a lot more opportunities for optimization, so
1032Emacs Lisp code that makes use of lexical binding is likely to run
1033faster in future Emacs versions. Such code is also much more friendly
1034to concurrency, which we want to add to Emacs in the near future.
1035
1036@node Using Lexical Binding
1037@subsection Using Lexical Binding
1038
1039 When loading an Emacs Lisp file or evaluating a Lisp buffer, lexical
1040binding is enabled if the buffer-local variable @code{lexical-binding}
1041is non-@code{nil}:
1108 1042
1109@defvar lexical-binding 1043@defvar lexical-binding
1110When non-nil, evaluation of Lisp code uses lexical scoping for non-special 1044If this buffer-local variable is non-@code{nil}, Emacs Lisp files and
1111local variables instead of dynamic scoping. If nil, dynamic scoping is used 1045buffers are evaluated using lexical binding instead of dynamic
1112for all local variables. This variable is typically set for a whole Elisp file 1046binding. (However, special variables are still dynamically bound; see
1113via file local variables (@pxref{File Local Variables}). 1047below.) If @code{nil}, dynamic binding is used for all local
1048variables. This variable is typically set for a whole Emacs Lisp
1049file, as a file local variable (@pxref{File Local Variables}).
1114@end defvar 1050@end defvar
1115 1051
1052@noindent
1053When evaluating Emacs Lisp code directly using an @code{eval} call,
1054lexical binding is enabled if the @var{lexical} argument to
1055@code{eval} is non-@code{nil}. @xref{Eval}.
1056
1057@cindex special variables
1058 Even when lexical binding is enabled, certain variables will
1059continue to be dynamically bound. These are called @dfn{special
1060variables}. Every variable that has been defined with @code{defvar},
1061@code{defcustom} or @code{defconst} is a special variable
1062(@pxref{Defining Variables}). All other variables are subject to
1063lexical binding.
1064
1116@defun special-variable-p SYMBOL 1065@defun special-variable-p SYMBOL
1117Return whether SYMBOL has been declared as a special variable, via 1066This function returns non-@code{nil} if @var{symbol} is a special
1118@code{defvar} or @code{defconst}. 1067variable (i.e.@: it has a @code{defvar}, @code{defcustom}, or
1068@code{defconst} variable definition). Otherwise, the return value is
1069@code{nil}.
1119@end defun 1070@end defun
1120 1071
1121The use of a special variable as a formal argument in a function is generally 1072 The use of a special variable as a formal argument in a function is
1122discouraged and its behavior in lexical binding mode is unspecified (it may use 1073discouraged. Doing so gives rise to unspecified behavior when lexical
1123lexical scoping sometimes and dynamic scoping other times). 1074binding mode is enabled (it may use lexical binding sometimes, and
1124 1075dynamic binding other times).
1125Functions like @code{symbol-value}, @code{boundp}, or @code{set} only know 1076
1126about dynamically scoped variables, so you cannot get the value of a lexical 1077 Converting an Emacs Lisp program to lexical binding is pretty easy.
1127variable via @code{symbol-value} and neither can you change it via @code{set}. 1078First, add a file-local variable setting of @code{lexical-binding} to
1128Another particularity is that code in the body of a @code{defun} or 1079@code{t} in the Emacs Lisp source file. Second, check that every
1129@code{defmacro} cannot refer to surrounding lexical variables. 1080variable in the program which needs to be dynamically bound has a
1130 1081variable definition, so that it is not inadvertently bound lexically.
1131Evaluation of a @code{lambda} expression in lexical binding mode will not just 1082
1132return that lambda expression unchanged, as in the dynamic binding case, but 1083 A simple way to find out which variables need a variable definition
1133will instead construct a new object that remembers the current lexical 1084is to byte-compile the source file. @xref{Byte Compilation}. If a
1134environment in which that lambda expression was defined, so that the function 1085non-special variable is used outside of a @code{let} form, the
1135body can later be evaluated in the proper context. Those objects are called 1086byte-compiler will warn about reference or assignment to a ``free
1136@dfn{closures}. They are also functions, in the sense that they are accepted 1087variable''. If a non-special variable is bound but not used within a
1137by @code{funcall}, and they are represented by a cons cell whose @code{car} is 1088@code{let} form, the byte-compiler will warn about an ``unused lexical
1138the symbol @code{closure}. 1089variable''. The byte-compiler will also issue a warning if you use a
1139 1090special variable as a function argument.
1140@menu 1091
1141* Converting to Lexical Binding:: How to start using lexical scoping 1092 (To silence byte-compiler warnings about unused variables, just use
1142@end menu 1093a variable name that start with an underscore. The byte-compiler
1143 1094interprets this as an indication that this is a variable known not to
1144@node Converting to Lexical Binding 1095be used.)
1145@subsubsection Converting a package to use lexical scoping
1146
1147Lexical scoping, as currently implemented, does not bring many significant
1148benefits, unless you are a seasoned functional programmer addicted to
1149higher-order functions. But its importance will increase in the future:
1150lexical scoping opens up a lot more opportunities for optimization, so
1151lexically scoped code is likely to run faster in future Emacs versions, and it
1152is much more friendly to concurrency, which we want to add in the near future.
1153
1154Converting a package to lexical binding is usually pretty easy and should not
1155break backward compatibility: just add a file-local variable setting
1156@code{lexical-binding} to @code{t} and add declarations of the form
1157@code{(defvar @var{VAR})} for every variable which still needs to use
1158dynamic scoping.
1159
1160To find which variables need this declaration, the simplest solution is to
1161check the byte-compiler's warnings. The byte-compiler will usually find those
1162variables either because they are used outside of a let-binding (leading to
1163warnings about reference or assignment to ``free variable @var{VAR}'') or
1164because they are let-bound but not used within the let-binding (leading to
1165warnings about ``unused lexical variable @var{VAR}'').
1166
1167In cases where a dynamically scoped variable was bound as a function argument,
1168you will also need to move this binding to a @code{let}. These cases are also
1169flagged by the byte-compiler.
1170
1171To silence byte-compiler warnings about unused variables, just use a variable
1172name that start with an underscore, which the byte-compiler interpret as an
1173indication that this is a variable known not to be used.
1174
1175In most cases, the resulting code will then work with either setting of
1176@code{lexical-binding}, so it can still be used with older Emacsen (which will
1177simply ignore the @code{lexical-binding} variable setting).
1178 1096
1179@node Buffer-Local Variables 1097@node Buffer-Local Variables
1180@section Buffer-Local Variables 1098@section Buffer-Local Variables