Add seq-set-equal-p to test for set equality
[emacs.git] / doc / lispref / variables.texi
blob2818ea067d23e3969fd5cbde5c423a4dd63d6911
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998-2017 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 @node Local Variables
143 @section Local Variables
144 @cindex binding local variables
145 @cindex local variables
146 @cindex local binding
147 @cindex global binding
149   Global variables have values that last until explicitly superseded
150 with new values.  Sometimes it is useful to give a variable a
151 @dfn{local value}---a value that takes effect only within a certain
152 part of a Lisp program.  When a variable has a local value, we say
153 that it is @dfn{locally bound} to that value, and that it is a
154 @dfn{local variable}.
156   For example, when a function is called, its argument variables
157 receive local values, which are the actual arguments supplied to the
158 function call; these local bindings take effect within the body of the
159 function.  To take another example, the @code{let} special form
160 explicitly establishes local bindings for specific variables, which
161 take effect within the body of the @code{let} form.
163   We also speak of the @dfn{global binding}, which is where
164 (conceptually) the global value is kept.
166 @cindex shadowing of variables
167   Establishing a local binding saves away the variable's previous
168 value (or lack of one).  We say that the previous value is
169 @dfn{shadowed}.  Both global and local values may be shadowed.  If a
170 local binding is in effect, using @code{setq} on the local variable
171 stores the specified value in the local binding.  When that local
172 binding is no longer in effect, the previously shadowed value (or lack
173 of one) comes back.
175 @cindex current binding
176   A variable can have more than one local binding at a time (e.g., if
177 there are nested @code{let} forms that bind the variable).  The
178 @dfn{current binding} is the local binding that is actually in effect.
179 It determines the value returned by evaluating the variable symbol,
180 and it is the binding acted on by @code{setq}.
182   For most purposes, you can think of the current binding as the
183 innermost local binding, or the global binding if there is no
184 local binding.  To be more precise, a rule called the @dfn{scoping
185 rule} determines where in a program a local binding takes effect.  The
186 default scoping rule in Emacs Lisp is called @dfn{dynamic scoping},
187 which simply states that the current binding at any given point in the
188 execution of a program is the most recently-created binding for that
189 variable that still exists.  For details about dynamic scoping, and an
190 alternative scoping rule called @dfn{lexical scoping}, @xref{Variable
191 Scoping}.
193   The special forms @code{let} and @code{let*} exist to create local
194 bindings:
196 @defspec let (bindings@dots{}) forms@dots{}
197 This special form sets up local bindings for a certain set of
198 variables, as specified by @var{bindings}, and then evaluates all of
199 the @var{forms} in textual order.  Its return value is the value of
200 the last form in @var{forms}.
202 Each of the @var{bindings} is either @w{(i) a} symbol, in which case
203 that symbol is locally bound to @code{nil}; or @w{(ii) a} list of the
204 form @code{(@var{symbol} @var{value-form})}, in which case
205 @var{symbol} is locally bound to the result of evaluating
206 @var{value-form}.  If @var{value-form} is omitted, @code{nil} is used.
208 All of the @var{value-form}s in @var{bindings} are evaluated in the
209 order they appear and @emph{before} binding any of the symbols to them.
210 Here is an example of this: @code{z} is bound to the old value of
211 @code{y}, which is 2, not the new value of @code{y}, which is 1.
213 @example
214 @group
215 (setq y 2)
216      @result{} 2
217 @end group
219 @group
220 (let ((y 1)
221       (z y))
222   (list y z))
223      @result{} (1 2)
224 @end group
225 @end example
227 On the other hand, the order of @emph{bindings} is unspecified: in the
228 following example, either 1 or 2 might be printed.
230 @example
231 (let ((x 1)
232       (x 2))
233   (print x))
234 @end example
236 Therefore, avoid binding a variable more than once in a single
237 @code{let} form.
238 @end defspec
240 @defspec let* (bindings@dots{}) forms@dots{}
241 This special form is like @code{let}, but it binds each variable right
242 after computing its local value, before computing the local value for
243 the next variable.  Therefore, an expression in @var{bindings} can
244 refer to the preceding symbols bound in this @code{let*} form.
245 Compare the following example with the example above for @code{let}.
247 @example
248 @group
249 (setq y 2)
250      @result{} 2
251 @end group
253 @group
254 (let* ((y 1)
255        (z y))    ; @r{Use the just-established value of @code{y}.}
256   (list y z))
257      @result{} (1 1)
258 @end group
259 @end example
260 @end defspec
262   Here is a complete list of the other facilities that create local
263 bindings:
265 @itemize @bullet
266 @item
267 Function calls (@pxref{Functions}).
269 @item
270 Macro calls (@pxref{Macros}).
272 @item
273 @code{condition-case} (@pxref{Errors}).
274 @end itemize
276   Variables can also have buffer-local bindings (@pxref{Buffer-Local
277 Variables}); a few variables have terminal-local bindings
278 (@pxref{Multiple Terminals}).  These kinds of bindings work somewhat
279 like ordinary local bindings, but they are localized depending on
280 where you are in Emacs.
282 @defopt max-specpdl-size
283 @anchor{Definition of max-specpdl-size}
284 @cindex variable limit error
285 @cindex evaluation error
286 @cindex infinite recursion
287 This variable defines the limit on the total number of local variable
288 bindings and @code{unwind-protect} cleanups (see @ref{Cleanups,,
289 Cleaning Up from Nonlocal Exits}) that are allowed before Emacs
290 signals an error (with data @code{"Variable binding depth exceeds
291 max-specpdl-size"}).
293 This limit, with the associated error when it is exceeded, is one way
294 that Lisp avoids infinite recursion on an ill-defined function.
295 @code{max-lisp-eval-depth} provides another limit on depth of nesting.
296 @xref{Definition of max-lisp-eval-depth,, Eval}.
298 The default value is 1300.  Entry to the Lisp debugger increases the
299 value, if there is little room left, to make sure the debugger itself
300 has room to execute.
301 @end defopt
303 @node Void Variables
304 @section When a Variable is Void
305 @cindex @code{void-variable} error
306 @cindex void variable
308   We say that a variable is void if its symbol has an unassigned value
309 cell (@pxref{Symbol Components}).
311   Under Emacs Lisp's default dynamic scoping rule (@pxref{Variable
312 Scoping}), the value cell stores the variable's current (local or
313 global) value.  Note that an unassigned value cell is @emph{not} the
314 same as having @code{nil} in the value cell.  The symbol @code{nil} is
315 a Lisp object and can be the value of a variable, just as any other
316 object can be; but it is still a value.  If a variable is void, trying
317 to evaluate the variable signals a @code{void-variable} error, instead
318 of returning a value.
320   Under the optional lexical scoping rule, the value cell only holds
321 the variable's global value---the value outside of any lexical binding
322 construct.  When a variable is lexically bound, the local value is
323 determined by the lexical environment; hence, variables can have local
324 values even if their symbols' value cells are unassigned.
326 @defun makunbound symbol
327 This function empties out the value cell of @var{symbol}, making the
328 variable void.  It returns @var{symbol}.
330 If @var{symbol} has a dynamic local binding, @code{makunbound} voids
331 the current binding, and this voidness lasts only as long as the local
332 binding is in effect.  Afterwards, the previously shadowed local or
333 global binding is reexposed; then the variable will no longer be void,
334 unless the reexposed binding is void too.
336 Here are some examples (assuming dynamic binding is in effect):
338 @smallexample
339 @group
340 (setq x 1)               ; @r{Put a value in the global binding.}
341      @result{} 1
342 (let ((x 2))             ; @r{Locally bind it.}
343   (makunbound 'x)        ; @r{Void the local binding.}
344   x)
345 @error{} Symbol's value as variable is void: x
346 @end group
347 @group
348 x                        ; @r{The global binding is unchanged.}
349      @result{} 1
351 (let ((x 2))             ; @r{Locally bind it.}
352   (let ((x 3))           ; @r{And again.}
353     (makunbound 'x)      ; @r{Void the innermost-local binding.}
354     x))                  ; @r{And refer: it's void.}
355 @error{} Symbol's value as variable is void: x
356 @end group
358 @group
359 (let ((x 2))
360   (let ((x 3))
361     (makunbound 'x))     ; @r{Void inner binding, then remove it.}
362   x)                     ; @r{Now outer @code{let} binding is visible.}
363      @result{} 2
364 @end group
365 @end smallexample
366 @end defun
368 @defun boundp variable
369 This function returns @code{t} if @var{variable} (a symbol) is not
370 void, and @code{nil} if it is void.
372 Here are some examples (assuming dynamic binding is in effect):
374 @smallexample
375 @group
376 (boundp 'abracadabra)          ; @r{Starts out void.}
377      @result{} nil
378 @end group
379 @group
380 (let ((abracadabra 5))         ; @r{Locally bind it.}
381   (boundp 'abracadabra))
382      @result{} t
383 @end group
384 @group
385 (boundp 'abracadabra)          ; @r{Still globally void.}
386      @result{} nil
387 @end group
388 @group
389 (setq abracadabra 5)           ; @r{Make it globally nonvoid.}
390      @result{} 5
391 @end group
392 @group
393 (boundp 'abracadabra)
394      @result{} t
395 @end group
396 @end smallexample
397 @end defun
399 @node Defining Variables
400 @section Defining Global Variables
401 @cindex variable definition
403   A @dfn{variable definition} is a construct that announces your
404 intention to use a symbol as a global variable.  It uses the special
405 forms @code{defvar} or @code{defconst}, which are documented below.
407   A variable definition serves three purposes.  First, it informs
408 people who read the code that the symbol is @emph{intended} to be used
409 a certain way (as a variable).  Second, it informs the Lisp system of
410 this, optionally supplying an initial value and a documentation
411 string.  Third, it provides information to programming tools such as
412 @command{etags}, allowing them to find where the variable was defined.
414   The difference between @code{defconst} and @code{defvar} is mainly a
415 matter of intent, serving to inform human readers of whether the value
416 should ever change.  Emacs Lisp does not actually prevent you from
417 changing the value of a variable defined with @code{defconst}.  One
418 notable difference between the two forms is that @code{defconst}
419 unconditionally initializes the variable, whereas @code{defvar}
420 initializes it only if it is originally void.
422   To define a customizable variable, you should use @code{defcustom}
423 (which calls @code{defvar} as a subroutine).  @xref{Variable
424 Definitions}.
426 @defspec defvar symbol [value [doc-string]]
427 This special form defines @var{symbol} as a variable.  Note that
428 @var{symbol} is not evaluated; the symbol to be defined should appear
429 explicitly in the @code{defvar} form.  The variable is marked as
430 @dfn{special}, meaning that it should always be dynamically bound
431 (@pxref{Variable Scoping}).
433 If @var{value} is specified, and @var{symbol} is void (i.e., it has no
434 dynamically bound value; @pxref{Void Variables}), then @var{value} is
435 evaluated and @var{symbol} is set to the result.  But if @var{symbol}
436 is not void, @var{value} is not evaluated, and @var{symbol}'s value is
437 left unchanged.  If @var{value} is omitted, the value of @var{symbol}
438 is not changed in any case.
440 If @var{symbol} has a buffer-local binding in the current buffer,
441 @code{defvar} acts on the default value, which is buffer-independent,
442 rather than the buffer-local binding.  It sets the default value if
443 the default value is void.  @xref{Buffer-Local Variables}.
445 If @var{symbol} is already lexically bound (e.g., if the @code{defvar}
446 form occurs in a @code{let} form with lexical binding enabled), then
447 @code{defvar} sets the dynamic value.  The lexical binding remains in
448 effect until its binding construct exits.  @xref{Variable Scoping}.
450 When you evaluate a top-level @code{defvar} form with @kbd{C-M-x} in
451 Emacs Lisp mode (@code{eval-defun}), a special feature of
452 @code{eval-defun} arranges to set the variable unconditionally, without
453 testing whether its value is void.
455 If the @var{doc-string} argument is supplied, it specifies the
456 documentation string for the variable (stored in the symbol's
457 @code{variable-documentation} property).  @xref{Documentation}.
459 Here are some examples.  This form defines @code{foo} but does not
460 initialize it:
462 @example
463 @group
464 (defvar foo)
465      @result{} foo
466 @end group
467 @end example
469 This example initializes the value of @code{bar} to @code{23}, and gives
470 it a documentation string:
472 @example
473 @group
474 (defvar bar 23
475   "The normal weight of a bar.")
476      @result{} bar
477 @end group
478 @end example
480 The @code{defvar} form returns @var{symbol}, but it is normally used
481 at top level in a file where its value does not matter.
482 @end defspec
484 @cindex constant variables
485 @defspec defconst symbol value [doc-string]
486 This special form defines @var{symbol} as a value and initializes it.
487 It informs a person reading your code that @var{symbol} has a standard
488 global value, established here, that should not be changed by the user
489 or by other programs.  Note that @var{symbol} is not evaluated; the
490 symbol to be defined must appear explicitly in the @code{defconst}.
492 The @code{defconst} form, like @code{defvar}, marks the variable as
493 @dfn{special}, meaning that it should always be dynamically bound
494 (@pxref{Variable Scoping}).  In addition, it marks the variable as
495 risky (@pxref{File Local Variables}).
497 @code{defconst} always evaluates @var{value}, and sets the value of
498 @var{symbol} to the result.  If @var{symbol} does have a buffer-local
499 binding in the current buffer, @code{defconst} sets the default value,
500 not the buffer-local value.  (But you should not be making
501 buffer-local bindings for a symbol that is defined with
502 @code{defconst}.)
504 An example of the use of @code{defconst} is Emacs's definition of
505 @code{float-pi}---the mathematical constant @math{pi}, which ought not
506 to be changed by anyone (attempts by the Indiana State Legislature
507 notwithstanding).  As the second form illustrates, however,
508 @code{defconst} is only advisory.
510 @example
511 @group
512 (defconst float-pi 3.141592653589793 "The value of Pi.")
513      @result{} float-pi
514 @end group
515 @group
516 (setq float-pi 3)
517      @result{} float-pi
518 @end group
519 @group
520 float-pi
521      @result{} 3
522 @end group
523 @end example
524 @end defspec
526   @strong{Warning:} If you use a @code{defconst} or @code{defvar}
527 special form while the variable has a local binding (made with
528 @code{let}, or a function argument), it sets the local binding rather
529 than the global binding.  This is not what you usually want.  To
530 prevent this, use these special forms at top level in a file, where
531 normally no local binding is in effect, and make sure to load the file
532 before making a local binding for the variable.
534 @node Tips for Defining
535 @section Tips for Defining Variables Robustly
537   When you define a variable whose value is a function, or a list of
538 functions, use a name that ends in @samp{-function} or
539 @samp{-functions}, respectively.
541   There are several other variable name conventions;
542 here is a complete list:
544 @table @samp
545 @item @dots{}-hook
546 The variable is a normal hook (@pxref{Hooks}).
548 @item @dots{}-function
549 The value is a function.
551 @item @dots{}-functions
552 The value is a list of functions.
554 @item @dots{}-form
555 The value is a form (an expression).
557 @item @dots{}-forms
558 The value is a list of forms (expressions).
560 @item @dots{}-predicate
561 The value is a predicate---a function of one argument that returns
562 non-@code{nil} for success and @code{nil} for failure.
564 @item @dots{}-flag
565 The value is significant only as to whether it is @code{nil} or not.
566 Since such variables often end up acquiring more values over time,
567 this convention is not strongly recommended.
569 @item @dots{}-program
570 The value is a program name.
572 @item @dots{}-command
573 The value is a whole shell command.
575 @item @dots{}-switches
576 The value specifies options for a command.
577 @end table
579   When you define a variable, always consider whether you should mark
580 it as safe or risky; see @ref{File Local Variables}.
582   When defining and initializing a variable that holds a complicated
583 value (such as a keymap with bindings in it), it's best to put the
584 entire computation of the value into the @code{defvar}, like this:
586 @example
587 (defvar my-mode-map
588   (let ((map (make-sparse-keymap)))
589     (define-key map "\C-c\C-a" 'my-command)
590     @dots{}
591     map)
592   @var{docstring})
593 @end example
595 @noindent
596 This method has several benefits.  First, if the user quits while
597 loading the file, the variable is either still uninitialized or
598 initialized properly, never in-between.  If it is still uninitialized,
599 reloading the file will initialize it properly.  Second, reloading the
600 file once the variable is initialized will not alter it; that is
601 important if the user has run hooks to alter part of the contents
602 (such as, to rebind keys).  Third, evaluating the @code{defvar} form
603 with @kbd{C-M-x} will reinitialize the map completely.
605   Putting so much code in the @code{defvar} form has one disadvantage:
606 it puts the documentation string far away from the line which names the
607 variable.  Here's a safe way to avoid that:
609 @example
610 (defvar my-mode-map nil
611   @var{docstring})
612 (unless my-mode-map
613   (let ((map (make-sparse-keymap)))
614     (define-key map "\C-c\C-a" 'my-command)
615     @dots{}
616     (setq my-mode-map map)))
617 @end example
619 @noindent
620 This has all the same advantages as putting the initialization inside
621 the @code{defvar}, except that you must type @kbd{C-M-x} twice, once on
622 each form, if you do want to reinitialize the variable.
624 @node Accessing Variables
625 @section Accessing Variable Values
627   The usual way to reference a variable is to write the symbol which
628 names it.  @xref{Symbol Forms}.
630   Occasionally, you may want to reference a variable which is only
631 determined at run time.  In that case, you cannot specify the variable
632 name in the text of the program.  You can use the @code{symbol-value}
633 function to extract the value.
635 @defun symbol-value symbol
636 This function returns the value stored in @var{symbol}'s value cell.
637 This is where the variable's current (dynamic) value is stored.  If
638 the variable has no local binding, this is simply its global value.
639 If the variable is void, a @code{void-variable} error is signaled.
641 If the variable is lexically bound, the value reported by
642 @code{symbol-value} is not necessarily the same as the variable's
643 lexical value, which is determined by the lexical environment rather
644 than the symbol's value cell.  @xref{Variable Scoping}.
646 @example
647 @group
648 (setq abracadabra 5)
649      @result{} 5
650 @end group
651 @group
652 (setq foo 9)
653      @result{} 9
654 @end group
656 @group
657 ;; @r{Here the symbol @code{abracadabra}}
658 ;;   @r{is the symbol whose value is examined.}
659 (let ((abracadabra 'foo))
660   (symbol-value 'abracadabra))
661      @result{} foo
662 @end group
664 @group
665 ;; @r{Here, the value of @code{abracadabra},}
666 ;;   @r{which is @code{foo},}
667 ;;   @r{is the symbol whose value is examined.}
668 (let ((abracadabra 'foo))
669   (symbol-value abracadabra))
670      @result{} 9
671 @end group
673 @group
674 (symbol-value 'abracadabra)
675      @result{} 5
676 @end group
677 @end example
678 @end defun
680 @node Setting Variables
681 @section Setting Variable Values
683   The usual way to change the value of a variable is with the special
684 form @code{setq}.  When you need to compute the choice of variable at
685 run time, use the function @code{set}.
687 @defspec setq [symbol form]@dots{}
688 This special form is the most common method of changing a variable's
689 value.  Each @var{symbol} is given a new value, which is the result of
690 evaluating the corresponding @var{form}.  The current binding of the
691 symbol is changed.
693 @code{setq} does not evaluate @var{symbol}; it sets the symbol that you
694 write.  We say that this argument is @dfn{automatically quoted}.  The
695 @samp{q} in @code{setq} stands for ``quoted''.
697 The value of the @code{setq} form is the value of the last @var{form}.
699 @example
700 @group
701 (setq x (1+ 2))
702      @result{} 3
703 @end group
704 x                   ; @r{@code{x} now has a global value.}
705      @result{} 3
706 @group
707 (let ((x 5))
708   (setq x 6)        ; @r{The local binding of @code{x} is set.}
709   x)
710      @result{} 6
711 @end group
712 x                   ; @r{The global value is unchanged.}
713      @result{} 3
714 @end example
716 Note that the first @var{form} is evaluated, then the first
717 @var{symbol} is set, then the second @var{form} is evaluated, then the
718 second @var{symbol} is set, and so on:
720 @example
721 @group
722 (setq x 10          ; @r{Notice that @code{x} is set before}
723       y (1+ x))     ;   @r{the value of @code{y} is computed.}
724      @result{} 11
725 @end group
726 @end example
727 @end defspec
729 @defun set symbol value
730 This function puts @var{value} in the value cell of @var{symbol}.
731 Since it is a function rather than a special form, the expression
732 written for @var{symbol} is evaluated to obtain the symbol to set.
733 The return value is @var{value}.
735 When dynamic variable binding is in effect (the default), @code{set}
736 has the same effect as @code{setq}, apart from the fact that
737 @code{set} evaluates its @var{symbol} argument whereas @code{setq}
738 does not.  But when a variable is lexically bound, @code{set} affects
739 its @emph{dynamic} value, whereas @code{setq} affects its current
740 (lexical) value.  @xref{Variable Scoping}.
742 @example
743 @group
744 (set one 1)
745 @error{} Symbol's value as variable is void: one
746 @end group
747 @group
748 (set 'one 1)
749      @result{} 1
750 @end group
751 @group
752 (set 'two 'one)
753      @result{} one
754 @end group
755 @group
756 (set two 2)         ; @r{@code{two} evaluates to symbol @code{one}.}
757      @result{} 2
758 @end group
759 @group
760 one                 ; @r{So it is @code{one} that was set.}
761      @result{} 2
762 (let ((one 1))      ; @r{This binding of @code{one} is set,}
763   (set 'one 3)      ;   @r{not the global value.}
764   one)
765      @result{} 3
766 @end group
767 @group
769      @result{} 2
770 @end group
771 @end example
773 If @var{symbol} is not actually a symbol, a @code{wrong-type-argument}
774 error is signaled.
776 @example
777 (set '(x y) 'z)
778 @error{} Wrong type argument: symbolp, (x y)
779 @end example
780 @end defun
782 @node Watching Variables
783 @section Running a function when a variable is changed.
784 @cindex variable watchpoints
785 @cindex watchpoints for Lisp variables
787 It is sometimes useful to take some action when a variable changes its
788 value.  The watchpoint facility provides the means to do so.  Some
789 possible uses for this feature include keeping display in sync with
790 variable settings, and invoking the debugger to track down unexpected
791 changes to variables (@pxref{Variable Debugging}).
793 The following functions may be used to manipulate and query the watch
794 functions for a variable.
796 @defun add-variable-watcher symbol watch-function
797 This function arranges for @var{watch-function} to be called whenever
798 @var{symbol} is modified.  Modifications through aliases
799 (@pxref{Variable Aliases}) will have the same effect.
801 @var{watch-function} will be called with 4 arguments: (@var{symbol}
802 @var{newval} @var{operation} @var{where}).
804 @var{symbol} is the variable being changed.
805 @var{newval} is the value it will be changed to.
806 @var{operation} is a symbol representing the kind of change, one of:
807 `set', `let', `unlet', `makunbound', and `defvaralias'.
808 @var{where} is a buffer if the buffer-local value of the variable is
809 being changed, nil otherwise.
810 @end defun
812 @defun remove-variable-watch symbol watch-function
813 This function removes @var{watch-function} from @var{symbol}'s list of
814 watchers.
815 @end defun
817 @defun get-variable-watchers symbol
818 This function returns the list of @var{symbol}'s active watcher
819 functions.
820 @end defun
822 @subsection Limitations
824 There are a couple of ways in which a variable could be modified (or at
825 least appear to be modified) without triggering a watchpoint.
827 Since watchpoints are attached to symbols, modification to the
828 objects contained within variables (e.g., by a list modification
829 function @pxref{Modifying Lists}) is not caught by this mechanism.
831 Additionally, C code can modify the value of variables directly,
832 bypassing the watchpoint mechanism.
834 A minor limitation of this feature, again because it targets symbols,
835 is that only variables of dynamic scope may be watched.  This poses
836 little difficulty, since modifications to lexical variables can be
837 discovered easily by inspecting the code within the scope of the
838 variable (unlike dynamic variables, which can be modified by any code
839 at all, @pxref{Variable Scoping}).
842 @node Variable Scoping
843 @section Scoping Rules for Variable Bindings
844 @cindex scoping rule
846   When you create a local binding for a variable, that binding takes
847 effect only within a limited portion of the program (@pxref{Local
848 Variables}).  This section describes exactly what this means.
850 @cindex scope
851 @cindex extent
852   Each local binding has a certain @dfn{scope} and @dfn{extent}.
853 @dfn{Scope} refers to @emph{where} in the textual source code the
854 binding can be accessed.  @dfn{Extent} refers to @emph{when}, as the
855 program is executing, the binding exists.
857 @cindex dynamic binding
858 @cindex dynamic scope
859 @cindex dynamic extent
860   By default, the local bindings that Emacs creates are @dfn{dynamic
861 bindings}.  Such a binding has @dfn{dynamic scope}, meaning that any
862 part of the program can potentially access the variable binding.  It
863 also has @dfn{dynamic extent}, meaning that the binding lasts only
864 while the binding construct (such as the body of a @code{let} form) is
865 being executed.
867 @cindex lexical binding
868 @cindex lexical scope
869 @cindex indefinite extent
870   Emacs can optionally create @dfn{lexical bindings}.  A lexical
871 binding has @dfn{lexical scope}, meaning that any reference to the
872 variable must be located textually within the binding
873 construct@footnote{With some exceptions; for instance, a lexical
874 binding can also be accessed from the Lisp debugger.}.  It also has
875 @dfn{indefinite extent}, meaning that under some circumstances the
876 binding can live on even after the binding construct has finished
877 executing, by means of special objects called @dfn{closures}.
879   The following subsections describe dynamic binding and lexical
880 binding in greater detail, and how to enable lexical binding in Emacs
881 Lisp programs.
883 @menu
884 * Dynamic Binding::         The default for binding local variables in Emacs.
885 * Dynamic Binding Tips::    Avoiding problems with dynamic binding.
886 * Lexical Binding::         A different type of local variable binding.
887 * Using Lexical Binding::   How to enable lexical binding.
888 @end menu
890 @node Dynamic Binding
891 @subsection Dynamic Binding
893   By default, the local variable bindings made by Emacs are dynamic
894 bindings.  When a variable is dynamically bound, its current binding
895 at any point in the execution of the Lisp program is simply the most
896 recently-created dynamic local binding for that symbol, or the global
897 binding if there is no such local binding.
899   Dynamic bindings have dynamic scope and extent, as shown by the
900 following example:
902 @example
903 @group
904 (defvar x -99)  ; @r{@code{x} receives an initial value of @minus{}99.}
906 (defun getx ()
907   x)            ; @r{@code{x} is used free in this function.}
909 (let ((x 1))    ; @r{@code{x} is dynamically bound.}
910   (getx))
911      @result{} 1
913 ;; @r{After the @code{let} form finishes, @code{x} reverts to its}
914 ;; @r{previous value, which is @minus{}99.}
916 (getx)
917      @result{} -99
918 @end group
919 @end example
921 @noindent
922 The function @code{getx} refers to @code{x}.  This is a @dfn{free}
923 reference, in the sense that there is no binding for @code{x} within
924 that @code{defun} construct itself.  When we call @code{getx} from
925 within a @code{let} form in which @code{x} is (dynamically) bound, it
926 retrieves the local value (i.e., 1).  But when we call @code{getx}
927 outside the @code{let} form, it retrieves the global value (i.e.,
928 @minus{}99).
930   Here is another example, which illustrates setting a dynamically
931 bound variable using @code{setq}:
933 @example
934 @group
935 (defvar x -99)      ; @r{@code{x} receives an initial value of @minus{}99.}
937 (defun addx ()
938   (setq x (1+ x)))  ; @r{Add 1 to @code{x} and return its new value.}
940 (let ((x 1))
941   (addx)
942   (addx))
943      @result{} 3           ; @r{The two @code{addx} calls add to @code{x} twice.}
945 ;; @r{After the @code{let} form finishes, @code{x} reverts to its}
946 ;; @r{previous value, which is @minus{}99.}
948 (addx)
949      @result{} -98
950 @end group
951 @end example
953   Dynamic binding is implemented in Emacs Lisp in a simple way.  Each
954 symbol has a value cell, which specifies its current dynamic value (or
955 absence of value).  @xref{Symbol Components}.  When a symbol is given
956 a dynamic local binding, Emacs records the contents of the value cell
957 (or absence thereof) in a stack, and stores the new local value in the
958 value cell.  When the binding construct finishes executing, Emacs pops
959 the old value off the stack, and puts it in the value cell.
961 @node Dynamic Binding Tips
962 @subsection Proper Use of Dynamic Binding
964   Dynamic binding is a powerful feature, as it allows programs to
965 refer to variables that are not defined within their local textual
966 scope.  However, if used without restraint, this can also make
967 programs hard to understand.  There are two clean ways to use this
968 technique:
970 @itemize @bullet
971 @item
972 If a variable has no global definition, use it as a local variable
973 only within a binding construct, such as the body of the @code{let}
974 form where the variable was bound.  If this convention is followed
975 consistently throughout a program, the value of the variable will not
976 affect, nor be affected by, any uses of the same variable symbol
977 elsewhere in the program.
979 @item
980 Otherwise, define the variable with @code{defvar}, @code{defconst}, or
981 @code{defcustom}.  @xref{Defining Variables}.  Usually, the definition
982 should be at top-level in an Emacs Lisp file.  As far as possible, it
983 should include a documentation string which explains the meaning and
984 purpose of the variable.  You should also choose the variable's name
985 to avoid name conflicts (@pxref{Coding Conventions}).
987 Then you can bind the variable anywhere in a program, knowing reliably
988 what the effect will be.  Wherever you encounter the variable, it will
989 be easy to refer back to the definition, e.g., via the @kbd{C-h v}
990 command (provided the variable definition has been loaded into Emacs).
991 @xref{Name Help,,, emacs, The GNU Emacs Manual}.
993 For example, it is common to use local bindings for customizable
994 variables like @code{case-fold-search}:
996 @example
997 @group
998 (defun search-for-abc ()
999   "Search for the string \"abc\", ignoring case differences."
1000   (let ((case-fold-search nil))
1001     (re-search-forward "abc")))
1002 @end group
1003 @end example
1004 @end itemize
1006 @node Lexical Binding
1007 @subsection Lexical Binding
1009   Lexical binding was introduced to Emacs, as an optional feature, in
1010 version 24.1.  We expect its importance to increase in the future.
1011 Lexical binding opens up many more opportunities for optimization, so
1012 programs using it are likely to run faster in future Emacs versions.
1013 Lexical binding is also more compatible with concurrency, which we
1014 want to add to Emacs in the future.
1016   A lexically-bound variable has @dfn{lexical scope}, meaning that any
1017 reference to the variable must be located textually within the binding
1018 construct.  Here is an example
1019 @iftex
1020 (see the next subsection, for how to actually enable lexical binding):
1021 @end iftex
1022 @ifnottex
1023 (@pxref{Using Lexical Binding}, for how to actually enable lexical binding):
1024 @end ifnottex
1026 @example
1027 @group
1028 (let ((x 1))    ; @r{@code{x} is lexically bound.}
1029   (+ x 3))
1030      @result{} 4
1032 (defun getx ()
1033   x)            ; @r{@code{x} is used free in this function.}
1035 (let ((x 1))    ; @r{@code{x} is lexically bound.}
1036   (getx))
1037 @error{} Symbol's value as variable is void: x
1038 @end group
1039 @end example
1041 @noindent
1042 Here, the variable @code{x} has no global value.  When it is lexically
1043 bound within a @code{let} form, it can be used in the textual confines
1044 of that @code{let} form.  But it can @emph{not} be used from within a
1045 @code{getx} function called from the @code{let} form, since the
1046 function definition of @code{getx} occurs outside the @code{let} form
1047 itself.
1049 @cindex lexical environment
1050   Here is how lexical binding works.  Each binding construct defines a
1051 @dfn{lexical environment}, specifying the variables that are bound
1052 within the construct and their local values.  When the Lisp evaluator
1053 wants the current value of a variable, it looks first in the lexical
1054 environment; if the variable is not specified in there, it looks in
1055 the symbol's value cell, where the dynamic value is stored.
1057   (Internally, the lexical environment is an alist of symbol-value
1058 pairs, with the final element in the alist being the symbol @code{t}
1059 rather than a cons cell.  Such an alist can be passed as the second
1060 argument to the @code{eval} function, in order to specify a lexical
1061 environment in which to evaluate a form.  @xref{Eval}.  Most Emacs
1062 Lisp programs, however, should not interact directly with lexical
1063 environments in this way; only specialized programs like debuggers.)
1065 @cindex closures, example of using
1066   Lexical bindings have indefinite extent.  Even after a binding
1067 construct has finished executing, its lexical environment can be
1068 ``kept around'' in Lisp objects called @dfn{closures}.  A closure is
1069 created when you define a named or anonymous function with lexical
1070 binding enabled.  @xref{Closures}, for details.
1072   When a closure is called as a function, any lexical variable
1073 references within its definition use the retained lexical environment.
1074 Here is an example:
1076 @example
1077 (defvar my-ticker nil)   ; @r{We will use this dynamically bound}
1078                          ; @r{variable to store a closure.}
1080 (let ((x 0))             ; @r{@code{x} is lexically bound.}
1081   (setq my-ticker (lambda ()
1082                     (setq x (1+ x)))))
1083     @result{} (closure ((x . 0) t) ()
1084           (setq x (1+ x)))
1086 (funcall my-ticker)
1087     @result{} 1
1089 (funcall my-ticker)
1090     @result{} 2
1092 (funcall my-ticker)
1093     @result{} 3
1095 x                        ; @r{Note that @code{x} has no global value.}
1096 @error{} Symbol's value as variable is void: x
1097 @end example
1099 @noindent
1100 The @code{let} binding defines a lexical environment in which the
1101 variable @code{x} is locally bound to 0.  Within this binding
1102 construct, we define a lambda expression which increments @code{x} by
1103 one and returns the incremented value.  This lambda expression is
1104 automatically turned into a closure, in which the lexical environment
1105 lives on even after the @code{let} binding construct has exited.  Each
1106 time we evaluate the closure, it increments @code{x}, using the
1107 binding of @code{x} in that lexical environment.
1109   Note that unlike dynamic variables which are tied to the symbol
1110 object itself, the relationship between lexical variables and symbols
1111 is only present in the interpreter (or compiler).  Therefore,
1112 functions which take a symbol argument (like @code{symbol-value},
1113 @code{boundp}, and @code{set}) can only retrieve or modify a
1114 variable's dynamic binding (i.e., the contents of its symbol's value
1115 cell).
1117 @node Using Lexical Binding
1118 @subsection Using Lexical Binding
1120   When loading an Emacs Lisp file or evaluating a Lisp buffer, lexical
1121 binding is enabled if the buffer-local variable @code{lexical-binding}
1122 is non-@code{nil}:
1124 @defvar lexical-binding
1125 If this buffer-local variable is non-@code{nil}, Emacs Lisp files and
1126 buffers are evaluated using lexical binding instead of dynamic
1127 binding.  (However, special variables are still dynamically bound; see
1128 below.)  If @code{nil}, dynamic binding is used for all local
1129 variables.  This variable is typically set for a whole Emacs Lisp
1130 file, as a file local variable (@pxref{File Local Variables}).
1131 Note that unlike other such variables, this one must be set in the
1132 first line of a file.
1133 @end defvar
1135 @noindent
1136 When evaluating Emacs Lisp code directly using an @code{eval} call,
1137 lexical binding is enabled if the @var{lexical} argument to
1138 @code{eval} is non-@code{nil}.  @xref{Eval}.
1140 @cindex special variables
1141   Even when lexical binding is enabled, certain variables will
1142 continue to be dynamically bound.  These are called @dfn{special
1143 variables}.  Every variable that has been defined with @code{defvar},
1144 @code{defcustom} or @code{defconst} is a special variable
1145 (@pxref{Defining Variables}).  All other variables are subject to
1146 lexical binding.
1148 @defun special-variable-p symbol
1149 This function returns non-@code{nil} if @var{symbol} is a special
1150 variable (i.e., it has a @code{defvar}, @code{defcustom}, or
1151 @code{defconst} variable definition).  Otherwise, the return value is
1152 @code{nil}.
1153 @end defun
1155   The use of a special variable as a formal argument in a function is
1156 discouraged.  Doing so gives rise to unspecified behavior when lexical
1157 binding mode is enabled (it may use lexical binding sometimes, and
1158 dynamic binding other times).
1160   Converting an Emacs Lisp program to lexical binding is easy.  First,
1161 add a file-local variable setting of @code{lexical-binding} to
1162 @code{t} in the header line of the Emacs Lisp source file (@pxref{File
1163 Local Variables}).  Second, check that every variable in the program
1164 which needs to be dynamically bound has a variable definition, so that
1165 it is not inadvertently bound lexically.
1167 @cindex free variable
1168 @cindex unused lexical variable
1169   A simple way to find out which variables need a variable definition
1170 is to byte-compile the source file.  @xref{Byte Compilation}.  If a
1171 non-special variable is used outside of a @code{let} form, the
1172 byte-compiler will warn about reference or assignment to a free
1173 variable.  If a non-special variable is bound but not used within a
1174 @code{let} form, the byte-compiler will warn about an unused lexical
1175 variable.  The byte-compiler will also issue a warning if you use a
1176 special variable as a function argument.
1178   (To silence byte-compiler warnings about unused variables, just use
1179 a variable name that start with an underscore.  The byte-compiler
1180 interprets this as an indication that this is a variable known not to
1181 be used.)
1183 @node Buffer-Local Variables
1184 @section Buffer-Local Variables
1185 @cindex variable, buffer-local
1186 @cindex buffer-local variables
1188   Global and local variable bindings are found in most programming
1189 languages in one form or another.  Emacs, however, also supports
1190 additional, unusual kinds of variable binding, such as
1191 @dfn{buffer-local} bindings, which apply only in one buffer.  Having
1192 different values for a variable in different buffers is an important
1193 customization method.  (Variables can also have bindings that are
1194 local to each terminal.  @xref{Multiple Terminals}.)
1196 @menu
1197 * Intro to Buffer-Local::       Introduction and concepts.
1198 * Creating Buffer-Local::       Creating and destroying buffer-local bindings.
1199 * Default Value::               The default value is seen in buffers
1200                                  that don't have their own buffer-local values.
1201 @end menu
1203 @node Intro to Buffer-Local
1204 @subsection Introduction to Buffer-Local Variables
1206   A buffer-local variable has a buffer-local binding associated with a
1207 particular buffer.  The binding is in effect when that buffer is
1208 current; otherwise, it is not in effect.  If you set the variable while
1209 a buffer-local binding is in effect, the new value goes in that binding,
1210 so its other bindings are unchanged.  This means that the change is
1211 visible only in the buffer where you made it.
1213   The variable's ordinary binding, which is not associated with any
1214 specific buffer, is called the @dfn{default binding}.  In most cases,
1215 this is the global binding.
1217   A variable can have buffer-local bindings in some buffers but not in
1218 other buffers.  The default binding is shared by all the buffers that
1219 don't have their own bindings for the variable.  (This includes all
1220 newly-created buffers.)  If you set the variable in a buffer that does
1221 not have a buffer-local binding for it, this sets the default binding,
1222 so the new value is visible in all the buffers that see the default
1223 binding.
1225   The most common use of buffer-local bindings is for major modes to change
1226 variables that control the behavior of commands.  For example, C mode and
1227 Lisp mode both set the variable @code{paragraph-start} to specify that only
1228 blank lines separate paragraphs.  They do this by making the variable
1229 buffer-local in the buffer that is being put into C mode or Lisp mode, and
1230 then setting it to the new value for that mode.  @xref{Major Modes}.
1232   The usual way to make a buffer-local binding is with
1233 @code{make-local-variable}, which is what major mode commands typically
1234 use.  This affects just the current buffer; all other buffers (including
1235 those yet to be created) will continue to share the default value unless
1236 they are explicitly given their own buffer-local bindings.
1238 @cindex automatically buffer-local
1239   A more powerful operation is to mark the variable as
1240 @dfn{automatically buffer-local} by calling
1241 @code{make-variable-buffer-local}.  You can think of this as making the
1242 variable local in all buffers, even those yet to be created.  More
1243 precisely, the effect is that setting the variable automatically makes
1244 the variable local to the current buffer if it is not already so.  All
1245 buffers start out by sharing the default value of the variable as usual,
1246 but setting the variable creates a buffer-local binding for the current
1247 buffer.  The new value is stored in the buffer-local binding, leaving
1248 the default binding untouched.  This means that the default value cannot
1249 be changed with @code{setq} in any buffer; the only way to change it is
1250 with @code{setq-default}.
1252   @strong{Warning:} When a variable has buffer-local
1253 bindings in one or more buffers, @code{let} rebinds the binding that's
1254 currently in effect.  For instance, if the current buffer has a
1255 buffer-local value, @code{let} temporarily rebinds that.  If no
1256 buffer-local bindings are in effect, @code{let} rebinds
1257 the default value.  If inside the @code{let} you then change to a
1258 different current buffer in which a different binding is in effect,
1259 you won't see the @code{let} binding any more.  And if you exit the
1260 @code{let} while still in the other buffer, you won't see the
1261 unbinding occur (though it will occur properly).  Here is an example
1262 to illustrate:
1264 @example
1265 @group
1266 (setq foo 'g)
1267 (set-buffer "a")
1268 (make-local-variable 'foo)
1269 @end group
1270 (setq foo 'a)
1271 (let ((foo 'temp))
1272   ;; foo @result{} 'temp  ; @r{let binding in buffer @samp{a}}
1273   (set-buffer "b")
1274   ;; foo @result{} 'g     ; @r{the global value since foo is not local in @samp{b}}
1275   @var{body}@dots{})
1276 @group
1277 foo @result{} 'g        ; @r{exiting restored the local value in buffer @samp{a},}
1278                  ; @r{but we don't see that in buffer @samp{b}}
1279 @end group
1280 @group
1281 (set-buffer "a") ; @r{verify the local value was restored}
1282 foo @result{} 'a
1283 @end group
1284 @end example
1286 @noindent
1287 Note that references to @code{foo} in @var{body} access the
1288 buffer-local binding of buffer @samp{b}.
1290   When a file specifies local variable values, these become buffer-local
1291 values when you visit the file.  @xref{File Variables,,, emacs, The
1292 GNU Emacs Manual}.
1294   A buffer-local variable cannot be made terminal-local
1295 (@pxref{Multiple Terminals}).
1297 @node Creating Buffer-Local
1298 @subsection Creating and Deleting Buffer-Local Bindings
1300 @deffn Command make-local-variable variable
1301 This function creates a buffer-local binding in the current buffer for
1302 @var{variable} (a symbol).  Other buffers are not affected.  The value
1303 returned is @var{variable}.
1305 The buffer-local value of @var{variable} starts out as the same value
1306 @var{variable} previously had.  If @var{variable} was void, it remains
1307 void.
1309 @example
1310 @group
1311 ;; @r{In buffer @samp{b1}:}
1312 (setq foo 5)                ; @r{Affects all buffers.}
1313      @result{} 5
1314 @end group
1315 @group
1316 (make-local-variable 'foo)  ; @r{Now it is local in @samp{b1}.}
1317      @result{} foo
1318 @end group
1319 @group
1320 foo                         ; @r{That did not change}
1321      @result{} 5                   ;   @r{the value.}
1322 @end group
1323 @group
1324 (setq foo 6)                ; @r{Change the value}
1325      @result{} 6                   ;   @r{in @samp{b1}.}
1326 @end group
1327 @group
1329      @result{} 6
1330 @end group
1332 @group
1333 ;; @r{In buffer @samp{b2}, the value hasn't changed.}
1334 (with-current-buffer "b2"
1335   foo)
1336      @result{} 5
1337 @end group
1338 @end example
1340 Making a variable buffer-local within a @code{let}-binding for that
1341 variable does not work reliably, unless the buffer in which you do this
1342 is not current either on entry to or exit from the @code{let}.  This is
1343 because @code{let} does not distinguish between different kinds of
1344 bindings; it knows only which variable the binding was made for.
1346 If the variable is terminal-local (@pxref{Multiple Terminals}), this
1347 function signals an error.  Such variables cannot have buffer-local
1348 bindings as well.
1350 @strong{Warning:} do not use @code{make-local-variable} for a hook
1351 variable.  The hook variables are automatically made buffer-local as
1352 needed if you use the @var{local} argument to @code{add-hook} or
1353 @code{remove-hook}.
1354 @end deffn
1356 @defmac setq-local variable value
1357 This macro creates a buffer-local binding in the current buffer for
1358 @var{variable}, and gives it the buffer-local value @var{value}.  It
1359 is equivalent to calling @code{make-local-variable} followed by
1360 @code{setq}.  @var{variable} should be an unquoted symbol.
1361 @end defmac
1363 @deffn Command make-variable-buffer-local variable
1364 This function marks @var{variable} (a symbol) automatically
1365 buffer-local, so that any subsequent attempt to set it will make it
1366 local to the current buffer at the time.  Unlike
1367 @code{make-local-variable}, with which it is often confused, this
1368 cannot be undone, and affects the behavior of the variable in all
1369 buffers.
1371 A peculiar wrinkle of this feature is that binding the variable (with
1372 @code{let} or other binding constructs) does not create a buffer-local
1373 binding for it.  Only setting the variable (with @code{set} or
1374 @code{setq}), while the variable does not have a @code{let}-style
1375 binding that was made in the current buffer, does so.
1377 If @var{variable} does not have a default value, then calling this
1378 command will give it a default value of @code{nil}.  If @var{variable}
1379 already has a default value, that value remains unchanged.
1380 Subsequently calling @code{makunbound} on @var{variable} will result
1381 in a void buffer-local value and leave the default value unaffected.
1383 The value returned is @var{variable}.
1385 @strong{Warning:} Don't assume that you should use
1386 @code{make-variable-buffer-local} for user-option variables, simply
1387 because users @emph{might} want to customize them differently in
1388 different buffers.  Users can make any variable local, when they wish
1389 to.  It is better to leave the choice to them.
1391 The time to use @code{make-variable-buffer-local} is when it is crucial
1392 that no two buffers ever share the same binding.  For example, when a
1393 variable is used for internal purposes in a Lisp program which depends
1394 on having separate values in separate buffers, then using
1395 @code{make-variable-buffer-local} can be the best solution.
1396 @end deffn
1398 @defmac defvar-local variable value &optional docstring
1399 This macro defines @var{variable} as a variable with initial value
1400 @var{value} and @var{docstring}, and marks it as automatically
1401 buffer-local.  It is equivalent to calling @code{defvar} followed by
1402 @code{make-variable-buffer-local}.  @var{variable} should be an
1403 unquoted symbol.
1404 @end defmac
1406 @defun local-variable-p variable &optional buffer
1407 This returns @code{t} if @var{variable} is buffer-local in buffer
1408 @var{buffer} (which defaults to the current buffer); otherwise,
1409 @code{nil}.
1410 @end defun
1412 @defun local-variable-if-set-p variable &optional buffer
1413 This returns @code{t} if @var{variable} either has a buffer-local
1414 value in buffer @var{buffer}, or is automatically buffer-local.
1415 Otherwise, it returns @code{nil}.  If omitted or @code{nil},
1416 @var{buffer} defaults to the current buffer.
1417 @end defun
1419 @defun buffer-local-value variable buffer
1420 This function returns the buffer-local binding of @var{variable} (a
1421 symbol) in buffer @var{buffer}.  If @var{variable} does not have a
1422 buffer-local binding in buffer @var{buffer}, it returns the default
1423 value (@pxref{Default Value}) of @var{variable} instead.
1424 @end defun
1426 @defun buffer-local-variables &optional buffer
1427 This function returns a list describing the buffer-local variables in
1428 buffer @var{buffer}.  (If @var{buffer} is omitted, the current buffer
1429 is used.)  Normally, each list element has the form
1430 @w{@code{(@var{sym} . @var{val})}}, where @var{sym} is a buffer-local
1431 variable (a symbol) and @var{val} is its buffer-local value.  But when
1432 a variable's buffer-local binding in @var{buffer} is void, its list
1433 element is just @var{sym}.
1435 @example
1436 @group
1437 (make-local-variable 'foobar)
1438 (makunbound 'foobar)
1439 (make-local-variable 'bind-me)
1440 (setq bind-me 69)
1441 @end group
1442 (setq lcl (buffer-local-variables))
1443     ;; @r{First, built-in variables local in all buffers:}
1444 @result{} ((mark-active . nil)
1445     (buffer-undo-list . nil)
1446     (mode-name . "Fundamental")
1447     @dots{}
1448 @group
1449     ;; @r{Next, non-built-in buffer-local variables.}
1450     ;; @r{This one is buffer-local and void:}
1451     foobar
1452     ;; @r{This one is buffer-local and nonvoid:}
1453     (bind-me . 69))
1454 @end group
1455 @end example
1457 Note that storing new values into the @sc{cdr}s of cons cells in this
1458 list does @emph{not} change the buffer-local values of the variables.
1459 @end defun
1461 @deffn Command kill-local-variable variable
1462 This function deletes the buffer-local binding (if any) for
1463 @var{variable} (a symbol) in the current buffer.  As a result, the
1464 default binding of @var{variable} becomes visible in this buffer.  This
1465 typically results in a change in the value of @var{variable}, since the
1466 default value is usually different from the buffer-local value just
1467 eliminated.
1469 If you kill the buffer-local binding of a variable that automatically
1470 becomes buffer-local when set, this makes the default value visible in
1471 the current buffer.  However, if you set the variable again, that will
1472 once again create a buffer-local binding for it.
1474 @code{kill-local-variable} returns @var{variable}.
1476 This function is a command because it is sometimes useful to kill one
1477 buffer-local variable interactively, just as it is useful to create
1478 buffer-local variables interactively.
1479 @end deffn
1481 @cindex local variables, killed by major mode
1482 @defun kill-all-local-variables
1483 This function eliminates all the buffer-local variable bindings of the
1484 current buffer except for variables marked as permanent and local
1485 hook functions that have a non-@code{nil} @code{permanent-local-hook}
1486 property (@pxref{Setting Hooks}).  As a result, the buffer will see
1487 the default values of most variables.
1489 This function also resets certain other information pertaining to the
1490 buffer: it sets the local keymap to @code{nil}, the syntax table to the
1491 value of @code{(standard-syntax-table)}, the case table to
1492 @code{(standard-case-table)}, and the abbrev table to the value of
1493 @code{fundamental-mode-abbrev-table}.
1495 The very first thing this function does is run the normal hook
1496 @code{change-major-mode-hook} (see below).
1498 Every major mode command begins by calling this function, which has the
1499 effect of switching to Fundamental mode and erasing most of the effects
1500 of the previous major mode.  To ensure that this does its job, the
1501 variables that major modes set should not be marked permanent.
1503 @code{kill-all-local-variables} returns @code{nil}.
1504 @end defun
1506 @defvar change-major-mode-hook
1507 The function @code{kill-all-local-variables} runs this normal hook
1508 before it does anything else.  This gives major modes a way to arrange
1509 for something special to be done if the user switches to a different
1510 major mode.  It is also useful for buffer-specific minor modes
1511 that should be forgotten if the user changes the major mode.
1513 For best results, make this variable buffer-local, so that it will
1514 disappear after doing its job and will not interfere with the
1515 subsequent major mode.  @xref{Hooks}.
1516 @end defvar
1518 @cindex permanent local variable
1519 A buffer-local variable is @dfn{permanent} if the variable name (a
1520 symbol) has a @code{permanent-local} property that is non-@code{nil}.
1521 Such variables are unaffected by @code{kill-all-local-variables}, and
1522 their local bindings are therefore not cleared by changing major modes.
1523 Permanent locals are appropriate for data pertaining to where the file
1524 came from or how to save it, rather than with how to edit the contents.
1526 @node Default Value
1527 @subsection The Default Value of a Buffer-Local Variable
1528 @cindex default value
1530   The global value of a variable with buffer-local bindings is also
1531 called the @dfn{default} value, because it is the value that is in
1532 effect whenever neither the current buffer nor the selected frame has
1533 its own binding for the variable.
1535   The functions @code{default-value} and @code{setq-default} access and
1536 change a variable's default value regardless of whether the current
1537 buffer has a buffer-local binding.  For example, you could use
1538 @code{setq-default} to change the default setting of
1539 @code{paragraph-start} for most buffers; and this would work even when
1540 you are in a C or Lisp mode buffer that has a buffer-local value for
1541 this variable.
1543 @c Emacs 19 feature
1544   The special forms @code{defvar} and @code{defconst} also set the
1545 default value (if they set the variable at all), rather than any
1546 buffer-local value.
1548 @defun default-value symbol
1549 This function returns @var{symbol}'s default value.  This is the value
1550 that is seen in buffers and frames that do not have their own values for
1551 this variable.  If @var{symbol} is not buffer-local, this is equivalent
1552 to @code{symbol-value} (@pxref{Accessing Variables}).
1553 @end defun
1555 @c Emacs 19 feature
1556 @defun default-boundp symbol
1557 The function @code{default-boundp} tells you whether @var{symbol}'s
1558 default value is nonvoid.  If @code{(default-boundp 'foo)} returns
1559 @code{nil}, then @code{(default-value 'foo)} would get an error.
1561 @code{default-boundp} is to @code{default-value} as @code{boundp} is to
1562 @code{symbol-value}.
1563 @end defun
1565 @defspec setq-default [symbol form]@dots{}
1566 This special form gives each @var{symbol} a new default value, which is
1567 the result of evaluating the corresponding @var{form}.  It does not
1568 evaluate @var{symbol}, but does evaluate @var{form}.  The value of the
1569 @code{setq-default} form is the value of the last @var{form}.
1571 If a @var{symbol} is not buffer-local for the current buffer, and is not
1572 marked automatically buffer-local, @code{setq-default} has the same
1573 effect as @code{setq}.  If @var{symbol} is buffer-local for the current
1574 buffer, then this changes the value that other buffers will see (as long
1575 as they don't have a buffer-local value), but not the value that the
1576 current buffer sees.
1578 @example
1579 @group
1580 ;; @r{In buffer @samp{foo}:}
1581 (make-local-variable 'buffer-local)
1582      @result{} buffer-local
1583 @end group
1584 @group
1585 (setq buffer-local 'value-in-foo)
1586      @result{} value-in-foo
1587 @end group
1588 @group
1589 (setq-default buffer-local 'new-default)
1590      @result{} new-default
1591 @end group
1592 @group
1593 buffer-local
1594      @result{} value-in-foo
1595 @end group
1596 @group
1597 (default-value 'buffer-local)
1598      @result{} new-default
1599 @end group
1601 @group
1602 ;; @r{In (the new) buffer @samp{bar}:}
1603 buffer-local
1604      @result{} new-default
1605 @end group
1606 @group
1607 (default-value 'buffer-local)
1608      @result{} new-default
1609 @end group
1610 @group
1611 (setq buffer-local 'another-default)
1612      @result{} another-default
1613 @end group
1614 @group
1615 (default-value 'buffer-local)
1616      @result{} another-default
1617 @end group
1619 @group
1620 ;; @r{Back in buffer @samp{foo}:}
1621 buffer-local
1622      @result{} value-in-foo
1623 (default-value 'buffer-local)
1624      @result{} another-default
1625 @end group
1626 @end example
1627 @end defspec
1629 @defun set-default symbol value
1630 This function is like @code{setq-default}, except that @var{symbol} is
1631 an ordinary evaluated argument.
1633 @example
1634 @group
1635 (set-default (car '(a b c)) 23)
1636      @result{} 23
1637 @end group
1638 @group
1639 (default-value 'a)
1640      @result{} 23
1641 @end group
1642 @end example
1643 @end defun
1645   A variable can be let-bound (@pxref{Local Variables}) to a value.
1646 This makes its global value shadowed by the binding;
1647 @code{default-value} will then return the value from that binding, not
1648 the global value, and @code{set-default} will be prevented from
1649 setting the global value (it will change the let-bound value instead).
1650 The following two functions allow to reference the global value even
1651 if it's shadowed by a let-binding.
1653 @cindex top-level default value
1654 @defun default-toplevel-value symbol
1655 This function returns the @dfn{top-level} default value of
1656 @var{symbol}, which is its value outside of any let-binding.
1657 @end defun
1659 @example
1660 @group
1661 (defvar variable 'global-value)
1662     @result{} variable
1663 @end group
1664 @group
1665 (let ((variable 'let-binding))
1666   (default-value 'variable))
1667     @result{} let-binding
1668 @end group
1669 @group
1670 (let ((variable 'let-binding))
1671   (default-toplevel-value 'variable))
1672     @result{} global-value
1673 @end group
1674 @end example
1676 @defun set-default-toplevel-value symbol value
1677 This function sets the top-level default value of @var{symbol} to the
1678 specified @var{value}.  This comes in handy when you want to set the
1679 global value of @var{symbol} regardless of whether your code runs in
1680 the context of @var{symbol}'s let-binding.
1681 @end defun
1684 @node File Local Variables
1685 @section File Local Variables
1686 @cindex file local variables
1688   A file can specify local variable values; Emacs uses these to create
1689 buffer-local bindings for those variables in the buffer visiting that
1690 file.  @xref{File Variables, , Local Variables in Files, emacs, The
1691 GNU Emacs Manual}, for basic information about file-local variables.
1692 This section describes the functions and variables that affect how
1693 file-local variables are processed.
1695   If a file-local variable could specify an arbitrary function or Lisp
1696 expression that would be called later, visiting a file could take over
1697 your Emacs.  Emacs protects against this by automatically setting only
1698 those file-local variables whose specified values are known to be
1699 safe.  Other file-local variables are set only if the user agrees.
1701   For additional safety, @code{read-circle} is temporarily bound to
1702 @code{nil} when Emacs reads file-local variables (@pxref{Input
1703 Functions}).  This prevents the Lisp reader from recognizing circular
1704 and shared Lisp structures (@pxref{Circular Objects}).
1706 @defopt enable-local-variables
1707 This variable controls whether to process file-local variables.
1708 The possible values are:
1710 @table @asis
1711 @item @code{t} (the default)
1712 Set the safe variables, and query (once) about any unsafe variables.
1713 @item @code{:safe}
1714 Set only the safe variables and do not query.
1715 @item @code{:all}
1716 Set all the variables and do not query.
1717 @item @code{nil}
1718 Don't set any variables.
1719 @item anything else
1720 Query (once) about all the variables.
1721 @end table
1722 @end defopt
1724 @defvar inhibit-local-variables-regexps
1725 This is a list of regular expressions.  If a file has a name
1726 matching an element of this list, then it is not scanned for
1727 any form of file-local variable.  For examples of why you might want
1728 to use this, @pxref{Auto Major Mode}.
1729 @end defvar
1731 @defun hack-local-variables &optional handle-mode
1732 This function parses, and binds or evaluates as appropriate, any local
1733 variables specified by the contents of the current buffer.  The variable
1734 @code{enable-local-variables} has its effect here.  However, this
1735 function does not look for the @samp{mode:} local variable in the
1736 @w{@samp{-*-}} line.  @code{set-auto-mode} does that, also taking
1737 @code{enable-local-variables} into account (@pxref{Auto Major Mode}).
1739 This function works by walking the alist stored in
1740 @code{file-local-variables-alist} and applying each local variable in
1741 turn.  It calls @code{before-hack-local-variables-hook} and
1742 @code{hack-local-variables-hook} before and after applying the
1743 variables, respectively.  It only calls the before-hook if the alist
1744 is non-@code{nil}; it always calls the other hook.  This
1745 function ignores a @samp{mode} element if it specifies the same major
1746 mode as the buffer already has.
1748 If the optional argument @var{handle-mode} is @code{t}, then all this
1749 function does is return a symbol specifying the major mode, if the
1750 @w{@samp{-*-}} line or the local variables list specifies one, and
1751 @code{nil} otherwise.  It does not set the mode or any other
1752 file-local variable.  If @var{handle-mode} has any value other than
1753 @code{nil} or @code{t}, any settings of @samp{mode} in the
1754 @w{@samp{-*-}} line or the local variables list are ignored, and the
1755 other settings are applied.  If @var{handle-mode} is @code{nil}, all
1756 the file local variables are set.
1757 @end defun
1759 @defvar file-local-variables-alist
1760 This buffer-local variable holds the alist of file-local variable
1761 settings.  Each element of the alist is of the form
1762 @w{@code{(@var{var} . @var{value})}}, where @var{var} is a symbol of
1763 the local variable and @var{value} is its value.  When Emacs visits a
1764 file, it first collects all the file-local variables into this alist,
1765 and then the @code{hack-local-variables} function applies them one by
1766 one.
1767 @end defvar
1769 @defvar before-hack-local-variables-hook
1770 Emacs calls this hook immediately before applying file-local variables
1771 stored in @code{file-local-variables-alist}.
1772 @end defvar
1774 @defvar hack-local-variables-hook
1775 Emacs calls this hook immediately after it finishes applying
1776 file-local variables stored in @code{file-local-variables-alist}.
1777 @end defvar
1779 @cindex safe local variable
1780   You can specify safe values for a variable with a
1781 @code{safe-local-variable} property.  The property has to be a
1782 function of one argument; any value is safe if the function returns
1783 non-@code{nil} given that value.  Many commonly-encountered file
1784 variables have @code{safe-local-variable} properties; these include
1785 @code{fill-column}, @code{fill-prefix}, and @code{indent-tabs-mode}.
1786 For boolean-valued variables that are safe, use @code{booleanp} as the
1787 property value.
1789   When defining a user option using @code{defcustom}, you can set its
1790 @code{safe-local-variable} property by adding the arguments
1791 @code{:safe @var{function}} to @code{defcustom} (@pxref{Variable
1792 Definitions}).
1794 @defopt safe-local-variable-values
1795 This variable provides another way to mark some variable values as
1796 safe.  It is a list of cons cells @code{(@var{var} . @var{val})},
1797 where @var{var} is a variable name and @var{val} is a value which is
1798 safe for that variable.
1800 When Emacs asks the user whether or not to obey a set of file-local
1801 variable specifications, the user can choose to mark them as safe.
1802 Doing so adds those variable/value pairs to
1803 @code{safe-local-variable-values}, and saves it to the user's custom
1804 file.
1805 @end defopt
1807 @defun safe-local-variable-p sym val
1808 This function returns non-@code{nil} if it is safe to give @var{sym}
1809 the value @var{val}, based on the above criteria.
1810 @end defun
1812 @c @cindex risky local variable   Duplicates risky-local-variable
1813   Some variables are considered @dfn{risky}.  If a variable is risky,
1814 it is never entered automatically into
1815 @code{safe-local-variable-values}; Emacs always queries before setting
1816 a risky variable, unless the user explicitly allows a value by
1817 customizing @code{safe-local-variable-values} directly.
1819   Any variable whose name has a non-@code{nil}
1820 @code{risky-local-variable} property is considered risky.  When you
1821 define a user option using @code{defcustom}, you can set its
1822 @code{risky-local-variable} property by adding the arguments
1823 @code{:risky @var{value}} to @code{defcustom} (@pxref{Variable
1824 Definitions}).  In addition, any variable whose name ends in any of
1825 @samp{-command}, @samp{-frame-alist}, @samp{-function},
1826 @samp{-functions}, @samp{-hook}, @samp{-hooks}, @samp{-form},
1827 @samp{-forms}, @samp{-map}, @samp{-map-alist}, @samp{-mode-alist},
1828 @samp{-program}, or @samp{-predicate} is automatically considered
1829 risky.  The variables @samp{font-lock-keywords},
1830 @samp{font-lock-keywords} followed by a digit, and
1831 @samp{font-lock-syntactic-keywords} are also considered risky.
1833 @defun risky-local-variable-p sym
1834 This function returns non-@code{nil} if @var{sym} is a risky variable,
1835 based on the above criteria.
1836 @end defun
1838 @defvar ignored-local-variables
1839 This variable holds a list of variables that should not be given local
1840 values by files.  Any value specified for one of these variables is
1841 completely ignored.
1842 @end defvar
1844   The @samp{Eval:} ``variable'' is also a potential loophole, so Emacs
1845 normally asks for confirmation before handling it.
1847 @defopt enable-local-eval
1848 This variable controls processing of @samp{Eval:} in @samp{-*-} lines
1849 or local variables
1850 lists in files being visited.  A value of @code{t} means process them
1851 unconditionally; @code{nil} means ignore them; anything else means ask
1852 the user what to do for each file.  The default value is @code{maybe}.
1853 @end defopt
1855 @defopt safe-local-eval-forms
1856 This variable holds a list of expressions that are safe to
1857 evaluate when found in the @samp{Eval:} ``variable'' in a file
1858 local variables list.
1859 @end defopt
1861   If the expression is a function call and the function has a
1862 @code{safe-local-eval-function} property, the property value
1863 determines whether the expression is safe to evaluate.  The property
1864 value can be a predicate to call to test the expression, a list of
1865 such predicates (it's safe if any predicate succeeds), or @code{t}
1866 (always safe provided the arguments are constant).
1868   Text properties are also potential loopholes, since their values
1869 could include functions to call.  So Emacs discards all text
1870 properties from string values specified for file-local variables.
1872 @node Directory Local Variables
1873 @section Directory Local Variables
1874 @cindex directory local variables
1876   A directory can specify local variable values common to all files in
1877 that directory; Emacs uses these to create buffer-local bindings for
1878 those variables in buffers visiting any file in that directory.  This
1879 is useful when the files in the directory belong to some @dfn{project}
1880 and therefore share the same local variables.
1882   There are two different methods for specifying directory local
1883 variables: by putting them in a special file, or by defining a
1884 @dfn{project class} for that directory.
1886 @defvr Constant dir-locals-file
1887 This constant is the name of the file where Emacs expects to find the
1888 directory-local variables.  The name of the file is
1889 @file{.dir-locals.el}@footnote{
1890 The MS-DOS version of Emacs uses @file{_dir-locals.el} instead, due to
1891 limitations of the DOS filesystems.
1892 }.  A file by that name in a directory causes Emacs to apply its
1893 settings to any file in that directory or any of its subdirectories
1894 (optionally, you can exclude subdirectories; see below).
1895 If some of the subdirectories have their own @file{.dir-locals.el}
1896 files, Emacs uses the settings from the deepest file it finds starting
1897 from the file's directory and moving up the directory tree.  The file
1898 specifies local variables as a specially formatted list; see
1899 @ref{Directory Variables, , Per-directory Local Variables, emacs, The
1900 GNU Emacs Manual}, for more details.
1901 @end defvr
1903 @defun hack-dir-local-variables
1904 This function reads the @code{.dir-locals.el} file and stores the
1905 directory-local variables in @code{file-local-variables-alist} that is
1906 local to the buffer visiting any file in the directory, without
1907 applying them.  It also stores the directory-local settings in
1908 @code{dir-locals-class-alist}, where it defines a special class for
1909 the directory in which @file{.dir-locals.el} file was found.  This
1910 function works by calling @code{dir-locals-set-class-variables} and
1911 @code{dir-locals-set-directory-class}, described below.
1912 @end defun
1914 @defun hack-dir-local-variables-non-file-buffer
1915 This function looks for directory-local variables, and immediately
1916 applies them in the current buffer.  It is intended to be called in
1917 the mode commands for non-file buffers, such as Dired buffers, to let
1918 them obey directory-local variable settings.  For non-file buffers,
1919 Emacs looks for directory-local variables in @code{default-directory}
1920 and its parent directories.
1921 @end defun
1923 @defun dir-locals-set-class-variables class variables
1924 This function defines a set of variable settings for the named
1925 @var{class}, which is a symbol.  You can later assign the class to one
1926 or more directories, and Emacs will apply those variable settings to
1927 all files in those directories.  The list in @var{variables} can be of
1928 one of the two forms: @code{(@var{major-mode} . @var{alist})} or
1929 @code{(@var{directory} . @var{list})}.  With the first form, if the
1930 file's buffer turns on a mode that is derived from @var{major-mode},
1931 then the all the variables in the associated @var{alist} are applied;
1932 @var{alist} should be of the form @code{(@var{name} . @var{value})}.
1933 A special value @code{nil} for @var{major-mode} means the settings are
1934 applicable to any mode.  In @var{alist}, you can use a special
1935 @var{name}: @code{subdirs}.  If the associated value is
1936 @code{nil}, the alist is only applied to files in the relevant
1937 directory, not to those in any subdirectories.
1939 With the second form of @var{variables}, if @var{directory} is the
1940 initial substring of the file's directory, then @var{list} is applied
1941 recursively by following the above rules; @var{list} should be of one
1942 of the two forms accepted by this function in @var{variables}.
1943 @end defun
1945 @defun dir-locals-set-directory-class directory class &optional mtime
1946 This function assigns @var{class} to all the files in @code{directory}
1947 and its subdirectories.  Thereafter, all the variable settings
1948 specified for @var{class} will be applied to any visited file in
1949 @var{directory} and its children.  @var{class} must have been already
1950 defined by @code{dir-locals-set-class-variables}.
1952 Emacs uses this function internally when it loads directory variables
1953 from a @code{.dir-locals.el} file.  In that case, the optional
1954 argument @var{mtime} holds the file modification time (as returned by
1955 @code{file-attributes}).  Emacs uses this time to check stored
1956 local variables are still valid.  If you are assigning a class
1957 directly, not via a file, this argument should be @code{nil}.
1958 @end defun
1960 @defvar dir-locals-class-alist
1961 This alist holds the class symbols and the associated variable
1962 settings.  It is updated by @code{dir-locals-set-class-variables}.
1963 @end defvar
1965 @defvar dir-locals-directory-cache
1966 This alist holds directory names, their assigned class names, and
1967 modification times of the associated directory local variables file
1968 (if there is one).  The function @code{dir-locals-set-directory-class}
1969 updates this list.
1970 @end defvar
1972 @defvar enable-dir-local-variables
1973 If @code{nil}, directory-local variables are ignored.  This variable
1974 may be useful for modes that want to ignore directory-locals while
1975 still respecting file-local variables (@pxref{File Local Variables}).
1976 @end defvar
1978 @node Connection Local Variables
1979 @section Connection Local Variables
1980 @cindex connection local variables
1982   Connection-local variables provide a general mechanism for different
1983 variable settings in buffers with a remote connection.  They are bound
1984 and set depending on the remote connection a buffer is dedicated to.
1986 @defun connection-local-set-profile-variables profile variables
1987 This function defines a set of variable settings for the connection
1988 @var{profile}, which is a symbol.  You can later assign the connection
1989 profile to one or more remote connections, and Emacs will apply those
1990 variable settings to all process buffers for those connections.  The
1991 list in @var{variables} is an alist of the form
1992 @code{(@var{name}@tie{}.@tie{}@var{value})}.  Example:
1994 @example
1995 @group
1996 (connection-local-set-profile-variables
1997   'remote-bash
1998   '((shell-file-name . "/bin/bash")
1999     (shell-command-switch . "-c")
2000     (shell-interactive-switch . "-i")
2001     (shell-login-switch . "-l")))
2002 @end group
2004 @group
2005 (connection-local-set-profile-variables
2006   'remote-ksh
2007   '((shell-file-name . "/bin/ksh")
2008     (shell-command-switch . "-c")
2009     (shell-interactive-switch . "-i")
2010     (shell-login-switch . "-l")))
2011 @end group
2013 @group
2014 (connection-local-set-profile-variables
2015   'remote-null-device
2016   '((null-device . "/dev/null")))
2017 @end group
2018 @end example
2019 @end defun
2021 @defvar connection-local-profile-alist
2022 This alist holds the connection profile symbols and the associated
2023 variable settings.  It is updated by
2024 @code{connection-local-set-profile-variables}.
2025 @end defvar
2027 @defun connection-local-set-profiles criteria &rest profiles
2028 This function assigns @var{profiles}, which are symbols, to all remote
2029 connections identified by @var{criteria}.  @var{criteria} is a plist
2030 identifying a connection and the application using this connection.
2031 Property names might be @code{:application}, @code{:protocol},
2032 @code{:user} and @code{:machine}.  The property value of
2033 @code{:application} is a symbol, all other property values are
2034 strings.  All properties are optional; if @var{criteria} is nil, it
2035 always applies.  Example:
2037 @example
2038 @group
2039 (connection-local-set-profiles
2040   '(:application 'tramp :protocol "ssh" :machine "localhost")
2041   'remote-bash 'remote-null-device)
2042 @end group
2044 @group
2045 (connection-local-set-profiles
2046   '(:application 'tramp :protocol "sudo"
2047     :user "root" :machine "localhost")
2048   'remote-ksh 'remote-null-device)
2049 @end group
2050 @end example
2052   If @var{criteria} is nil, it applies for all remote connections.
2053 Therefore, the example above would be equivalent to
2055 @example
2056 @group
2057 (connection-local-set-profiles
2058   '(:application 'tramp :protocol "ssh" :machine "localhost")
2059   'remote-bash)
2060 @end group
2062 @group
2063 (connection-local-set-profiles
2064   '(:application 'tramp :protocol "sudo"
2065     :user "root" :machine "localhost")
2066   'remote-ksh)
2067 @end group
2069 @group
2070 (connection-local-set-profiles
2071   nil 'remote-null-device)
2072 @end group
2073 @end example
2075   Any connection profile of @var{profiles} must have been already
2076 defined by @code{connection-local-set-profile-variables}.
2077 @end defun
2079 @defvar connection-local-criteria-alist
2080 This alist contains connection criteria and their assigned profile
2081 names.  The function @code{connection-local-set-profiles} updates this
2082 list.
2083 @end defvar
2085 @defun hack-connection-local-variables criteria
2086 This function collects applicable connection-local variables
2087 associated with @var{criteria} in
2088 @code{connection-local-variables-alist}, without applying them.
2089 Example:
2091 @example
2092 @group
2093 (hack-connection-local-variables
2094   '(:application 'tramp :protocol "ssh" :machine "localhost"))
2095 @end group
2097 @group
2098 connection-local-variables-alist
2099      @result{} ((null-device . "/dev/null")
2100         (shell-login-switch . "-l")
2101         (shell-interactive-switch . "-i")
2102         (shell-command-switch . "-c")
2103         (shell-file-name . "/bin/bash"))
2104 @end group
2105 @end example
2106 @end defun
2108 @defun hack-connection-local-variables-apply criteria
2109 This function looks for connection-local variables according to
2110 @var{criteria}, and immediately applies them in the current buffer.
2111 @end defun
2113 @defmac with-connection-local-profiles profiles &rest body
2114 All connection-local variables, which are specified by a connection
2115 profile in @var{profiles}, are applied.
2117 After that, @var{body} is executed, and the connection-local variables
2118 are unwound.  Example:
2120 @example
2121 @group
2122 (connection-local-set-profile-variables
2123   'remote-perl
2124   '((perl-command-name . "/usr/local/bin/perl")
2125     (perl-command-switch . "-e %s")))
2126 @end group
2128 @group
2129 (with-connection-local-profiles '(remote-perl)
2130   do something useful)
2131 @end group
2132 @end example
2133 @end defmac
2135 @defvar enable-connection-local-variables
2136 If @code{nil}, connection-local variables are ignored.  This variable
2137 shall be changed temporarily only in special modes.
2138 @end defvar
2140 @node Variable Aliases
2141 @section Variable Aliases
2142 @cindex variable aliases
2143 @cindex alias, for variables
2145   It is sometimes useful to make two variables synonyms, so that both
2146 variables always have the same value, and changing either one also
2147 changes the other.  Whenever you change the name of a
2148 variable---either because you realize its old name was not well
2149 chosen, or because its meaning has partly changed---it can be useful
2150 to keep the old name as an @emph{alias} of the new one for
2151 compatibility.  You can do this with @code{defvaralias}.
2153 @defun defvaralias new-alias base-variable &optional docstring
2154 This function defines the symbol @var{new-alias} as a variable alias
2155 for symbol @var{base-variable}. This means that retrieving the value
2156 of @var{new-alias} returns the value of @var{base-variable}, and
2157 changing the value of @var{new-alias} changes the value of
2158 @var{base-variable}.  The two aliased variable names always share the
2159 same value and the same bindings.
2161 If the @var{docstring} argument is non-@code{nil}, it specifies the
2162 documentation for @var{new-alias}; otherwise, the alias gets the same
2163 documentation as @var{base-variable} has, if any, unless
2164 @var{base-variable} is itself an alias, in which case @var{new-alias} gets
2165 the documentation of the variable at the end of the chain of aliases.
2167 This function returns @var{base-variable}.
2168 @end defun
2170   Variable aliases are convenient for replacing an old name for a
2171 variable with a new name.  @code{make-obsolete-variable} declares that
2172 the old name is obsolete and therefore that it may be removed at some
2173 stage in the future.
2175 @defun make-obsolete-variable obsolete-name current-name when &optional access-type
2176 This function makes the byte compiler warn that the variable
2177 @var{obsolete-name} is obsolete.  If @var{current-name} is a symbol,
2178 it is the variable's new name; then the warning message says to use
2179 @var{current-name} instead of @var{obsolete-name}.  If
2180 @var{current-name} is a string, this is the message and there is no
2181 replacement variable.  @var{when} should be a string indicating when
2182 the variable was first made obsolete (usually a version number
2183 string).
2185 The optional argument @var{access-type}, if non-@code{nil}, should
2186 specify the kind of access that will trigger obsolescence warnings; it
2187 can be either @code{get} or @code{set}.
2188 @end defun
2190   You can make two variables synonyms and declare one obsolete at the
2191 same time using the macro @code{define-obsolete-variable-alias}.
2193 @defmac define-obsolete-variable-alias obsolete-name current-name &optional when docstring
2194 This macro marks the variable @var{obsolete-name} as obsolete and also
2195 makes it an alias for the variable @var{current-name}.  It is
2196 equivalent to the following:
2198 @example
2199 (defvaralias @var{obsolete-name} @var{current-name} @var{docstring})
2200 (make-obsolete-variable @var{obsolete-name} @var{current-name} @var{when})
2201 @end example
2202 @end defmac
2204 @defun indirect-variable variable
2205 This function returns the variable at the end of the chain of aliases
2206 of @var{variable}.  If @var{variable} is not a symbol, or if @var{variable} is
2207 not defined as an alias, the function returns @var{variable}.
2209 This function signals a @code{cyclic-variable-indirection} error if
2210 there is a loop in the chain of symbols.
2211 @end defun
2213 @example
2214 (defvaralias 'foo 'bar)
2215 (indirect-variable 'foo)
2216      @result{} bar
2217 (indirect-variable 'bar)
2218      @result{} bar
2219 (setq bar 2)
2221      @result{} 2
2222 @group
2224      @result{} 2
2225 @end group
2226 (setq foo 0)
2228      @result{} 0
2230      @result{} 0
2231 @end example
2233 @node Variables with Restricted Values
2234 @section Variables with Restricted Values
2235 @cindex lisp variables defined in C, restrictions
2237   Ordinary Lisp variables can be assigned any value that is a valid
2238 Lisp object.  However, certain Lisp variables are not defined in Lisp,
2239 but in C@.  Most of these variables are defined in the C code using
2240 @code{DEFVAR_LISP}.  Like variables defined in Lisp, these can take on
2241 any value.  However, some variables are defined using
2242 @code{DEFVAR_INT} or @code{DEFVAR_BOOL}.  @xref{Defining Lisp
2243 variables in C,, Writing Emacs Primitives}, in particular the
2244 description of functions of the type @code{syms_of_@var{filename}},
2245 for a brief discussion of the C implementation.
2247   Variables of type @code{DEFVAR_BOOL} can only take on the values
2248 @code{nil} or @code{t}.  Attempting to assign them any other value
2249 will set them to @code{t}:
2251 @example
2252 (let ((display-hourglass 5))
2253   display-hourglass)
2254      @result{} t
2255 @end example
2257 @defvar byte-boolean-vars
2258 This variable holds a list of all variables of type @code{DEFVAR_BOOL}.
2259 @end defvar
2261   Variables of type @code{DEFVAR_INT} can take on only integer values.
2262 Attempting to assign them any other value will result in an error:
2264 @example
2265 (setq undo-limit 1000.0)
2266 @error{} Wrong type argument: integerp, 1000.0
2267 @end example
2269 @node Generalized Variables
2270 @section Generalized Variables
2272 @cindex generalized variable
2273 @cindex place form
2274 A @dfn{generalized variable} or @dfn{place form} is one of the many places
2275 in Lisp memory where values can be stored.  The simplest place form is
2276 a regular Lisp variable.  But the @sc{car}s and @sc{cdr}s of lists, elements
2277 of arrays, properties of symbols, and many other locations are also
2278 places where Lisp values are stored.
2280 Generalized variables are analogous to lvalues in the C
2281 language, where @samp{x = a[i]} gets an element from an array
2282 and @samp{a[i] = x} stores an element using the same notation.
2283 Just as certain forms like @code{a[i]} can be lvalues in C, there
2284 is a set of forms that can be generalized variables in Lisp.
2286 @menu
2287 * Setting Generalized Variables::   The @code{setf} macro.
2288 * Adding Generalized Variables::    Defining new @code{setf} forms.
2289 @end menu
2291 @node Setting Generalized Variables
2292 @subsection The @code{setf} Macro
2294 The @code{setf} macro is the most basic way to operate on generalized
2295 variables.  The @code{setf} form is like @code{setq}, except that it
2296 accepts arbitrary place forms on the left side rather than just
2297 symbols.  For example, @code{(setf (car a) b)} sets the car of
2298 @code{a} to @code{b}, doing the same operation as @code{(setcar a b)},
2299 but without having to remember two separate functions for setting and
2300 accessing every type of place.
2302 @defmac setf [place form]@dots{}
2303 This macro evaluates @var{form} and stores it in @var{place}, which
2304 must be a valid generalized variable form.  If there are several
2305 @var{place} and @var{form} pairs, the assignments are done sequentially
2306 just as with @code{setq}.  @code{setf} returns the value of the last
2307 @var{form}.
2308 @end defmac
2310 The following Lisp forms will work as generalized variables, and
2311 so may appear in the @var{place} argument of @code{setf}:
2313 @itemize
2314 @item
2315 A symbol naming a variable.  In other words, @code{(setf x y)} is
2316 exactly equivalent to @code{(setq x y)}, and @code{setq} itself is
2317 strictly speaking redundant given that @code{setf} exists.  Many
2318 programmers continue to prefer @code{setq} for setting simple
2319 variables, though, purely for stylistic or historical reasons.
2320 The macro @code{(setf x y)} actually expands to @code{(setq x y)},
2321 so there is no performance penalty for using it in compiled code.
2323 @item
2324 A call to any of the following standard Lisp functions:
2326 @smallexample
2327 aref      cddr      symbol-function
2328 car       elt       symbol-plist
2329 caar      get       symbol-value
2330 cadr      gethash
2331 cdr       nth
2332 cdar      nthcdr
2333 @end smallexample
2335 @item
2336 A call to any of the following Emacs-specific functions:
2338 @smallexample
2339 alist-get                     process-get
2340 frame-parameter               process-sentinel
2341 terminal-parameter            window-buffer
2342 keymap-parent                 window-display-table
2343 match-data                    window-dedicated-p
2344 overlay-get                   window-hscroll
2345 overlay-start                 window-parameter
2346 overlay-end                   window-point
2347 process-buffer                window-start
2348 process-filter                default-value
2349 @end smallexample
2350 @end itemize
2352 @noindent
2353 @code{setf} signals an error if you pass a @var{place} form that it
2354 does not know how to handle.
2356 @c And for cl-lib's cl-getf.
2357 Note that for @code{nthcdr}, the list argument of the function must
2358 itself be a valid @var{place} form.  For example, @code{(setf (nthcdr
2359 0 foo) 7)} will set @code{foo} itself to 7.
2360 @c The use of @code{nthcdr} as a @var{place} form is an extension
2361 @c to standard Common Lisp.
2363 @c FIXME I don't think is a particularly good way to do it,
2364 @c but these macros are introduced before generalized variables are.
2365 The macros @code{push} (@pxref{List Variables}) and @code{pop}
2366 (@pxref{List Elements}) can manipulate generalized variables,
2367 not just lists.  @code{(pop @var{place})} removes and returns the first
2368 element of the list stored in @var{place}.  It is analogous to
2369 @code{(prog1 (car @var{place}) (setf @var{place} (cdr @var{place})))},
2370 except that it takes care to evaluate all subforms only once.
2371 @code{(push @var{x} @var{place})} inserts @var{x} at the front of
2372 the list stored in @var{place}.  It is analogous to @code{(setf
2373 @var{place} (cons @var{x} @var{place}))}, except for evaluation of the
2374 subforms.  Note that @code{push} and @code{pop} on an @code{nthcdr}
2375 place can be used to insert or delete at any position in a list.
2377 The @file{cl-lib} library defines various extensions for generalized
2378 variables, including additional @code{setf} places.
2379 @xref{Generalized Variables,,, cl, Common Lisp Extensions}.
2382 @node Adding Generalized Variables
2383 @subsection Defining new @code{setf} forms
2385 This section describes how to define new forms that @code{setf} can
2386 operate on.
2388 @defmac gv-define-simple-setter name setter &optional fix-return
2389 This macro enables you to easily define @code{setf} methods for simple
2390 cases.  @var{name} is the name of a function, macro, or special form.
2391 You can use this macro whenever @var{name} has a directly
2392 corresponding @var{setter} function that updates it, e.g.,
2393 @code{(gv-define-simple-setter car setcar)}.
2395 This macro translates a call of the form
2397 @example
2398 (setf (@var{name} @var{args}@dots{}) @var{value})
2399 @end example
2401 into
2402 @example
2403 (@var{setter} @var{args}@dots{} @var{value})
2404 @end example
2406 @noindent
2407 Such a @code{setf} call is documented to return @var{value}.  This is
2408 no problem with, e.g., @code{car} and @code{setcar}, because
2409 @code{setcar} returns the value that it set.  If your @var{setter}
2410 function does not return @var{value}, use a non-@code{nil} value for
2411 the @var{fix-return} argument of @code{gv-define-simple-setter}.  This
2412 expands into something equivalent to
2413 @example
2414 (let ((temp @var{value}))
2415   (@var{setter} @var{args}@dots{} temp)
2416   temp)
2417 @end example
2418 so ensuring that it returns the correct result.
2419 @end defmac
2422 @defmac gv-define-setter name arglist &rest body
2423 This macro allows for more complex @code{setf} expansions than the
2424 previous form.  You may need to use this form, for example, if there
2425 is no simple setter function to call, or if there is one but it
2426 requires different arguments to the place form.
2428 This macro expands the form
2429 @code{(setf (@var{name} @var{args}@dots{}) @var{value})} by
2430 first binding the @code{setf} argument forms
2431 @code{(@var{value} @var{args}@dots{})} according to @var{arglist},
2432 and then executing @var{body}.  @var{body} should return a Lisp
2433 form that does the assignment, and finally returns the value that was
2434 set.  An example of using this macro is:
2436 @example
2437 (gv-define-setter caar (val x) `(setcar (car ,x) ,val))
2438 @end example
2439 @end defmac
2441 @findex gv-define-expander
2442 @findex gv-letplace
2443 @c FIXME?  Not sure what or how much to say about these.
2444 @c See cl.texi for an example of using gv-letplace.
2445 For more control over the expansion, see the macro @code{gv-define-expander}.
2446 The macro @code{gv-letplace} can be useful in defining macros that
2447 perform similarly to @code{setf}; for example, the @code{incf} macro
2448 of Common Lisp.  Consult the source file @file{gv.el} for more details.
2450 @cindex CL note---no @code{setf} functions
2451 @quotation
2452 @b{Common Lisp note:} Common Lisp defines another way to specify the
2453 @code{setf} behavior of a function, namely @code{setf} functions,
2454 whose names are lists @code{(setf @var{name})} rather than symbols.
2455 For example, @code{(defun (setf foo) @dots{})} defines the function
2456 that is used when @code{setf} is applied to @code{foo}.  Emacs does
2457 not support this.  It is a compile-time error to use @code{setf} on a
2458 form that has not already had an appropriate expansion defined.  In
2459 Common Lisp, this is not an error since the function @code{(setf
2460 @var{func})} might be defined later.
2461 @end quotation