Minor improvements in manuals
[emacs.git] / doc / lispref / variables.texi
blobaecee6f30565cc5d5e5e621fac17fe7c32a95938
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998-2018 Free Software Foundation, Inc.
4 @c See the file elisp.texi for copying conditions.
5 @node Variables
6 @chapter Variables
7 @cindex variable
9   A @dfn{variable} is a name used in a program to stand for a value.
10 In Lisp, each variable is represented by a Lisp symbol
11 (@pxref{Symbols}).  The variable name is simply the symbol's name, and
12 the variable's value is stored in the symbol's value cell@footnote{To
13 be precise, under the default @dfn{dynamic scoping} rule, the value
14 cell always holds the variable's current value, but this is not the
15 case under the @dfn{lexical scoping} rule.  @xref{Variable Scoping},
16 for details.}.  @xref{Symbol Components}.  In Emacs Lisp, the use of a
17 symbol as a variable is independent of its use as a function name.
19   As previously noted in this manual, a Lisp program is represented
20 primarily by Lisp objects, and only secondarily as text.  The textual
21 form of a Lisp program is given by the read syntax of the Lisp objects
22 that constitute the program.  Hence, the textual form of a variable in
23 a Lisp program is written using the read syntax for the symbol
24 representing the variable.
26 @menu
27 * Global Variables::            Variable values that exist permanently, everywhere.
28 * Constant Variables::          Variables that never change.
29 * Local Variables::             Variable values that exist only temporarily.
30 * Void Variables::              Symbols that lack values.
31 * Defining Variables::          A definition says a symbol is used as a variable.
32 * Tips for Defining::           Things you should think about when you
33                             define a variable.
34 * Accessing Variables::         Examining values of variables whose names
35                             are known only at run time.
36 * Setting Variables::           Storing new values in variables.
37 * Watching Variables::          Running a function when a variable is changed.
38 * Variable Scoping::            How Lisp chooses among local and global values.
39 * Buffer-Local Variables::      Variable values in effect only in one buffer.
40 * File Local Variables::        Handling local variable lists in files.
41 * Directory Local Variables::   Local variables common to all files in a directory.
42 * Connection Local Variables::  Local variables common for remote connections.
43 * Variable Aliases::            Variables that are aliases for other variables.
44 * Variables with Restricted Values::  Non-constant variables whose value can
45                                         @emph{not} be an arbitrary Lisp object.
46 * Generalized Variables::       Extending the concept of variables.
47 @end menu
49 @node Global Variables
50 @section Global Variables
51 @cindex global variable
53   The simplest way to use a variable is @dfn{globally}.  This means that
54 the variable has just one value at a time, and this value is in effect
55 (at least for the moment) throughout the Lisp system.  The value remains
56 in effect until you specify a new one.  When a new value replaces the
57 old one, no trace of the old value remains in the variable.
59   You specify a value for a symbol with @code{setq}.  For example,
61 @example
62 (setq x '(a b))
63 @end example
65 @noindent
66 gives the variable @code{x} the value @code{(a b)}.  Note that
67 @code{setq} is a special form (@pxref{Special Forms}); it does not
68 evaluate its first argument, the name of the variable, but it does
69 evaluate the second argument, the new value.
71   Once the variable has a value, you can refer to it by using the
72 symbol itself as an expression.  Thus,
74 @example
75 @group
76 x @result{} (a b)
77 @end group
78 @end example
80 @noindent
81 assuming the @code{setq} form shown above has already been executed.
83   If you do set the same variable again, the new value replaces the old
84 one:
86 @example
87 @group
89      @result{} (a b)
90 @end group
91 @group
92 (setq x 4)
93      @result{} 4
94 @end group
95 @group
97      @result{} 4
98 @end group
99 @end example
101 @node Constant Variables
102 @section Variables that Never Change
103 @cindex @code{setting-constant} error
104 @cindex keyword symbol
105 @cindex variable with constant value
106 @cindex constant variables
107 @cindex symbol that evaluates to itself
108 @cindex symbol with constant value
110   In Emacs Lisp, certain symbols normally evaluate to themselves.  These
111 include @code{nil} and @code{t}, as well as any symbol whose name starts
112 with @samp{:} (these are called @dfn{keywords}).  These symbols cannot
113 be rebound, nor can their values be changed.  Any attempt to set or bind
114 @code{nil} or @code{t} signals a @code{setting-constant} error.  The
115 same is true for a keyword (a symbol whose name starts with @samp{:}),
116 if it is interned in the standard obarray, except that setting such a
117 symbol to itself is not an error.
119 @example
120 @group
121 nil @equiv{} 'nil
122      @result{} nil
123 @end group
124 @group
125 (setq nil 500)
126 @error{} Attempt to set constant symbol: nil
127 @end group
128 @end example
130 @defun keywordp object
131 function returns @code{t} if @var{object} is a symbol whose name
132 starts with @samp{:}, interned in the standard obarray, and returns
133 @code{nil} otherwise.
134 @end defun
136 These constants are fundamentally different from the constants
137 defined using the @code{defconst} special form (@pxref{Defining
138 Variables}).  A @code{defconst} form serves to inform human readers
139 that you do not intend to change the value of a variable, but Emacs
140 does not raise an error if you actually change it.
142 @cindex read-only variables
143 A small number of additional symbols are made read-only for various
144 practical reasons.  These include @code{enable-multibyte-characters},
145 @code{most-positive-fixnum}, @code{most-negative-fixnum}, and a few
146 others.  Any attempt to set or bind these also signals a
147 @code{setting-constant} error.
149 @node Local Variables
150 @section Local Variables
151 @cindex binding local variables
152 @cindex local variables
153 @cindex local binding
154 @cindex global binding
156   Global variables have values that last until explicitly superseded
157 with new values.  Sometimes it is useful to give a variable a
158 @dfn{local value}---a value that takes effect only within a certain
159 part of a Lisp program.  When a variable has a local value, we say
160 that it is @dfn{locally bound} to that value, and that it is a
161 @dfn{local variable}.
163   For example, when a function is called, its argument variables
164 receive local values, which are the actual arguments supplied to the
165 function call; these local bindings take effect within the body of the
166 function.  To take another example, the @code{let} special form
167 explicitly establishes local bindings for specific variables, which
168 take effect only within the body of the @code{let} form.
170   We also speak of the @dfn{global binding}, which is where
171 (conceptually) the global value is kept.
173 @cindex shadowing of variables
174   Establishing a local binding saves away the variable's previous
175 value (or lack of one).  We say that the previous value is
176 @dfn{shadowed}.  Both global and local values may be shadowed.  If a
177 local binding is in effect, using @code{setq} on the local variable
178 stores the specified value in the local binding.  When that local
179 binding is no longer in effect, the previously shadowed value (or lack
180 of one) comes back.
182 @cindex current binding
183   A variable can have more than one local binding at a time (e.g., if
184 there are nested @code{let} forms that bind the variable).  The
185 @dfn{current binding} is the local binding that is actually in effect.
186 It determines the value returned by evaluating the variable symbol,
187 and it is the binding acted on by @code{setq}.
189   For most purposes, you can think of the current binding as the
190 innermost local binding, or the global binding if there is no
191 local binding.  To be more precise, a rule called the @dfn{scoping
192 rule} determines where in a program a local binding takes effect.  The
193 default scoping rule in Emacs Lisp is called @dfn{dynamic scoping},
194 which simply states that the current binding at any given point in the
195 execution of a program is the most recently-created binding for that
196 variable that still exists.  For details about dynamic scoping, and an
197 alternative scoping rule called @dfn{lexical scoping}, @xref{Variable
198 Scoping}.
200   The special forms @code{let} and @code{let*} exist to create local
201 bindings:
203 @defspec let (bindings@dots{}) forms@dots{}
204 This special form sets up local bindings for a certain set of
205 variables, as specified by @var{bindings}, and then evaluates all of
206 the @var{forms} in textual order.  Its return value is the value of
207 the last form in @var{forms}.  The local bindings set up by @code{let}
208 will be in effect only within the body of @var{forms}.
210 Each of the @var{bindings} is either @w{(i) a} symbol, in which case
211 that symbol is locally bound to @code{nil}; or @w{(ii) a} list of the
212 form @code{(@var{symbol} @var{value-form})}, in which case
213 @var{symbol} is locally bound to the result of evaluating
214 @var{value-form}.  If @var{value-form} is omitted, @code{nil} is used.
216 All of the @var{value-form}s in @var{bindings} are evaluated in the
217 order they appear and @emph{before} binding any of the symbols to them.
218 Here is an example of this: @code{z} is bound to the old value of
219 @code{y}, which is 2, not the new value of @code{y}, which is 1.
221 @example
222 @group
223 (setq y 2)
224      @result{} 2
225 @end group
227 @group
228 (let ((y 1)
229       (z y))
230   (list y z))
231      @result{} (1 2)
232 @end group
233 @end example
235 On the other hand, the order of @emph{bindings} is unspecified: in the
236 following example, either 1 or 2 might be printed.
238 @example
239 (let ((x 1)
240       (x 2))
241   (print x))
242 @end example
244 Therefore, avoid binding a variable more than once in a single
245 @code{let} form.
246 @end defspec
248 @defspec let* (bindings@dots{}) forms@dots{}
249 This special form is like @code{let}, but it binds each variable right
250 after computing its local value, before computing the local value for
251 the next variable.  Therefore, an expression in @var{bindings} can
252 refer to the preceding symbols bound in this @code{let*} form.
253 Compare the following example with the example above for @code{let}.
255 @example
256 @group
257 (setq y 2)
258      @result{} 2
259 @end group
261 @group
262 (let* ((y 1)
263        (z y))    ; @r{Use the just-established value of @code{y}.}
264   (list y z))
265      @result{} (1 1)
266 @end group
267 @end example
268 @end defspec
270   Here is a complete list of the other facilities that create local
271 bindings:
273 @itemize @bullet
274 @item
275 Function calls (@pxref{Functions}).
277 @item
278 Macro calls (@pxref{Macros}).
280 @item
281 @code{condition-case} (@pxref{Errors}).
282 @end itemize
284   Variables can also have buffer-local bindings (@pxref{Buffer-Local
285 Variables}); a few variables have terminal-local bindings
286 (@pxref{Multiple Terminals}).  These kinds of bindings work somewhat
287 like ordinary local bindings, but they are localized depending on
288 where you are in Emacs.
290 @defopt max-specpdl-size
291 @anchor{Definition of max-specpdl-size}
292 @cindex variable limit error
293 @cindex evaluation error
294 @cindex infinite recursion
295 This variable defines the limit on the total number of local variable
296 bindings and @code{unwind-protect} cleanups (see @ref{Cleanups,,
297 Cleaning Up from Nonlocal Exits}) that are allowed before Emacs
298 signals an error (with data @code{"Variable binding depth exceeds
299 max-specpdl-size"}).
301 This limit, with the associated error when it is exceeded, is one way
302 that Lisp avoids infinite recursion on an ill-defined function.
303 @code{max-lisp-eval-depth} provides another limit on depth of nesting.
304 @xref{Definition of max-lisp-eval-depth,, Eval}.
306 The default value is 1300.  Entry to the Lisp debugger increases the
307 value, if there is little room left, to make sure the debugger itself
308 has room to execute.
309 @end defopt
311 @node Void Variables
312 @section When a Variable is Void
313 @cindex @code{void-variable} error
314 @cindex void variable
316   We say that a variable is void if its symbol has an unassigned value
317 cell (@pxref{Symbol Components}).
319   Under Emacs Lisp's default dynamic scoping rule (@pxref{Variable
320 Scoping}), the value cell stores the variable's current (local or
321 global) value.  Note that an unassigned value cell is @emph{not} the
322 same as having @code{nil} in the value cell.  The symbol @code{nil} is
323 a Lisp object and can be the value of a variable, just as any other
324 object can be; but it is still a value.  If a variable is void, trying
325 to evaluate the variable signals a @code{void-variable} error, instead
326 of returning a value.
328   Under the optional lexical scoping rule, the value cell only holds
329 the variable's global value---the value outside of any lexical binding
330 construct.  When a variable is lexically bound, the local value is
331 determined by the lexical environment; hence, variables can have local
332 values even if their symbols' value cells are unassigned.
334 @defun makunbound symbol
335 This function empties out the value cell of @var{symbol}, making the
336 variable void.  It returns @var{symbol}.
338 If @var{symbol} has a dynamic local binding, @code{makunbound} voids
339 the current binding, and this voidness lasts only as long as the local
340 binding is in effect.  Afterwards, the previously shadowed local or
341 global binding is reexposed; then the variable will no longer be void,
342 unless the reexposed binding is void too.
344 Here are some examples (assuming dynamic binding is in effect):
346 @smallexample
347 @group
348 (setq x 1)               ; @r{Put a value in the global binding.}
349      @result{} 1
350 (let ((x 2))             ; @r{Locally bind it.}
351   (makunbound 'x)        ; @r{Void the local binding.}
352   x)
353 @error{} Symbol's value as variable is void: x
354 @end group
355 @group
356 x                        ; @r{The global binding is unchanged.}
357      @result{} 1
359 (let ((x 2))             ; @r{Locally bind it.}
360   (let ((x 3))           ; @r{And again.}
361     (makunbound 'x)      ; @r{Void the innermost-local binding.}
362     x))                  ; @r{And refer: it's void.}
363 @error{} Symbol's value as variable is void: x
364 @end group
366 @group
367 (let ((x 2))
368   (let ((x 3))
369     (makunbound 'x))     ; @r{Void inner binding, then remove it.}
370   x)                     ; @r{Now outer @code{let} binding is visible.}
371      @result{} 2
372 @end group
373 @end smallexample
374 @end defun
376 @defun boundp variable
377 This function returns @code{t} if @var{variable} (a symbol) is not
378 void, and @code{nil} if it is void.
380 Here are some examples (assuming dynamic binding is in effect):
382 @smallexample
383 @group
384 (boundp 'abracadabra)          ; @r{Starts out void.}
385      @result{} nil
386 @end group
387 @group
388 (let ((abracadabra 5))         ; @r{Locally bind it.}
389   (boundp 'abracadabra))
390      @result{} t
391 @end group
392 @group
393 (boundp 'abracadabra)          ; @r{Still globally void.}
394      @result{} nil
395 @end group
396 @group
397 (setq abracadabra 5)           ; @r{Make it globally nonvoid.}
398      @result{} 5
399 @end group
400 @group
401 (boundp 'abracadabra)
402      @result{} t
403 @end group
404 @end smallexample
405 @end defun
407 @node Defining Variables
408 @section Defining Global Variables
409 @cindex variable definition
411   A @dfn{variable definition} is a construct that announces your
412 intention to use a symbol as a global variable.  It uses the special
413 forms @code{defvar} or @code{defconst}, which are documented below.
415   A variable definition serves three purposes.  First, it informs
416 people who read the code that the symbol is @emph{intended} to be used
417 a certain way (as a variable).  Second, it informs the Lisp system of
418 this, optionally supplying an initial value and a documentation
419 string.  Third, it provides information to programming tools such as
420 @command{etags}, allowing them to find where the variable was defined.
422   The difference between @code{defconst} and @code{defvar} is mainly a
423 matter of intent, serving to inform human readers of whether the value
424 should ever change.  Emacs Lisp does not actually prevent you from
425 changing the value of a variable defined with @code{defconst}.  One
426 notable difference between the two forms is that @code{defconst}
427 unconditionally initializes the variable, whereas @code{defvar}
428 initializes it only if it is originally void.
430   To define a customizable variable, you should use @code{defcustom}
431 (which calls @code{defvar} as a subroutine).  @xref{Variable
432 Definitions}.
434 @defspec defvar symbol [value [doc-string]]
435 This special form defines @var{symbol} as a variable.  Note that
436 @var{symbol} is not evaluated; the symbol to be defined should appear
437 explicitly in the @code{defvar} form.  The variable is marked as
438 @dfn{special}, meaning that it should always be dynamically bound
439 (@pxref{Variable Scoping}).
441 If @var{value} is specified, and @var{symbol} is void (i.e., it has no
442 dynamically bound value; @pxref{Void Variables}), then @var{value} is
443 evaluated and @var{symbol} is set to the result.  But if @var{symbol}
444 is not void, @var{value} is not evaluated, and @var{symbol}'s value is
445 left unchanged.  If @var{value} is omitted, the value of @var{symbol}
446 is not changed in any case.  Using @code{defvar} with no value is one
447 method of suppressing byte compilation warnings, see @ref{Compiler
448 Errors}.
450 If @var{symbol} has a buffer-local binding in the current buffer,
451 @code{defvar} acts on the default value, which is buffer-independent,
452 rather than the buffer-local binding.  It sets the default value if
453 the default value is void.  @xref{Buffer-Local Variables}.
455 If @var{symbol} is already lexically bound (e.g., if the @code{defvar}
456 form occurs in a @code{let} form with lexical binding enabled), then
457 @code{defvar} sets the dynamic value.  The lexical binding remains in
458 effect until its binding construct exits.  @xref{Variable Scoping}.
460 When you evaluate a top-level @code{defvar} form with @kbd{C-M-x} in
461 Emacs Lisp mode (@code{eval-defun}), a special feature of
462 @code{eval-defun} arranges to set the variable unconditionally, without
463 testing whether its value is void.
465 If the @var{doc-string} argument is supplied, it specifies the
466 documentation string for the variable (stored in the symbol's
467 @code{variable-documentation} property).  @xref{Documentation}.
469 Here are some examples.  This form defines @code{foo} but does not
470 initialize it:
472 @example
473 @group
474 (defvar foo)
475      @result{} foo
476 @end group
477 @end example
479 This example initializes the value of @code{bar} to @code{23}, and gives
480 it a documentation string:
482 @example
483 @group
484 (defvar bar 23
485   "The normal weight of a bar.")
486      @result{} bar
487 @end group
488 @end example
490 The @code{defvar} form returns @var{symbol}, but it is normally used
491 at top level in a file where its value does not matter.
492 @end defspec
494 @cindex constant variables
495 @defspec defconst symbol value [doc-string]
496 This special form defines @var{symbol} as a value and initializes it.
497 It informs a person reading your code that @var{symbol} has a standard
498 global value, established here, that should not be changed by the user
499 or by other programs.  Note that @var{symbol} is not evaluated; the
500 symbol to be defined must appear explicitly in the @code{defconst}.
502 The @code{defconst} form, like @code{defvar}, marks the variable as
503 @dfn{special}, meaning that it should always be dynamically bound
504 (@pxref{Variable Scoping}).  In addition, it marks the variable as
505 risky (@pxref{File Local Variables}).
507 @code{defconst} always evaluates @var{value}, and sets the value of
508 @var{symbol} to the result.  If @var{symbol} does have a buffer-local
509 binding in the current buffer, @code{defconst} sets the default value,
510 not the buffer-local value.  (But you should not be making
511 buffer-local bindings for a symbol that is defined with
512 @code{defconst}.)
514 An example of the use of @code{defconst} is Emacs's definition of
515 @code{float-pi}---the mathematical constant @math{pi}, which ought not
516 to be changed by anyone (attempts by the Indiana State Legislature
517 notwithstanding).  As the second form illustrates, however,
518 @code{defconst} is only advisory.
520 @example
521 @group
522 (defconst float-pi 3.141592653589793 "The value of Pi.")
523      @result{} float-pi
524 @end group
525 @group
526 (setq float-pi 3)
527      @result{} float-pi
528 @end group
529 @group
530 float-pi
531      @result{} 3
532 @end group
533 @end example
534 @end defspec
536   @strong{Warning:} If you use a @code{defconst} or @code{defvar}
537 special form while the variable has a local binding (made with
538 @code{let}, or a function argument), it sets the local binding rather
539 than the global binding.  This is not what you usually want.  To
540 prevent this, use these special forms at top level in a file, where
541 normally no local binding is in effect, and make sure to load the file
542 before making a local binding for the variable.
544 @node Tips for Defining
545 @section Tips for Defining Variables Robustly
547   When you define a variable whose value is a function, or a list of
548 functions, use a name that ends in @samp{-function} or
549 @samp{-functions}, respectively.
551   There are several other variable name conventions;
552 here is a complete list:
554 @table @samp
555 @item @dots{}-hook
556 The variable is a normal hook (@pxref{Hooks}).
558 @item @dots{}-function
559 The value is a function.
561 @item @dots{}-functions
562 The value is a list of functions.
564 @item @dots{}-form
565 The value is a form (an expression).
567 @item @dots{}-forms
568 The value is a list of forms (expressions).
570 @item @dots{}-predicate
571 The value is a predicate---a function of one argument that returns
572 non-@code{nil} for success and @code{nil} for failure.
574 @item @dots{}-flag
575 The value is significant only as to whether it is @code{nil} or not.
576 Since such variables often end up acquiring more values over time,
577 this convention is not strongly recommended.
579 @item @dots{}-program
580 The value is a program name.
582 @item @dots{}-command
583 The value is a whole shell command.
585 @item @dots{}-switches
586 The value specifies options for a command.
588 @item @var{prefix}--@dots{}
589 The variable is intended for internal use and is defined in the file
590 @file{@var{prefix}.el}.  (Emacs code contributed before 2018 may
591 follow other conventions, which are being phased out.)
593 @item @dots{}-internal
594 The variable is intended for internal use and is defined in C code.
595 (Emacs code contributed before 2018 may follow other conventions,
596 which are being phased out.)
597 @end table
599   When you define a variable, always consider whether you should mark
600 it as safe or risky; see @ref{File Local Variables}.
602   When defining and initializing a variable that holds a complicated
603 value (such as a keymap with bindings in it), it's best to put the
604 entire computation of the value into the @code{defvar}, like this:
606 @example
607 (defvar my-mode-map
608   (let ((map (make-sparse-keymap)))
609     (define-key map "\C-c\C-a" 'my-command)
610     @dots{}
611     map)
612   @var{docstring})
613 @end example
615 @noindent
616 This method has several benefits.  First, if the user quits while
617 loading the file, the variable is either still uninitialized or
618 initialized properly, never in-between.  If it is still uninitialized,
619 reloading the file will initialize it properly.  Second, reloading the
620 file once the variable is initialized will not alter it; that is
621 important if the user has run hooks to alter part of the contents
622 (such as, to rebind keys).  Third, evaluating the @code{defvar} form
623 with @kbd{C-M-x} will reinitialize the map completely.
625   Putting so much code in the @code{defvar} form has one disadvantage:
626 it puts the documentation string far away from the line which names the
627 variable.  Here's a safe way to avoid that:
629 @example
630 (defvar my-mode-map nil
631   @var{docstring})
632 (unless my-mode-map
633   (let ((map (make-sparse-keymap)))
634     (define-key map "\C-c\C-a" 'my-command)
635     @dots{}
636     (setq my-mode-map map)))
637 @end example
639 @noindent
640 This has all the same advantages as putting the initialization inside
641 the @code{defvar}, except that you must type @kbd{C-M-x} twice, once on
642 each form, if you do want to reinitialize the variable.
644 @node Accessing Variables
645 @section Accessing Variable Values
647   The usual way to reference a variable is to write the symbol which
648 names it.  @xref{Symbol Forms}.
650   Occasionally, you may want to reference a variable which is only
651 determined at run time.  In that case, you cannot specify the variable
652 name in the text of the program.  You can use the @code{symbol-value}
653 function to extract the value.
655 @defun symbol-value symbol
656 This function returns the value stored in @var{symbol}'s value cell.
657 This is where the variable's current (dynamic) value is stored.  If
658 the variable has no local binding, this is simply its global value.
659 If the variable is void, a @code{void-variable} error is signaled.
661 If the variable is lexically bound, the value reported by
662 @code{symbol-value} is not necessarily the same as the variable's
663 lexical value, which is determined by the lexical environment rather
664 than the symbol's value cell.  @xref{Variable Scoping}.
666 @example
667 @group
668 (setq abracadabra 5)
669      @result{} 5
670 @end group
671 @group
672 (setq foo 9)
673      @result{} 9
674 @end group
676 @group
677 ;; @r{Here the symbol @code{abracadabra}}
678 ;;   @r{is the symbol whose value is examined.}
679 (let ((abracadabra 'foo))
680   (symbol-value 'abracadabra))
681      @result{} foo
682 @end group
684 @group
685 ;; @r{Here, the value of @code{abracadabra},}
686 ;;   @r{which is @code{foo},}
687 ;;   @r{is the symbol whose value is examined.}
688 (let ((abracadabra 'foo))
689   (symbol-value abracadabra))
690      @result{} 9
691 @end group
693 @group
694 (symbol-value 'abracadabra)
695      @result{} 5
696 @end group
697 @end example
698 @end defun
700 @node Setting Variables
701 @section Setting Variable Values
703   The usual way to change the value of a variable is with the special
704 form @code{setq}.  When you need to compute the choice of variable at
705 run time, use the function @code{set}.
707 @defspec setq [symbol form]@dots{}
708 This special form is the most common method of changing a variable's
709 value.  Each @var{symbol} is given a new value, which is the result of
710 evaluating the corresponding @var{form}.  The current binding of the
711 symbol is changed.
713 @code{setq} does not evaluate @var{symbol}; it sets the symbol that you
714 write.  We say that this argument is @dfn{automatically quoted}.  The
715 @samp{q} in @code{setq} stands for ``quoted''.
717 The value of the @code{setq} form is the value of the last @var{form}.
719 @example
720 @group
721 (setq x (1+ 2))
722      @result{} 3
723 @end group
724 x                   ; @r{@code{x} now has a global value.}
725      @result{} 3
726 @group
727 (let ((x 5))
728   (setq x 6)        ; @r{The local binding of @code{x} is set.}
729   x)
730      @result{} 6
731 @end group
732 x                   ; @r{The global value is unchanged.}
733      @result{} 3
734 @end example
736 Note that the first @var{form} is evaluated, then the first
737 @var{symbol} is set, then the second @var{form} is evaluated, then the
738 second @var{symbol} is set, and so on:
740 @example
741 @group
742 (setq x 10          ; @r{Notice that @code{x} is set before}
743       y (1+ x))     ;   @r{the value of @code{y} is computed.}
744      @result{} 11
745 @end group
746 @end example
747 @end defspec
749 @defun set symbol value
750 This function puts @var{value} in the value cell of @var{symbol}.
751 Since it is a function rather than a special form, the expression
752 written for @var{symbol} is evaluated to obtain the symbol to set.
753 The return value is @var{value}.
755 When dynamic variable binding is in effect (the default), @code{set}
756 has the same effect as @code{setq}, apart from the fact that
757 @code{set} evaluates its @var{symbol} argument whereas @code{setq}
758 does not.  But when a variable is lexically bound, @code{set} affects
759 its @emph{dynamic} value, whereas @code{setq} affects its current
760 (lexical) value.  @xref{Variable Scoping}.
762 @example
763 @group
764 (set one 1)
765 @error{} Symbol's value as variable is void: one
766 @end group
767 @group
768 (set 'one 1)
769      @result{} 1
770 @end group
771 @group
772 (set 'two 'one)
773      @result{} one
774 @end group
775 @group
776 (set two 2)         ; @r{@code{two} evaluates to symbol @code{one}.}
777      @result{} 2
778 @end group
779 @group
780 one                 ; @r{So it is @code{one} that was set.}
781      @result{} 2
782 (let ((one 1))      ; @r{This binding of @code{one} is set,}
783   (set 'one 3)      ;   @r{not the global value.}
784   one)
785      @result{} 3
786 @end group
787 @group
789      @result{} 2
790 @end group
791 @end example
793 If @var{symbol} is not actually a symbol, a @code{wrong-type-argument}
794 error is signaled.
796 @example
797 (set '(x y) 'z)
798 @error{} Wrong type argument: symbolp, (x y)
799 @end example
800 @end defun
802 @node Watching Variables
803 @section Running a function when a variable is changed.
804 @cindex variable watchpoints
805 @cindex watchpoints for Lisp variables
807 It is sometimes useful to take some action when a variable changes its
808 value.  The watchpoint facility provides the means to do so.  Some
809 possible uses for this feature include keeping display in sync with
810 variable settings, and invoking the debugger to track down unexpected
811 changes to variables (@pxref{Variable Debugging}).
813 The following functions may be used to manipulate and query the watch
814 functions for a variable.
816 @defun add-variable-watcher symbol watch-function
817 This function arranges for @var{watch-function} to be called whenever
818 @var{symbol} is modified.  Modifications through aliases
819 (@pxref{Variable Aliases}) will have the same effect.
821 @var{watch-function} will be called with 4 arguments: (@var{symbol}
822 @var{newval} @var{operation} @var{where}).
824 @var{symbol} is the variable being changed.
825 @var{newval} is the value it will be changed to.
826 @var{operation} is a symbol representing the kind of change, one of:
827 `set', `let', `unlet', `makunbound', and `defvaralias'.
828 @var{where} is a buffer if the buffer-local value of the variable is
829 being changed, @code{nil} otherwise.
830 @end defun
832 @defun remove-variable-watch symbol watch-function
833 This function removes @var{watch-function} from @var{symbol}'s list of
834 watchers.
835 @end defun
837 @defun get-variable-watchers symbol
838 This function returns the list of @var{symbol}'s active watcher
839 functions.
840 @end defun
842 @subsection Limitations
844 There are a couple of ways in which a variable could be modified (or at
845 least appear to be modified) without triggering a watchpoint.
847 Since watchpoints are attached to symbols, modification to the
848 objects contained within variables (e.g., by a list modification
849 function @pxref{Modifying Lists}) is not caught by this mechanism.
851 Additionally, C code can modify the value of variables directly,
852 bypassing the watchpoint mechanism.
854 A minor limitation of this feature, again because it targets symbols,
855 is that only variables of dynamic scope may be watched.  This poses
856 little difficulty, since modifications to lexical variables can be
857 discovered easily by inspecting the code within the scope of the
858 variable (unlike dynamic variables, which can be modified by any code
859 at all, @pxref{Variable Scoping}).
862 @node Variable Scoping
863 @section Scoping Rules for Variable Bindings
864 @cindex scoping rule
866   When you create a local binding for a variable, that binding takes
867 effect only within a limited portion of the program (@pxref{Local
868 Variables}).  This section describes exactly what this means.
870 @cindex scope
871 @cindex extent
872   Each local binding has a certain @dfn{scope} and @dfn{extent}.
873 @dfn{Scope} refers to @emph{where} in the textual source code the
874 binding can be accessed.  @dfn{Extent} refers to @emph{when}, as the
875 program is executing, the binding exists.
877 @cindex dynamic binding
878 @cindex dynamic scope
879 @cindex dynamic extent
880   By default, the local bindings that Emacs creates are @dfn{dynamic
881 bindings}.  Such a binding has @dfn{dynamic scope}, meaning that any
882 part of the program can potentially access the variable binding.  It
883 also has @dfn{dynamic extent}, meaning that the binding lasts only
884 while the binding construct (such as the body of a @code{let} form) is
885 being executed.
887 @cindex lexical binding
888 @cindex lexical scope
889 @cindex indefinite extent
890   Emacs can optionally create @dfn{lexical bindings}.  A lexical
891 binding has @dfn{lexical scope}, meaning that any reference to the
892 variable must be located textually within the binding
893 construct@footnote{With some exceptions; for instance, a lexical
894 binding can also be accessed from the Lisp debugger.}.  It also has
895 @dfn{indefinite extent}, meaning that under some circumstances the
896 binding can live on even after the binding construct has finished
897 executing, by means of special objects called @dfn{closures}.
899   The following subsections describe dynamic binding and lexical
900 binding in greater detail, and how to enable lexical binding in Emacs
901 Lisp programs.
903 @menu
904 * Dynamic Binding::         The default for binding local variables in Emacs.
905 * Dynamic Binding Tips::    Avoiding problems with dynamic binding.
906 * Lexical Binding::         A different type of local variable binding.
907 * Using Lexical Binding::   How to enable lexical binding.
908 @end menu
910 @node Dynamic Binding
911 @subsection Dynamic Binding
913   By default, the local variable bindings made by Emacs are dynamic
914 bindings.  When a variable is dynamically bound, its current binding
915 at any point in the execution of the Lisp program is simply the most
916 recently-created dynamic local binding for that symbol, or the global
917 binding if there is no such local binding.
919   Dynamic bindings have dynamic scope and extent, as shown by the
920 following example:
922 @example
923 @group
924 (defvar x -99)  ; @r{@code{x} receives an initial value of @minus{}99.}
926 (defun getx ()
927   x)            ; @r{@code{x} is used free in this function.}
929 (let ((x 1))    ; @r{@code{x} is dynamically bound.}
930   (getx))
931      @result{} 1
933 ;; @r{After the @code{let} form finishes, @code{x} reverts to its}
934 ;; @r{previous value, which is @minus{}99.}
936 (getx)
937      @result{} -99
938 @end group
939 @end example
941 @noindent
942 The function @code{getx} refers to @code{x}.  This is a @dfn{free}
943 reference, in the sense that there is no binding for @code{x} within
944 that @code{defun} construct itself.  When we call @code{getx} from
945 within a @code{let} form in which @code{x} is (dynamically) bound, it
946 retrieves the local value (i.e., 1).  But when we call @code{getx}
947 outside the @code{let} form, it retrieves the global value (i.e.,
948 @minus{}99).
950   Here is another example, which illustrates setting a dynamically
951 bound variable using @code{setq}:
953 @example
954 @group
955 (defvar x -99)      ; @r{@code{x} receives an initial value of @minus{}99.}
957 (defun addx ()
958   (setq x (1+ x)))  ; @r{Add 1 to @code{x} and return its new value.}
960 (let ((x 1))
961   (addx)
962   (addx))
963      @result{} 3           ; @r{The two @code{addx} calls add to @code{x} twice.}
965 ;; @r{After the @code{let} form finishes, @code{x} reverts to its}
966 ;; @r{previous value, which is @minus{}99.}
968 (addx)
969      @result{} -98
970 @end group
971 @end example
973   Dynamic binding is implemented in Emacs Lisp in a simple way.  Each
974 symbol has a value cell, which specifies its current dynamic value (or
975 absence of value).  @xref{Symbol Components}.  When a symbol is given
976 a dynamic local binding, Emacs records the contents of the value cell
977 (or absence thereof) in a stack, and stores the new local value in the
978 value cell.  When the binding construct finishes executing, Emacs pops
979 the old value off the stack, and puts it in the value cell.
981 @node Dynamic Binding Tips
982 @subsection Proper Use of Dynamic Binding
984   Dynamic binding is a powerful feature, as it allows programs to
985 refer to variables that are not defined within their local textual
986 scope.  However, if used without restraint, this can also make
987 programs hard to understand.  There are two clean ways to use this
988 technique:
990 @itemize @bullet
991 @item
992 If a variable has no global definition, use it as a local variable
993 only within a binding construct, such as the body of the @code{let}
994 form where the variable was bound.  If this convention is followed
995 consistently throughout a program, the value of the variable will not
996 affect, nor be affected by, any uses of the same variable symbol
997 elsewhere in the program.
999 @item
1000 Otherwise, define the variable with @code{defvar}, @code{defconst}, or
1001 @code{defcustom}.  @xref{Defining Variables}.  Usually, the definition
1002 should be at top-level in an Emacs Lisp file.  As far as possible, it
1003 should include a documentation string which explains the meaning and
1004 purpose of the variable.  You should also choose the variable's name
1005 to avoid name conflicts (@pxref{Coding Conventions}).
1007 Then you can bind the variable anywhere in a program, knowing reliably
1008 what the effect will be.  Wherever you encounter the variable, it will
1009 be easy to refer back to the definition, e.g., via the @kbd{C-h v}
1010 command (provided the variable definition has been loaded into Emacs).
1011 @xref{Name Help,,, emacs, The GNU Emacs Manual}.
1013 For example, it is common to use local bindings for customizable
1014 variables like @code{case-fold-search}:
1016 @example
1017 @group
1018 (defun search-for-abc ()
1019   "Search for the string \"abc\", ignoring case differences."
1020   (let ((case-fold-search nil))
1021     (re-search-forward "abc")))
1022 @end group
1023 @end example
1024 @end itemize
1026 @node Lexical Binding
1027 @subsection Lexical Binding
1029   Lexical binding was introduced to Emacs, as an optional feature, in
1030 version 24.1.  We expect its importance to increase with time.
1031 Lexical binding opens up many more opportunities for optimization, so
1032 programs using it are likely to run faster in future Emacs versions.
1033 Lexical binding is also more compatible with concurrency, which was
1034 added to Emacs in version 26.1.
1036   A lexically-bound variable has @dfn{lexical scope}, meaning that any
1037 reference to the variable must be located textually within the binding
1038 construct.  Here is an example
1039 @iftex
1040 (see the next subsection, for how to actually enable lexical binding):
1041 @end iftex
1042 @ifnottex
1043 (@pxref{Using Lexical Binding}, for how to actually enable lexical binding):
1044 @end ifnottex
1046 @example
1047 @group
1048 (let ((x 1))    ; @r{@code{x} is lexically bound.}
1049   (+ x 3))
1050      @result{} 4
1052 (defun getx ()
1053   x)            ; @r{@code{x} is used free in this function.}
1055 (let ((x 1))    ; @r{@code{x} is lexically bound.}
1056   (getx))
1057 @error{} Symbol's value as variable is void: x
1058 @end group
1059 @end example
1061 @noindent
1062 Here, the variable @code{x} has no global value.  When it is lexically
1063 bound within a @code{let} form, it can be used in the textual confines
1064 of that @code{let} form.  But it can @emph{not} be used from within a
1065 @code{getx} function called from the @code{let} form, since the
1066 function definition of @code{getx} occurs outside the @code{let} form
1067 itself.
1069 @cindex lexical environment
1070   Here is how lexical binding works.  Each binding construct defines a
1071 @dfn{lexical environment}, specifying the variables that are bound
1072 within the construct and their local values.  When the Lisp evaluator
1073 wants the current value of a variable, it looks first in the lexical
1074 environment; if the variable is not specified in there, it looks in
1075 the symbol's value cell, where the dynamic value is stored.
1077   (Internally, the lexical environment is an alist of symbol-value
1078 pairs, with the final element in the alist being the symbol @code{t}
1079 rather than a cons cell.  Such an alist can be passed as the second
1080 argument to the @code{eval} function, in order to specify a lexical
1081 environment in which to evaluate a form.  @xref{Eval}.  Most Emacs
1082 Lisp programs, however, should not interact directly with lexical
1083 environments in this way; only specialized programs like debuggers.)
1085 @cindex closures, example of using
1086   Lexical bindings have indefinite extent.  Even after a binding
1087 construct has finished executing, its lexical environment can be
1088 ``kept around'' in Lisp objects called @dfn{closures}.  A closure is
1089 created when you define a named or anonymous function with lexical
1090 binding enabled.  @xref{Closures}, for details.
1092   When a closure is called as a function, any lexical variable
1093 references within its definition use the retained lexical environment.
1094 Here is an example:
1096 @example
1097 (defvar my-ticker nil)   ; @r{We will use this dynamically bound}
1098                          ; @r{variable to store a closure.}
1100 (let ((x 0))             ; @r{@code{x} is lexically bound.}
1101   (setq my-ticker (lambda ()
1102                     (setq x (1+ x)))))
1103     @result{} (closure ((x . 0) t) ()
1104           (setq x (1+ x)))
1106 (funcall my-ticker)
1107     @result{} 1
1109 (funcall my-ticker)
1110     @result{} 2
1112 (funcall my-ticker)
1113     @result{} 3
1115 x                        ; @r{Note that @code{x} has no global value.}
1116 @error{} Symbol's value as variable is void: x
1117 @end example
1119 @noindent
1120 The @code{let} binding defines a lexical environment in which the
1121 variable @code{x} is locally bound to 0.  Within this binding
1122 construct, we define a lambda expression which increments @code{x} by
1123 one and returns the incremented value.  This lambda expression is
1124 automatically turned into a closure, in which the lexical environment
1125 lives on even after the @code{let} binding construct has exited.  Each
1126 time we evaluate the closure, it increments @code{x}, using the
1127 binding of @code{x} in that lexical environment.
1129   Note that unlike dynamic variables which are tied to the symbol
1130 object itself, the relationship between lexical variables and symbols
1131 is only present in the interpreter (or compiler).  Therefore,
1132 functions which take a symbol argument (like @code{symbol-value},
1133 @code{boundp}, and @code{set}) can only retrieve or modify a
1134 variable's dynamic binding (i.e., the contents of its symbol's value
1135 cell).
1137 @node Using Lexical Binding
1138 @subsection Using Lexical Binding
1140   When loading an Emacs Lisp file or evaluating a Lisp buffer, lexical
1141 binding is enabled if the buffer-local variable @code{lexical-binding}
1142 is non-@code{nil}:
1144 @defvar lexical-binding
1145 If this buffer-local variable is non-@code{nil}, Emacs Lisp files and
1146 buffers are evaluated using lexical binding instead of dynamic
1147 binding.  (However, special variables are still dynamically bound; see
1148 below.)  If @code{nil}, dynamic binding is used for all local
1149 variables.  This variable is typically set for a whole Emacs Lisp
1150 file, as a file local variable (@pxref{File Local Variables}).
1151 Note that unlike other such variables, this one must be set in the
1152 first line of a file.
1153 @end defvar
1155 @noindent
1156 When evaluating Emacs Lisp code directly using an @code{eval} call,
1157 lexical binding is enabled if the @var{lexical} argument to
1158 @code{eval} is non-@code{nil}.  @xref{Eval}.
1160 @cindex special variables
1161   Even when lexical binding is enabled, certain variables will
1162 continue to be dynamically bound.  These are called @dfn{special
1163 variables}.  Every variable that has been defined with @code{defvar},
1164 @code{defcustom} or @code{defconst} is a special variable
1165 (@pxref{Defining Variables}).  All other variables are subject to
1166 lexical binding.
1168 @defun special-variable-p symbol
1169 This function returns non-@code{nil} if @var{symbol} is a special
1170 variable (i.e., it has a @code{defvar}, @code{defcustom}, or
1171 @code{defconst} variable definition).  Otherwise, the return value is
1172 @code{nil}.
1173 @end defun
1175   The use of a special variable as a formal argument in a function is
1176 discouraged.  Doing so gives rise to unspecified behavior when lexical
1177 binding mode is enabled (it may use lexical binding sometimes, and
1178 dynamic binding other times).
1180   Converting an Emacs Lisp program to lexical binding is easy.  First,
1181 add a file-local variable setting of @code{lexical-binding} to
1182 @code{t} in the header line of the Emacs Lisp source file (@pxref{File
1183 Local Variables}).  Second, check that every variable in the program
1184 which needs to be dynamically bound has a variable definition, so that
1185 it is not inadvertently bound lexically.
1187 @cindex free variable
1188 @cindex unused lexical variable
1189   A simple way to find out which variables need a variable definition
1190 is to byte-compile the source file.  @xref{Byte Compilation}.  If a
1191 non-special variable is used outside of a @code{let} form, the
1192 byte-compiler will warn about reference or assignment to a free
1193 variable.  If a non-special variable is bound but not used within a
1194 @code{let} form, the byte-compiler will warn about an unused lexical
1195 variable.  The byte-compiler will also issue a warning if you use a
1196 special variable as a function argument.
1198   (To silence byte-compiler warnings about unused variables, just use
1199 a variable name that starts with an underscore.  The byte-compiler
1200 interprets this as an indication that this is a variable known not to
1201 be used.)
1203 @node Buffer-Local Variables
1204 @section Buffer-Local Variables
1205 @cindex variable, buffer-local
1206 @cindex buffer-local variables
1208   Global and local variable bindings are found in most programming
1209 languages in one form or another.  Emacs, however, also supports
1210 additional, unusual kinds of variable binding, such as
1211 @dfn{buffer-local} bindings, which apply only in one buffer.  Having
1212 different values for a variable in different buffers is an important
1213 customization method.  (Variables can also have bindings that are
1214 local to each terminal.  @xref{Multiple Terminals}.)
1216 @menu
1217 * Intro to Buffer-Local::       Introduction and concepts.
1218 * Creating Buffer-Local::       Creating and destroying buffer-local bindings.
1219 * Default Value::               The default value is seen in buffers
1220                                  that don't have their own buffer-local values.
1221 @end menu
1223 @node Intro to Buffer-Local
1224 @subsection Introduction to Buffer-Local Variables
1226   A buffer-local variable has a buffer-local binding associated with a
1227 particular buffer.  The binding is in effect when that buffer is
1228 current; otherwise, it is not in effect.  If you set the variable while
1229 a buffer-local binding is in effect, the new value goes in that binding,
1230 so its other bindings are unchanged.  This means that the change is
1231 visible only in the buffer where you made it.
1233   The variable's ordinary binding, which is not associated with any
1234 specific buffer, is called the @dfn{default binding}.  In most cases,
1235 this is the global binding.
1237   A variable can have buffer-local bindings in some buffers but not in
1238 other buffers.  The default binding is shared by all the buffers that
1239 don't have their own bindings for the variable.  (This includes all
1240 newly-created buffers.)  If you set the variable in a buffer that does
1241 not have a buffer-local binding for it, this sets the default binding,
1242 so the new value is visible in all the buffers that see the default
1243 binding.
1245   The most common use of buffer-local bindings is for major modes to change
1246 variables that control the behavior of commands.  For example, C mode and
1247 Lisp mode both set the variable @code{paragraph-start} to specify that only
1248 blank lines separate paragraphs.  They do this by making the variable
1249 buffer-local in the buffer that is being put into C mode or Lisp mode, and
1250 then setting it to the new value for that mode.  @xref{Major Modes}.
1252   The usual way to make a buffer-local binding is with
1253 @code{make-local-variable}, which is what major mode commands typically
1254 use.  This affects just the current buffer; all other buffers (including
1255 those yet to be created) will continue to share the default value unless
1256 they are explicitly given their own buffer-local bindings.
1258 @cindex automatically buffer-local
1259   A more powerful operation is to mark the variable as
1260 @dfn{automatically buffer-local} by calling
1261 @code{make-variable-buffer-local}.  You can think of this as making the
1262 variable local in all buffers, even those yet to be created.  More
1263 precisely, the effect is that setting the variable automatically makes
1264 the variable local to the current buffer if it is not already so.  All
1265 buffers start out by sharing the default value of the variable as usual,
1266 but setting the variable creates a buffer-local binding for the current
1267 buffer.  The new value is stored in the buffer-local binding, leaving
1268 the default binding untouched.  This means that the default value cannot
1269 be changed with @code{setq} in any buffer; the only way to change it is
1270 with @code{setq-default}.
1272   @strong{Warning:} When a variable has buffer-local
1273 bindings in one or more buffers, @code{let} rebinds the binding that's
1274 currently in effect.  For instance, if the current buffer has a
1275 buffer-local value, @code{let} temporarily rebinds that.  If no
1276 buffer-local bindings are in effect, @code{let} rebinds
1277 the default value.  If inside the @code{let} you then change to a
1278 different current buffer in which a different binding is in effect,
1279 you won't see the @code{let} binding any more.  And if you exit the
1280 @code{let} while still in the other buffer, you won't see the
1281 unbinding occur (though it will occur properly).  Here is an example
1282 to illustrate:
1284 @example
1285 @group
1286 (setq foo 'g)
1287 (set-buffer "a")
1288 (make-local-variable 'foo)
1289 @end group
1290 (setq foo 'a)
1291 (let ((foo 'temp))
1292   ;; foo @result{} 'temp  ; @r{let binding in buffer @samp{a}}
1293   (set-buffer "b")
1294   ;; foo @result{} 'g     ; @r{the global value since foo is not local in @samp{b}}
1295   @var{body}@dots{})
1296 @group
1297 foo @result{} 'g        ; @r{exiting restored the local value in buffer @samp{a},}
1298                  ; @r{but we don't see that in buffer @samp{b}}
1299 @end group
1300 @group
1301 (set-buffer "a") ; @r{verify the local value was restored}
1302 foo @result{} 'a
1303 @end group
1304 @end example
1306 @noindent
1307 Note that references to @code{foo} in @var{body} access the
1308 buffer-local binding of buffer @samp{b}.
1310   When a file specifies local variable values, these become buffer-local
1311 values when you visit the file.  @xref{File Variables,,, emacs, The
1312 GNU Emacs Manual}.
1314   A buffer-local variable cannot be made terminal-local
1315 (@pxref{Multiple Terminals}).
1317 @node Creating Buffer-Local
1318 @subsection Creating and Deleting Buffer-Local Bindings
1320 @deffn Command make-local-variable variable
1321 This function creates a buffer-local binding in the current buffer for
1322 @var{variable} (a symbol).  Other buffers are not affected.  The value
1323 returned is @var{variable}.
1325 The buffer-local value of @var{variable} starts out as the same value
1326 @var{variable} previously had.  If @var{variable} was void, it remains
1327 void.
1329 @example
1330 @group
1331 ;; @r{In buffer @samp{b1}:}
1332 (setq foo 5)                ; @r{Affects all buffers.}
1333      @result{} 5
1334 @end group
1335 @group
1336 (make-local-variable 'foo)  ; @r{Now it is local in @samp{b1}.}
1337      @result{} foo
1338 @end group
1339 @group
1340 foo                         ; @r{That did not change}
1341      @result{} 5                   ;   @r{the value.}
1342 @end group
1343 @group
1344 (setq foo 6)                ; @r{Change the value}
1345      @result{} 6                   ;   @r{in @samp{b1}.}
1346 @end group
1347 @group
1349      @result{} 6
1350 @end group
1352 @group
1353 ;; @r{In buffer @samp{b2}, the value hasn't changed.}
1354 (with-current-buffer "b2"
1355   foo)
1356      @result{} 5
1357 @end group
1358 @end example
1360 Making a variable buffer-local within a @code{let}-binding for that
1361 variable does not work reliably, unless the buffer in which you do this
1362 is not current either on entry to or exit from the @code{let}.  This is
1363 because @code{let} does not distinguish between different kinds of
1364 bindings; it knows only which variable the binding was made for.
1366 It is an error to make a constant or a read-only variable
1367 buffer-local.  @xref{Constant Variables}.
1369 If the variable is terminal-local (@pxref{Multiple Terminals}), this
1370 function signals an error.  Such variables cannot have buffer-local
1371 bindings as well.
1373 @strong{Warning:} do not use @code{make-local-variable} for a hook
1374 variable.  The hook variables are automatically made buffer-local as
1375 needed if you use the @var{local} argument to @code{add-hook} or
1376 @code{remove-hook}.
1377 @end deffn
1379 @defmac setq-local variable value
1380 This macro creates a buffer-local binding in the current buffer for
1381 @var{variable}, and gives it the buffer-local value @var{value}.  It
1382 is equivalent to calling @code{make-local-variable} followed by
1383 @code{setq}.  @var{variable} should be an unquoted symbol.
1384 @end defmac
1386 @deffn Command make-variable-buffer-local variable
1387 This function marks @var{variable} (a symbol) automatically
1388 buffer-local, so that any subsequent attempt to set it will make it
1389 local to the current buffer at the time.  Unlike
1390 @code{make-local-variable}, with which it is often confused, this
1391 cannot be undone, and affects the behavior of the variable in all
1392 buffers.
1394 A peculiar wrinkle of this feature is that binding the variable (with
1395 @code{let} or other binding constructs) does not create a buffer-local
1396 binding for it.  Only setting the variable (with @code{set} or
1397 @code{setq}), while the variable does not have a @code{let}-style
1398 binding that was made in the current buffer, does so.
1400 If @var{variable} does not have a default value, then calling this
1401 command will give it a default value of @code{nil}.  If @var{variable}
1402 already has a default value, that value remains unchanged.
1403 Subsequently calling @code{makunbound} on @var{variable} will result
1404 in a void buffer-local value and leave the default value unaffected.
1406 The value returned is @var{variable}.
1408 It is an error to make a constant or a read-only variable
1409 buffer-local.  @xref{Constant Variables}.
1411 @strong{Warning:} Don't assume that you should use
1412 @code{make-variable-buffer-local} for user-option variables, simply
1413 because users @emph{might} want to customize them differently in
1414 different buffers.  Users can make any variable local, when they wish
1415 to.  It is better to leave the choice to them.
1417 The time to use @code{make-variable-buffer-local} is when it is crucial
1418 that no two buffers ever share the same binding.  For example, when a
1419 variable is used for internal purposes in a Lisp program which depends
1420 on having separate values in separate buffers, then using
1421 @code{make-variable-buffer-local} can be the best solution.
1422 @end deffn
1424 @defmac defvar-local variable value &optional docstring
1425 This macro defines @var{variable} as a variable with initial value
1426 @var{value} and @var{docstring}, and marks it as automatically
1427 buffer-local.  It is equivalent to calling @code{defvar} followed by
1428 @code{make-variable-buffer-local}.  @var{variable} should be an
1429 unquoted symbol.
1430 @end defmac
1432 @defun local-variable-p variable &optional buffer
1433 This returns @code{t} if @var{variable} is buffer-local in buffer
1434 @var{buffer} (which defaults to the current buffer); otherwise,
1435 @code{nil}.
1436 @end defun
1438 @defun local-variable-if-set-p variable &optional buffer
1439 This returns @code{t} if @var{variable} either has a buffer-local
1440 value in buffer @var{buffer}, or is automatically buffer-local.
1441 Otherwise, it returns @code{nil}.  If omitted or @code{nil},
1442 @var{buffer} defaults to the current buffer.
1443 @end defun
1445 @defun buffer-local-value variable buffer
1446 This function returns the buffer-local binding of @var{variable} (a
1447 symbol) in buffer @var{buffer}.  If @var{variable} does not have a
1448 buffer-local binding in buffer @var{buffer}, it returns the default
1449 value (@pxref{Default Value}) of @var{variable} instead.
1450 @end defun
1452 @defun buffer-local-variables &optional buffer
1453 This function returns a list describing the buffer-local variables in
1454 buffer @var{buffer}.  (If @var{buffer} is omitted, the current buffer
1455 is used.)  Normally, each list element has the form
1456 @w{@code{(@var{sym} . @var{val})}}, where @var{sym} is a buffer-local
1457 variable (a symbol) and @var{val} is its buffer-local value.  But when
1458 a variable's buffer-local binding in @var{buffer} is void, its list
1459 element is just @var{sym}.
1461 @example
1462 @group
1463 (make-local-variable 'foobar)
1464 (makunbound 'foobar)
1465 (make-local-variable 'bind-me)
1466 (setq bind-me 69)
1467 @end group
1468 (setq lcl (buffer-local-variables))
1469     ;; @r{First, built-in variables local in all buffers:}
1470 @result{} ((mark-active . nil)
1471     (buffer-undo-list . nil)
1472     (mode-name . "Fundamental")
1473     @dots{}
1474 @group
1475     ;; @r{Next, non-built-in buffer-local variables.}
1476     ;; @r{This one is buffer-local and void:}
1477     foobar
1478     ;; @r{This one is buffer-local and nonvoid:}
1479     (bind-me . 69))
1480 @end group
1481 @end example
1483 Note that storing new values into the @sc{cdr}s of cons cells in this
1484 list does @emph{not} change the buffer-local values of the variables.
1485 @end defun
1487 @deffn Command kill-local-variable variable
1488 This function deletes the buffer-local binding (if any) for
1489 @var{variable} (a symbol) in the current buffer.  As a result, the
1490 default binding of @var{variable} becomes visible in this buffer.  This
1491 typically results in a change in the value of @var{variable}, since the
1492 default value is usually different from the buffer-local value just
1493 eliminated.
1495 If you kill the buffer-local binding of a variable that automatically
1496 becomes buffer-local when set, this makes the default value visible in
1497 the current buffer.  However, if you set the variable again, that will
1498 once again create a buffer-local binding for it.
1500 @code{kill-local-variable} returns @var{variable}.
1502 This function is a command because it is sometimes useful to kill one
1503 buffer-local variable interactively, just as it is useful to create
1504 buffer-local variables interactively.
1505 @end deffn
1507 @cindex local variables, killed by major mode
1508 @defun kill-all-local-variables
1509 This function eliminates all the buffer-local variable bindings of the
1510 current buffer except for variables marked as permanent and local
1511 hook functions that have a non-@code{nil} @code{permanent-local-hook}
1512 property (@pxref{Setting Hooks}).  As a result, the buffer will see
1513 the default values of most variables.
1515 This function also resets certain other information pertaining to the
1516 buffer: it sets the local keymap to @code{nil}, the syntax table to the
1517 value of @code{(standard-syntax-table)}, the case table to
1518 @code{(standard-case-table)}, and the abbrev table to the value of
1519 @code{fundamental-mode-abbrev-table}.
1521 The very first thing this function does is run the normal hook
1522 @code{change-major-mode-hook} (see below).
1524 Every major mode command begins by calling this function, which has the
1525 effect of switching to Fundamental mode and erasing most of the effects
1526 of the previous major mode.  To ensure that this does its job, the
1527 variables that major modes set should not be marked permanent.
1529 @code{kill-all-local-variables} returns @code{nil}.
1530 @end defun
1532 @defvar change-major-mode-hook
1533 The function @code{kill-all-local-variables} runs this normal hook
1534 before it does anything else.  This gives major modes a way to arrange
1535 for something special to be done if the user switches to a different
1536 major mode.  It is also useful for buffer-specific minor modes
1537 that should be forgotten if the user changes the major mode.
1539 For best results, make this variable buffer-local, so that it will
1540 disappear after doing its job and will not interfere with the
1541 subsequent major mode.  @xref{Hooks}.
1542 @end defvar
1544 @cindex permanent local variable
1545 A buffer-local variable is @dfn{permanent} if the variable name (a
1546 symbol) has a @code{permanent-local} property that is non-@code{nil}.
1547 Such variables are unaffected by @code{kill-all-local-variables}, and
1548 their local bindings are therefore not cleared by changing major modes.
1549 Permanent locals are appropriate for data pertaining to where the file
1550 came from or how to save it, rather than with how to edit the contents.
1552 @node Default Value
1553 @subsection The Default Value of a Buffer-Local Variable
1554 @cindex default value
1556   The global value of a variable with buffer-local bindings is also
1557 called the @dfn{default} value, because it is the value that is in
1558 effect whenever neither the current buffer nor the selected frame has
1559 its own binding for the variable.
1561   The functions @code{default-value} and @code{setq-default} access and
1562 change a variable's default value regardless of whether the current
1563 buffer has a buffer-local binding.  For example, you could use
1564 @code{setq-default} to change the default setting of
1565 @code{paragraph-start} for most buffers; and this would work even when
1566 you are in a C or Lisp mode buffer that has a buffer-local value for
1567 this variable.
1569 @c Emacs 19 feature
1570   The special forms @code{defvar} and @code{defconst} also set the
1571 default value (if they set the variable at all), rather than any
1572 buffer-local value.
1574 @defun default-value symbol
1575 This function returns @var{symbol}'s default value.  This is the value
1576 that is seen in buffers and frames that do not have their own values for
1577 this variable.  If @var{symbol} is not buffer-local, this is equivalent
1578 to @code{symbol-value} (@pxref{Accessing Variables}).
1579 @end defun
1581 @c Emacs 19 feature
1582 @defun default-boundp symbol
1583 The function @code{default-boundp} tells you whether @var{symbol}'s
1584 default value is nonvoid.  If @code{(default-boundp 'foo)} returns
1585 @code{nil}, then @code{(default-value 'foo)} would get an error.
1587 @code{default-boundp} is to @code{default-value} as @code{boundp} is to
1588 @code{symbol-value}.
1589 @end defun
1591 @defspec setq-default [symbol form]@dots{}
1592 This special form gives each @var{symbol} a new default value, which is
1593 the result of evaluating the corresponding @var{form}.  It does not
1594 evaluate @var{symbol}, but does evaluate @var{form}.  The value of the
1595 @code{setq-default} form is the value of the last @var{form}.
1597 If a @var{symbol} is not buffer-local for the current buffer, and is not
1598 marked automatically buffer-local, @code{setq-default} has the same
1599 effect as @code{setq}.  If @var{symbol} is buffer-local for the current
1600 buffer, then this changes the value that other buffers will see (as long
1601 as they don't have a buffer-local value), but not the value that the
1602 current buffer sees.
1604 @example
1605 @group
1606 ;; @r{In buffer @samp{foo}:}
1607 (make-local-variable 'buffer-local)
1608      @result{} buffer-local
1609 @end group
1610 @group
1611 (setq buffer-local 'value-in-foo)
1612      @result{} value-in-foo
1613 @end group
1614 @group
1615 (setq-default buffer-local 'new-default)
1616      @result{} new-default
1617 @end group
1618 @group
1619 buffer-local
1620      @result{} value-in-foo
1621 @end group
1622 @group
1623 (default-value 'buffer-local)
1624      @result{} new-default
1625 @end group
1627 @group
1628 ;; @r{In (the new) buffer @samp{bar}:}
1629 buffer-local
1630      @result{} new-default
1631 @end group
1632 @group
1633 (default-value 'buffer-local)
1634      @result{} new-default
1635 @end group
1636 @group
1637 (setq buffer-local 'another-default)
1638      @result{} another-default
1639 @end group
1640 @group
1641 (default-value 'buffer-local)
1642      @result{} another-default
1643 @end group
1645 @group
1646 ;; @r{Back in buffer @samp{foo}:}
1647 buffer-local
1648      @result{} value-in-foo
1649 (default-value 'buffer-local)
1650      @result{} another-default
1651 @end group
1652 @end example
1653 @end defspec
1655 @defun set-default symbol value
1656 This function is like @code{setq-default}, except that @var{symbol} is
1657 an ordinary evaluated argument.
1659 @example
1660 @group
1661 (set-default (car '(a b c)) 23)
1662      @result{} 23
1663 @end group
1664 @group
1665 (default-value 'a)
1666      @result{} 23
1667 @end group
1668 @end example
1669 @end defun
1671   A variable can be let-bound (@pxref{Local Variables}) to a value.
1672 This makes its global value shadowed by the binding;
1673 @code{default-value} will then return the value from that binding, not
1674 the global value, and @code{set-default} will be prevented from
1675 setting the global value (it will change the let-bound value instead).
1676 The following two functions allow to reference the global value even
1677 if it's shadowed by a let-binding.
1679 @cindex top-level default value
1680 @defun default-toplevel-value symbol
1681 This function returns the @dfn{top-level} default value of
1682 @var{symbol}, which is its value outside of any let-binding.
1683 @end defun
1685 @example
1686 @group
1687 (defvar variable 'global-value)
1688     @result{} variable
1689 @end group
1690 @group
1691 (let ((variable 'let-binding))
1692   (default-value 'variable))
1693     @result{} let-binding
1694 @end group
1695 @group
1696 (let ((variable 'let-binding))
1697   (default-toplevel-value 'variable))
1698     @result{} global-value
1699 @end group
1700 @end example
1702 @defun set-default-toplevel-value symbol value
1703 This function sets the top-level default value of @var{symbol} to the
1704 specified @var{value}.  This comes in handy when you want to set the
1705 global value of @var{symbol} regardless of whether your code runs in
1706 the context of @var{symbol}'s let-binding.
1707 @end defun
1710 @node File Local Variables
1711 @section File Local Variables
1712 @cindex file local variables
1714   A file can specify local variable values; Emacs uses these to create
1715 buffer-local bindings for those variables in the buffer visiting that
1716 file.  @xref{File Variables, , Local Variables in Files, emacs, The
1717 GNU Emacs Manual}, for basic information about file-local variables.
1718 This section describes the functions and variables that affect how
1719 file-local variables are processed.
1721   If a file-local variable could specify an arbitrary function or Lisp
1722 expression that would be called later, visiting a file could take over
1723 your Emacs.  Emacs protects against this by automatically setting only
1724 those file-local variables whose specified values are known to be
1725 safe.  Other file-local variables are set only if the user agrees.
1727   For additional safety, @code{read-circle} is temporarily bound to
1728 @code{nil} when Emacs reads file-local variables (@pxref{Input
1729 Functions}).  This prevents the Lisp reader from recognizing circular
1730 and shared Lisp structures (@pxref{Circular Objects}).
1732 @defopt enable-local-variables
1733 This variable controls whether to process file-local variables.
1734 The possible values are:
1736 @table @asis
1737 @item @code{t} (the default)
1738 Set the safe variables, and query (once) about any unsafe variables.
1739 @item @code{:safe}
1740 Set only the safe variables and do not query.
1741 @item @code{:all}
1742 Set all the variables and do not query.
1743 @item @code{nil}
1744 Don't set any variables.
1745 @item anything else
1746 Query (once) about all the variables.
1747 @end table
1748 @end defopt
1750 @defvar inhibit-local-variables-regexps
1751 This is a list of regular expressions.  If a file has a name
1752 matching an element of this list, then it is not scanned for
1753 any form of file-local variable.  For examples of why you might want
1754 to use this, @pxref{Auto Major Mode}.
1755 @end defvar
1757 @defun hack-local-variables &optional handle-mode
1758 This function parses, and binds or evaluates as appropriate, any local
1759 variables specified by the contents of the current buffer.  The variable
1760 @code{enable-local-variables} has its effect here.  However, this
1761 function does not look for the @samp{mode:} local variable in the
1762 @w{@samp{-*-}} line.  @code{set-auto-mode} does that, also taking
1763 @code{enable-local-variables} into account (@pxref{Auto Major Mode}).
1765 This function works by walking the alist stored in
1766 @code{file-local-variables-alist} and applying each local variable in
1767 turn.  It calls @code{before-hack-local-variables-hook} and
1768 @code{hack-local-variables-hook} before and after applying the
1769 variables, respectively.  It only calls the before-hook if the alist
1770 is non-@code{nil}; it always calls the other hook.  This
1771 function ignores a @samp{mode} element if it specifies the same major
1772 mode as the buffer already has.
1774 If the optional argument @var{handle-mode} is @code{t}, then all this
1775 function does is return a symbol specifying the major mode, if the
1776 @w{@samp{-*-}} line or the local variables list specifies one, and
1777 @code{nil} otherwise.  It does not set the mode or any other
1778 file-local variable.  If @var{handle-mode} has any value other than
1779 @code{nil} or @code{t}, any settings of @samp{mode} in the
1780 @w{@samp{-*-}} line or the local variables list are ignored, and the
1781 other settings are applied.  If @var{handle-mode} is @code{nil}, all
1782 the file local variables are set.
1783 @end defun
1785 @defvar file-local-variables-alist
1786 This buffer-local variable holds the alist of file-local variable
1787 settings.  Each element of the alist is of the form
1788 @w{@code{(@var{var} . @var{value})}}, where @var{var} is a symbol of
1789 the local variable and @var{value} is its value.  When Emacs visits a
1790 file, it first collects all the file-local variables into this alist,
1791 and then the @code{hack-local-variables} function applies them one by
1792 one.
1793 @end defvar
1795 @defvar before-hack-local-variables-hook
1796 Emacs calls this hook immediately before applying file-local variables
1797 stored in @code{file-local-variables-alist}.
1798 @end defvar
1800 @defvar hack-local-variables-hook
1801 Emacs calls this hook immediately after it finishes applying
1802 file-local variables stored in @code{file-local-variables-alist}.
1803 @end defvar
1805 @cindex safe local variable
1806   You can specify safe values for a variable with a
1807 @code{safe-local-variable} property.  The property has to be a
1808 function of one argument; any value is safe if the function returns
1809 non-@code{nil} given that value.  Many commonly-encountered file
1810 variables have @code{safe-local-variable} properties; these include
1811 @code{fill-column}, @code{fill-prefix}, and @code{indent-tabs-mode}.
1812 For boolean-valued variables that are safe, use @code{booleanp} as the
1813 property value.
1815 @cindex autoload cookie, and safe values of variable
1816   When defining a user option using @code{defcustom}, you can set its
1817 @code{safe-local-variable} property by adding the arguments
1818 @code{:safe @var{function}} to @code{defcustom} (@pxref{Variable
1819 Definitions}).  However, a safety predicate defined using @code{:safe}
1820 will only be known once the package that contains the @code{defcustom}
1821 is loaded, which is often too late.  As an alternative, you can use
1822 the autoload cookie (@pxref{Autoload}) to assign the option its safety
1823 predicate, like this:
1825 @lisp
1826 ;;;###autoload (put '@var{var} 'safe-local-variable '@var{pred})
1827 @end lisp
1829 @noindent
1830 The safe value definitions specified with @code{autoload} are copied
1831 into the package's autoloads file (@file{loaddefs.el} for most
1832 packages bundled with Emacs), and are known to Emacs since the
1833 beginning of a session.
1835 @defopt safe-local-variable-values
1836 This variable provides another way to mark some variable values as
1837 safe.  It is a list of cons cells @code{(@var{var} . @var{val})},
1838 where @var{var} is a variable name and @var{val} is a value which is
1839 safe for that variable.
1841 When Emacs asks the user whether or not to obey a set of file-local
1842 variable specifications, the user can choose to mark them as safe.
1843 Doing so adds those variable/value pairs to
1844 @code{safe-local-variable-values}, and saves it to the user's custom
1845 file.
1846 @end defopt
1848 @defun safe-local-variable-p sym val
1849 This function returns non-@code{nil} if it is safe to give @var{sym}
1850 the value @var{val}, based on the above criteria.
1851 @end defun
1853 @c @cindex risky local variable   Duplicates risky-local-variable
1854   Some variables are considered @dfn{risky}.  If a variable is risky,
1855 it is never entered automatically into
1856 @code{safe-local-variable-values}; Emacs always queries before setting
1857 a risky variable, unless the user explicitly allows a value by
1858 customizing @code{safe-local-variable-values} directly.
1860   Any variable whose name has a non-@code{nil}
1861 @code{risky-local-variable} property is considered risky.  When you
1862 define a user option using @code{defcustom}, you can set its
1863 @code{risky-local-variable} property by adding the arguments
1864 @code{:risky @var{value}} to @code{defcustom} (@pxref{Variable
1865 Definitions}).  In addition, any variable whose name ends in any of
1866 @samp{-command}, @samp{-frame-alist}, @samp{-function},
1867 @samp{-functions}, @samp{-hook}, @samp{-hooks}, @samp{-form},
1868 @samp{-forms}, @samp{-map}, @samp{-map-alist}, @samp{-mode-alist},
1869 @samp{-program}, or @samp{-predicate} is automatically considered
1870 risky.  The variables @samp{font-lock-keywords},
1871 @samp{font-lock-keywords} followed by a digit, and
1872 @samp{font-lock-syntactic-keywords} are also considered risky.
1874 @defun risky-local-variable-p sym
1875 This function returns non-@code{nil} if @var{sym} is a risky variable,
1876 based on the above criteria.
1877 @end defun
1879 @defvar ignored-local-variables
1880 This variable holds a list of variables that should not be given local
1881 values by files.  Any value specified for one of these variables is
1882 completely ignored.
1883 @end defvar
1885   The @samp{Eval:} ``variable'' is also a potential loophole, so Emacs
1886 normally asks for confirmation before handling it.
1888 @defopt enable-local-eval
1889 This variable controls processing of @samp{Eval:} in @samp{-*-} lines
1890 or local variables
1891 lists in files being visited.  A value of @code{t} means process them
1892 unconditionally; @code{nil} means ignore them; anything else means ask
1893 the user what to do for each file.  The default value is @code{maybe}.
1894 @end defopt
1896 @defopt safe-local-eval-forms
1897 This variable holds a list of expressions that are safe to
1898 evaluate when found in the @samp{Eval:} ``variable'' in a file
1899 local variables list.
1900 @end defopt
1902   If the expression is a function call and the function has a
1903 @code{safe-local-eval-function} property, the property value
1904 determines whether the expression is safe to evaluate.  The property
1905 value can be a predicate to call to test the expression, a list of
1906 such predicates (it's safe if any predicate succeeds), or @code{t}
1907 (always safe provided the arguments are constant).
1909   Text properties are also potential loopholes, since their values
1910 could include functions to call.  So Emacs discards all text
1911 properties from string values specified for file-local variables.
1913 @node Directory Local Variables
1914 @section Directory Local Variables
1915 @cindex directory local variables
1917   A directory can specify local variable values common to all files in
1918 that directory; Emacs uses these to create buffer-local bindings for
1919 those variables in buffers visiting any file in that directory.  This
1920 is useful when the files in the directory belong to some @dfn{project}
1921 and therefore share the same local variables.
1923   There are two different methods for specifying directory local
1924 variables: by putting them in a special file, or by defining a
1925 @dfn{project class} for that directory.
1927 @defvr Constant dir-locals-file
1928 This constant is the name of the file where Emacs expects to find the
1929 directory-local variables.  The name of the file is
1930 @file{.dir-locals.el}@footnote{
1931 The MS-DOS version of Emacs uses @file{_dir-locals.el} instead, due to
1932 limitations of the DOS filesystems.
1933 }.  A file by that name in a directory causes Emacs to apply its
1934 settings to any file in that directory or any of its subdirectories
1935 (optionally, you can exclude subdirectories; see below).
1936 If some of the subdirectories have their own @file{.dir-locals.el}
1937 files, Emacs uses the settings from the deepest file it finds starting
1938 from the file's directory and moving up the directory tree.  This
1939 constant is also used to derive the name of a second dir-locals file
1940 @file{.dir-locals-2.el}.  If this second dir-locals file is present,
1941 then that is loaded instead of @file{.dir-locals.el}.  This is useful
1942 when @file{.dir-locals.el} is under version control in a shared
1943 repository and cannot be used for personal customizations.  The file
1944 specifies local variables as a specially formatted list; see
1945 @ref{Directory Variables, , Per-directory Local Variables, emacs, The
1946 GNU Emacs Manual}, for more details.
1947 @end defvr
1949 @defun hack-dir-local-variables
1950 This function reads the @code{.dir-locals.el} file and stores the
1951 directory-local variables in @code{file-local-variables-alist} that is
1952 local to the buffer visiting any file in the directory, without
1953 applying them.  It also stores the directory-local settings in
1954 @code{dir-locals-class-alist}, where it defines a special class for
1955 the directory in which @file{.dir-locals.el} file was found.  This
1956 function works by calling @code{dir-locals-set-class-variables} and
1957 @code{dir-locals-set-directory-class}, described below.
1958 @end defun
1960 @defun hack-dir-local-variables-non-file-buffer
1961 This function looks for directory-local variables, and immediately
1962 applies them in the current buffer.  It is intended to be called in
1963 the mode commands for non-file buffers, such as Dired buffers, to let
1964 them obey directory-local variable settings.  For non-file buffers,
1965 Emacs looks for directory-local variables in @code{default-directory}
1966 and its parent directories.
1967 @end defun
1969 @defun dir-locals-set-class-variables class variables
1970 This function defines a set of variable settings for the named
1971 @var{class}, which is a symbol.  You can later assign the class to one
1972 or more directories, and Emacs will apply those variable settings to
1973 all files in those directories.  The list in @var{variables} can be of
1974 one of the two forms: @code{(@var{major-mode} . @var{alist})} or
1975 @code{(@var{directory} . @var{list})}.  With the first form, if the
1976 file's buffer turns on a mode that is derived from @var{major-mode},
1977 then the all the variables in the associated @var{alist} are applied;
1978 @var{alist} should be of the form @code{(@var{name} . @var{value})}.
1979 A special value @code{nil} for @var{major-mode} means the settings are
1980 applicable to any mode.  In @var{alist}, you can use a special
1981 @var{name}: @code{subdirs}.  If the associated value is
1982 @code{nil}, the alist is only applied to files in the relevant
1983 directory, not to those in any subdirectories.
1985 With the second form of @var{variables}, if @var{directory} is the
1986 initial substring of the file's directory, then @var{list} is applied
1987 recursively by following the above rules; @var{list} should be of one
1988 of the two forms accepted by this function in @var{variables}.
1989 @end defun
1991 @defun dir-locals-set-directory-class directory class &optional mtime
1992 This function assigns @var{class} to all the files in @code{directory}
1993 and its subdirectories.  Thereafter, all the variable settings
1994 specified for @var{class} will be applied to any visited file in
1995 @var{directory} and its children.  @var{class} must have been already
1996 defined by @code{dir-locals-set-class-variables}.
1998 Emacs uses this function internally when it loads directory variables
1999 from a @code{.dir-locals.el} file.  In that case, the optional
2000 argument @var{mtime} holds the file modification time (as returned by
2001 @code{file-attributes}).  Emacs uses this time to check stored
2002 local variables are still valid.  If you are assigning a class
2003 directly, not via a file, this argument should be @code{nil}.
2004 @end defun
2006 @defvar dir-locals-class-alist
2007 This alist holds the class symbols and the associated variable
2008 settings.  It is updated by @code{dir-locals-set-class-variables}.
2009 @end defvar
2011 @defvar dir-locals-directory-cache
2012 This alist holds directory names, their assigned class names, and
2013 modification times of the associated directory local variables file
2014 (if there is one).  The function @code{dir-locals-set-directory-class}
2015 updates this list.
2016 @end defvar
2018 @defvar enable-dir-local-variables
2019 If @code{nil}, directory-local variables are ignored.  This variable
2020 may be useful for modes that want to ignore directory-locals while
2021 still respecting file-local variables (@pxref{File Local Variables}).
2022 @end defvar
2024 @node Connection Local Variables
2025 @section Connection Local Variables
2026 @cindex connection local variables
2028   Connection-local variables provide a general mechanism for different
2029 variable settings in buffers with a remote connection.  They are bound
2030 and set depending on the remote connection a buffer is dedicated to.
2032 @defun connection-local-set-profile-variables profile variables
2033 This function defines a set of variable settings for the connection
2034 @var{profile}, which is a symbol.  You can later assign the connection
2035 profile to one or more remote connections, and Emacs will apply those
2036 variable settings to all process buffers for those connections.  The
2037 list in @var{variables} is an alist of the form
2038 @code{(@var{name}@tie{}.@tie{}@var{value})}.  Example:
2040 @example
2041 @group
2042 (connection-local-set-profile-variables
2043   'remote-bash
2044   '((shell-file-name . "/bin/bash")
2045     (shell-command-switch . "-c")
2046     (shell-interactive-switch . "-i")
2047     (shell-login-switch . "-l")))
2048 @end group
2050 @group
2051 (connection-local-set-profile-variables
2052   'remote-ksh
2053   '((shell-file-name . "/bin/ksh")
2054     (shell-command-switch . "-c")
2055     (shell-interactive-switch . "-i")
2056     (shell-login-switch . "-l")))
2057 @end group
2059 @group
2060 (connection-local-set-profile-variables
2061   'remote-null-device
2062   '((null-device . "/dev/null")))
2063 @end group
2064 @end example
2065 @end defun
2067 @defvar connection-local-profile-alist
2068 This alist holds the connection profile symbols and the associated
2069 variable settings.  It is updated by
2070 @code{connection-local-set-profile-variables}.
2071 @end defvar
2073 @defun connection-local-set-profiles criteria &rest profiles
2074 This function assigns @var{profiles}, which are symbols, to all remote
2075 connections identified by @var{criteria}.  @var{criteria} is a plist
2076 identifying a connection and the application using this connection.
2077 Property names might be @code{:application}, @code{:protocol},
2078 @code{:user} and @code{:machine}.  The property value of
2079 @code{:application} is a symbol, all other property values are
2080 strings.  All properties are optional; if @var{criteria} is @code{nil}, it
2081 always applies.  Example:
2083 @example
2084 @group
2085 (connection-local-set-profiles
2086   '(:application 'tramp :protocol "ssh" :machine "localhost")
2087   'remote-bash 'remote-null-device)
2088 @end group
2090 @group
2091 (connection-local-set-profiles
2092   '(:application 'tramp :protocol "sudo"
2093     :user "root" :machine "localhost")
2094   'remote-ksh 'remote-null-device)
2095 @end group
2096 @end example
2098   If @var{criteria} is @code{nil}, it applies for all remote connections.
2099 Therefore, the example above would be equivalent to
2101 @example
2102 @group
2103 (connection-local-set-profiles
2104   '(:application 'tramp :protocol "ssh" :machine "localhost")
2105   'remote-bash)
2106 @end group
2108 @group
2109 (connection-local-set-profiles
2110   '(:application 'tramp :protocol "sudo"
2111     :user "root" :machine "localhost")
2112   'remote-ksh)
2113 @end group
2115 @group
2116 (connection-local-set-profiles
2117   nil 'remote-null-device)
2118 @end group
2119 @end example
2121   Any connection profile of @var{profiles} must have been already
2122 defined by @code{connection-local-set-profile-variables}.
2123 @end defun
2125 @defvar connection-local-criteria-alist
2126 This alist contains connection criteria and their assigned profile
2127 names.  The function @code{connection-local-set-profiles} updates this
2128 list.
2129 @end defvar
2131 @defun hack-connection-local-variables criteria
2132 This function collects applicable connection-local variables
2133 associated with @var{criteria} in
2134 @code{connection-local-variables-alist}, without applying them.
2135 Example:
2137 @example
2138 @group
2139 (hack-connection-local-variables
2140   '(:application 'tramp :protocol "ssh" :machine "localhost"))
2141 @end group
2143 @group
2144 connection-local-variables-alist
2145      @result{} ((null-device . "/dev/null")
2146         (shell-login-switch . "-l")
2147         (shell-interactive-switch . "-i")
2148         (shell-command-switch . "-c")
2149         (shell-file-name . "/bin/bash"))
2150 @end group
2151 @end example
2152 @end defun
2154 @defun hack-connection-local-variables-apply criteria
2155 This function looks for connection-local variables according to
2156 @var{criteria}, and immediately applies them in the current buffer.
2157 @end defun
2159 @defmac with-connection-local-profiles profiles &rest body
2160 All connection-local variables, which are specified by a connection
2161 profile in @var{profiles}, are applied.
2163 After that, @var{body} is executed, and the connection-local variables
2164 are unwound.  Example:
2166 @example
2167 @group
2168 (connection-local-set-profile-variables
2169   'remote-perl
2170   '((perl-command-name . "/usr/local/bin/perl")
2171     (perl-command-switch . "-e %s")))
2172 @end group
2174 @group
2175 (with-connection-local-profiles '(remote-perl)
2176   do something useful)
2177 @end group
2178 @end example
2179 @end defmac
2181 @defvar enable-connection-local-variables
2182 If @code{nil}, connection-local variables are ignored.  This variable
2183 shall be changed temporarily only in special modes.
2184 @end defvar
2186 @node Variable Aliases
2187 @section Variable Aliases
2188 @cindex variable aliases
2189 @cindex alias, for variables
2191   It is sometimes useful to make two variables synonyms, so that both
2192 variables always have the same value, and changing either one also
2193 changes the other.  Whenever you change the name of a
2194 variable---either because you realize its old name was not well
2195 chosen, or because its meaning has partly changed---it can be useful
2196 to keep the old name as an @emph{alias} of the new one for
2197 compatibility.  You can do this with @code{defvaralias}.
2199 @defun defvaralias new-alias base-variable &optional docstring
2200 This function defines the symbol @var{new-alias} as a variable alias
2201 for symbol @var{base-variable}. This means that retrieving the value
2202 of @var{new-alias} returns the value of @var{base-variable}, and
2203 changing the value of @var{new-alias} changes the value of
2204 @var{base-variable}.  The two aliased variable names always share the
2205 same value and the same bindings.
2207 If the @var{docstring} argument is non-@code{nil}, it specifies the
2208 documentation for @var{new-alias}; otherwise, the alias gets the same
2209 documentation as @var{base-variable} has, if any, unless
2210 @var{base-variable} is itself an alias, in which case @var{new-alias} gets
2211 the documentation of the variable at the end of the chain of aliases.
2213 This function returns @var{base-variable}.
2214 @end defun
2216   Variable aliases are convenient for replacing an old name for a
2217 variable with a new name.  @code{make-obsolete-variable} declares that
2218 the old name is obsolete and therefore that it may be removed at some
2219 stage in the future.
2221 @defun make-obsolete-variable obsolete-name current-name when &optional access-type
2222 This function makes the byte compiler warn that the variable
2223 @var{obsolete-name} is obsolete.  If @var{current-name} is a symbol,
2224 it is the variable's new name; then the warning message says to use
2225 @var{current-name} instead of @var{obsolete-name}.  If
2226 @var{current-name} is a string, this is the message and there is no
2227 replacement variable.  @var{when} should be a string indicating when
2228 the variable was first made obsolete (usually a version number
2229 string).
2231 The optional argument @var{access-type}, if non-@code{nil}, should
2232 specify the kind of access that will trigger obsolescence warnings; it
2233 can be either @code{get} or @code{set}.
2234 @end defun
2236   You can make two variables synonyms and declare one obsolete at the
2237 same time using the macro @code{define-obsolete-variable-alias}.
2239 @defmac define-obsolete-variable-alias obsolete-name current-name &optional when docstring
2240 This macro marks the variable @var{obsolete-name} as obsolete and also
2241 makes it an alias for the variable @var{current-name}.  It is
2242 equivalent to the following:
2244 @example
2245 (defvaralias @var{obsolete-name} @var{current-name} @var{docstring})
2246 (make-obsolete-variable @var{obsolete-name} @var{current-name} @var{when})
2247 @end example
2248 @end defmac
2250 @defun indirect-variable variable
2251 This function returns the variable at the end of the chain of aliases
2252 of @var{variable}.  If @var{variable} is not a symbol, or if @var{variable} is
2253 not defined as an alias, the function returns @var{variable}.
2255 This function signals a @code{cyclic-variable-indirection} error if
2256 there is a loop in the chain of symbols.
2257 @end defun
2259 @example
2260 (defvaralias 'foo 'bar)
2261 (indirect-variable 'foo)
2262      @result{} bar
2263 (indirect-variable 'bar)
2264      @result{} bar
2265 (setq bar 2)
2267      @result{} 2
2268 @group
2270      @result{} 2
2271 @end group
2272 (setq foo 0)
2274      @result{} 0
2276      @result{} 0
2277 @end example
2279 @node Variables with Restricted Values
2280 @section Variables with Restricted Values
2281 @cindex lisp variables defined in C, restrictions
2283   Ordinary Lisp variables can be assigned any value that is a valid
2284 Lisp object.  However, certain Lisp variables are not defined in Lisp,
2285 but in C@.  Most of these variables are defined in the C code using
2286 @code{DEFVAR_LISP}.  Like variables defined in Lisp, these can take on
2287 any value.  However, some variables are defined using
2288 @code{DEFVAR_INT} or @code{DEFVAR_BOOL}.  @xref{Defining Lisp
2289 variables in C,, Writing Emacs Primitives}, in particular the
2290 description of functions of the type @code{syms_of_@var{filename}},
2291 for a brief discussion of the C implementation.
2293   Variables of type @code{DEFVAR_BOOL} can only take on the values
2294 @code{nil} or @code{t}.  Attempting to assign them any other value
2295 will set them to @code{t}:
2297 @example
2298 (let ((display-hourglass 5))
2299   display-hourglass)
2300      @result{} t
2301 @end example
2303 @defvar byte-boolean-vars
2304 This variable holds a list of all variables of type @code{DEFVAR_BOOL}.
2305 @end defvar
2307   Variables of type @code{DEFVAR_INT} can take on only integer values.
2308 Attempting to assign them any other value will result in an error:
2310 @example
2311 (setq undo-limit 1000.0)
2312 @error{} Wrong type argument: integerp, 1000.0
2313 @end example
2315 @node Generalized Variables
2316 @section Generalized Variables
2318 @cindex generalized variable
2319 @cindex place form
2320 A @dfn{generalized variable} or @dfn{place form} is one of the many places
2321 in Lisp memory where values can be stored.  The simplest place form is
2322 a regular Lisp variable.  But the @sc{car}s and @sc{cdr}s of lists, elements
2323 of arrays, properties of symbols, and many other locations are also
2324 places where Lisp values are stored.
2326 Generalized variables are analogous to lvalues in the C
2327 language, where @samp{x = a[i]} gets an element from an array
2328 and @samp{a[i] = x} stores an element using the same notation.
2329 Just as certain forms like @code{a[i]} can be lvalues in C, there
2330 is a set of forms that can be generalized variables in Lisp.
2332 @menu
2333 * Setting Generalized Variables::   The @code{setf} macro.
2334 * Adding Generalized Variables::    Defining new @code{setf} forms.
2335 @end menu
2337 @node Setting Generalized Variables
2338 @subsection The @code{setf} Macro
2340 The @code{setf} macro is the most basic way to operate on generalized
2341 variables.  The @code{setf} form is like @code{setq}, except that it
2342 accepts arbitrary place forms on the left side rather than just
2343 symbols.  For example, @code{(setf (car a) b)} sets the car of
2344 @code{a} to @code{b}, doing the same operation as @code{(setcar a b)},
2345 but without having to remember two separate functions for setting and
2346 accessing every type of place.
2348 @defmac setf [place form]@dots{}
2349 This macro evaluates @var{form} and stores it in @var{place}, which
2350 must be a valid generalized variable form.  If there are several
2351 @var{place} and @var{form} pairs, the assignments are done sequentially
2352 just as with @code{setq}.  @code{setf} returns the value of the last
2353 @var{form}.
2354 @end defmac
2356 The following Lisp forms will work as generalized variables, and
2357 so may appear in the @var{place} argument of @code{setf}:
2359 @itemize
2360 @item
2361 A symbol naming a variable.  In other words, @code{(setf x y)} is
2362 exactly equivalent to @code{(setq x y)}, and @code{setq} itself is
2363 strictly speaking redundant given that @code{setf} exists.  Many
2364 programmers continue to prefer @code{setq} for setting simple
2365 variables, though, purely for stylistic or historical reasons.
2366 The macro @code{(setf x y)} actually expands to @code{(setq x y)},
2367 so there is no performance penalty for using it in compiled code.
2369 @item
2370 A call to any of the following standard Lisp functions:
2372 @smallexample
2373 aref      cddr      symbol-function
2374 car       elt       symbol-plist
2375 caar      get       symbol-value
2376 cadr      gethash
2377 cdr       nth
2378 cdar      nthcdr
2379 @end smallexample
2381 @item
2382 A call to any of the following Emacs-specific functions:
2384 @smallexample
2385 alist-get                     process-get
2386 frame-parameter               process-sentinel
2387 terminal-parameter            window-buffer
2388 keymap-parent                 window-display-table
2389 match-data                    window-dedicated-p
2390 overlay-get                   window-hscroll
2391 overlay-start                 window-parameter
2392 overlay-end                   window-point
2393 process-buffer                window-start
2394 process-filter                default-value
2395 @end smallexample
2396 @end itemize
2398 @noindent
2399 @code{setf} signals an error if you pass a @var{place} form that it
2400 does not know how to handle.
2402 @c And for cl-lib's cl-getf.
2403 Note that for @code{nthcdr}, the list argument of the function must
2404 itself be a valid @var{place} form.  For example, @code{(setf (nthcdr
2405 0 foo) 7)} will set @code{foo} itself to 7.
2406 @c The use of @code{nthcdr} as a @var{place} form is an extension
2407 @c to standard Common Lisp.
2409 @c FIXME I don't think is a particularly good way to do it,
2410 @c but these macros are introduced before generalized variables are.
2411 The macros @code{push} (@pxref{List Variables}) and @code{pop}
2412 (@pxref{List Elements}) can manipulate generalized variables,
2413 not just lists.  @code{(pop @var{place})} removes and returns the first
2414 element of the list stored in @var{place}.  It is analogous to
2415 @code{(prog1 (car @var{place}) (setf @var{place} (cdr @var{place})))},
2416 except that it takes care to evaluate all subforms only once.
2417 @code{(push @var{x} @var{place})} inserts @var{x} at the front of
2418 the list stored in @var{place}.  It is analogous to @code{(setf
2419 @var{place} (cons @var{x} @var{place}))}, except for evaluation of the
2420 subforms.  Note that @code{push} and @code{pop} on an @code{nthcdr}
2421 place can be used to insert or delete at any position in a list.
2423 The @file{cl-lib} library defines various extensions for generalized
2424 variables, including additional @code{setf} places.
2425 @xref{Generalized Variables,,, cl, Common Lisp Extensions}.
2428 @node Adding Generalized Variables
2429 @subsection Defining new @code{setf} forms
2431 This section describes how to define new forms that @code{setf} can
2432 operate on.
2434 @defmac gv-define-simple-setter name setter &optional fix-return
2435 This macro enables you to easily define @code{setf} methods for simple
2436 cases.  @var{name} is the name of a function, macro, or special form.
2437 You can use this macro whenever @var{name} has a directly
2438 corresponding @var{setter} function that updates it, e.g.,
2439 @code{(gv-define-simple-setter car setcar)}.
2441 This macro translates a call of the form
2443 @example
2444 (setf (@var{name} @var{args}@dots{}) @var{value})
2445 @end example
2447 into
2448 @example
2449 (@var{setter} @var{args}@dots{} @var{value})
2450 @end example
2452 @noindent
2453 Such a @code{setf} call is documented to return @var{value}.  This is
2454 no problem with, e.g., @code{car} and @code{setcar}, because
2455 @code{setcar} returns the value that it set.  If your @var{setter}
2456 function does not return @var{value}, use a non-@code{nil} value for
2457 the @var{fix-return} argument of @code{gv-define-simple-setter}.  This
2458 expands into something equivalent to
2459 @example
2460 (let ((temp @var{value}))
2461   (@var{setter} @var{args}@dots{} temp)
2462   temp)
2463 @end example
2464 so ensuring that it returns the correct result.
2465 @end defmac
2468 @defmac gv-define-setter name arglist &rest body
2469 This macro allows for more complex @code{setf} expansions than the
2470 previous form.  You may need to use this form, for example, if there
2471 is no simple setter function to call, or if there is one but it
2472 requires different arguments to the place form.
2474 This macro expands the form
2475 @code{(setf (@var{name} @var{args}@dots{}) @var{value})} by
2476 first binding the @code{setf} argument forms
2477 @code{(@var{value} @var{args}@dots{})} according to @var{arglist},
2478 and then executing @var{body}.  @var{body} should return a Lisp
2479 form that does the assignment, and finally returns the value that was
2480 set.  An example of using this macro is:
2482 @example
2483 (gv-define-setter caar (val x) `(setcar (car ,x) ,val))
2484 @end example
2485 @end defmac
2487 @findex gv-define-expander
2488 @findex gv-letplace
2489 @c FIXME?  Not sure what or how much to say about these.
2490 @c See cl.texi for an example of using gv-letplace.
2491 For more control over the expansion, see the macro @code{gv-define-expander}.
2492 The macro @code{gv-letplace} can be useful in defining macros that
2493 perform similarly to @code{setf}; for example, the @code{incf} macro
2494 of Common Lisp.  Consult the source file @file{gv.el} for more details.
2496 @cindex CL note---no @code{setf} functions
2497 @quotation
2498 @b{Common Lisp note:} Common Lisp defines another way to specify the
2499 @code{setf} behavior of a function, namely @code{setf} functions,
2500 whose names are lists @code{(setf @var{name})} rather than symbols.
2501 For example, @code{(defun (setf foo) @dots{})} defines the function
2502 that is used when @code{setf} is applied to @code{foo}.  Emacs does
2503 not support this.  It is a compile-time error to use @code{setf} on a
2504 form that has not already had an appropriate expansion defined.  In
2505 Common Lisp, this is not an error since the function @code{(setf
2506 @var{func})} might be defined later.
2507 @end quotation