1 This is Info file ../../info/lispref.info, produced by Makeinfo version
2 1.68 from the input file lispref.texi.
4 INFO-DIR-SECTION XEmacs Editor
6 * Lispref: (lispref). XEmacs Lisp Reference Manual.
11 GNU Emacs Lisp Reference Manual Second Edition (v2.01), May 1993 GNU
12 Emacs Lisp Reference Manual Further Revised (v2.02), August 1993 Lucid
13 Emacs Lisp Reference Manual (for 19.10) First Edition, March 1994
14 XEmacs Lisp Programmer's Manual (for 19.12) Second Edition, April 1995
15 GNU Emacs Lisp Reference Manual v2.4, June 1995 XEmacs Lisp
16 Programmer's Manual (for 19.13) Third Edition, July 1995 XEmacs Lisp
17 Reference Manual (for 19.14 and 20.0) v3.1, March 1996 XEmacs Lisp
18 Reference Manual (for 19.15 and 20.1, 20.2, 20.3) v3.2, April, May,
19 November 1997 XEmacs Lisp Reference Manual (for 21.0) v3.3, April 1998
21 Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995 Free Software
22 Foundation, Inc. Copyright (C) 1994, 1995 Sun Microsystems, Inc.
23 Copyright (C) 1995, 1996 Ben Wing.
25 Permission is granted to make and distribute verbatim copies of this
26 manual provided the copyright notice and this permission notice are
27 preserved on all copies.
29 Permission is granted to copy and distribute modified versions of
30 this manual under the conditions for verbatim copying, provided that the
31 entire resulting derived work is distributed under the terms of a
32 permission notice identical to this one.
34 Permission is granted to copy and distribute translations of this
35 manual into another language, under the above conditions for modified
36 versions, except that this permission notice may be stated in a
37 translation approved by the Foundation.
39 Permission is granted to copy and distribute modified versions of
40 this manual under the conditions for verbatim copying, provided also
41 that the section entitled "GNU General Public License" is included
42 exactly as in the original, and provided that the entire resulting
43 derived work is distributed under the terms of a permission notice
44 identical to this one.
46 Permission is granted to copy and distribute translations of this
47 manual into another language, under the above conditions for modified
48 versions, except that the section entitled "GNU General Public License"
49 may be included in a translation approved by the Free Software
50 Foundation instead of in the original English.
53 File: lispref.info, Node: Cleanups, Prev: Errors, Up: Nonlocal Exits
55 Cleaning Up from Nonlocal Exits
56 -------------------------------
58 The `unwind-protect' construct is essential whenever you temporarily
59 put a data structure in an inconsistent state; it permits you to ensure
60 the data are consistent in the event of an error or throw.
62 - Special Form: unwind-protect BODY CLEANUP-FORMS...
63 `unwind-protect' executes the BODY with a guarantee that the
64 CLEANUP-FORMS will be evaluated if control leaves BODY, no matter
65 how that happens. The BODY may complete normally, or execute a
66 `throw' out of the `unwind-protect', or cause an error; in all
67 cases, the CLEANUP-FORMS will be evaluated.
69 If the BODY forms finish normally, `unwind-protect' returns the
70 value of the last BODY form, after it evaluates the CLEANUP-FORMS.
71 If the BODY forms do not finish, `unwind-protect' does not return
72 any value in the normal sense.
74 Only the BODY is actually protected by the `unwind-protect'. If
75 any of the CLEANUP-FORMS themselves exits nonlocally (e.g., via a
76 `throw' or an error), `unwind-protect' is *not* guaranteed to
77 evaluate the rest of them. If the failure of one of the
78 CLEANUP-FORMS has the potential to cause trouble, then protect it
79 with another `unwind-protect' around that form.
81 The number of currently active `unwind-protect' forms counts,
82 together with the number of local variable bindings, against the
83 limit `max-specpdl-size' (*note Local Variables::.).
85 For example, here we make an invisible buffer for temporary use, and
86 make sure to kill it before finishing:
89 (let ((buffer (get-buffer-create " *temp*")))
93 (kill-buffer buffer))))
95 You might think that we could just as well write `(kill-buffer
96 (current-buffer))' and dispense with the variable `buffer'. However,
97 the way shown above is safer, if BODY happens to get an error after
98 switching to a different buffer! (Alternatively, you could write
99 another `save-excursion' around the body, to ensure that the temporary
100 buffer becomes current in time to kill it.)
102 Here is an actual example taken from the file `ftp.el'. It creates
103 a process (*note Processes::.) to try to establish a connection to a
104 remote machine. As the function `ftp-login' is highly susceptible to
105 numerous problems that the writer of the function cannot anticipate, it
106 is protected with a form that guarantees deletion of the process in the
107 event of failure. Otherwise, XEmacs might fill up with useless
113 (setq process (ftp-setup-buffer host file))
114 (if (setq win (ftp-login process host user password))
115 (message "Logged in")
116 (error "Ftp login failed")))
117 (or win (and process (delete-process process)))))
119 This example actually has a small bug: if the user types `C-g' to
120 quit, and the quit happens immediately after the function
121 `ftp-setup-buffer' returns but before the variable `process' is set,
122 the process will not be killed. There is no easy way to fix this bug,
123 but at least it is very unlikely.
125 Here is another example which uses `unwind-protect' to make sure to
126 kill a temporary buffer. In this example, the value returned by
127 `unwind-protect' is used.
129 (defun shell-command-string (cmd)
130 "Return the output of the shell command CMD, as a string."
132 (set-buffer (generate-new-buffer " OS*cmd"))
133 (shell-command cmd t)
136 (kill-buffer (current-buffer)))))
139 File: lispref.info, Node: Variables, Next: Functions, Prev: Control Structures, Up: Top
144 A "variable" is a name used in a program to stand for a value.
145 Nearly all programming languages have variables of some sort. In the
146 text of a Lisp program, variables are written using the syntax for
149 In Lisp, unlike most programming languages, programs are represented
150 primarily as Lisp objects and only secondarily as text. The Lisp
151 objects used for variables are symbols: the symbol name is the variable
152 name, and the variable's value is stored in the value cell of the
153 symbol. The use of a symbol as a variable is independent of its use as
154 a function name. *Note Symbol Components::.
156 The Lisp objects that constitute a Lisp program determine the textual
157 form of the program--it is simply the read syntax for those Lisp
158 objects. This is why, for example, a variable in a textual Lisp program
159 is written using the read syntax for the symbol that represents the
164 * Global Variables:: Variable values that exist permanently, everywhere.
165 * Constant Variables:: Certain "variables" have values that never change.
166 * Local Variables:: Variable values that exist only temporarily.
167 * Void Variables:: Symbols that lack values.
168 * Defining Variables:: A definition says a symbol is used as a variable.
169 * Accessing Variables:: Examining values of variables whose names
170 are known only at run time.
171 * Setting Variables:: Storing new values in variables.
172 * Variable Scoping:: How Lisp chooses among local and global values.
173 * Buffer-Local Variables:: Variable values in effect only in one buffer.
174 * Variable Aliases:: Making one variable point to another.
177 File: lispref.info, Node: Global Variables, Next: Constant Variables, Up: Variables
182 The simplest way to use a variable is "globally". This means that
183 the variable has just one value at a time, and this value is in effect
184 (at least for the moment) throughout the Lisp system. The value remains
185 in effect until you specify a new one. When a new value replaces the
186 old one, no trace of the old value remains in the variable.
188 You specify a value for a symbol with `setq'. For example,
192 gives the variable `x' the value `(a b)'. Note that `setq' does not
193 evaluate its first argument, the name of the variable, but it does
194 evaluate the second argument, the new value.
196 Once the variable has a value, you can refer to it by using the
197 symbol by itself as an expression. Thus,
201 assuming the `setq' form shown above has already been executed.
203 If you do another `setq', the new value replaces the old one:
213 File: lispref.info, Node: Constant Variables, Next: Local Variables, Prev: Global Variables, Up: Variables
215 Variables That Never Change
216 ===========================
218 In XEmacs Lisp, some symbols always evaluate to themselves: the two
219 special symbols `nil' and `t', as well as "keyword symbols", that is,
220 symbols whose name begins with the character ``:''. These symbols
221 cannot be rebound, nor can their value cells be changed. An attempt to
222 change the value of `nil' or `t' signals a `setting-constant' error.
227 error--> Attempt to set constant symbol: nil
230 File: lispref.info, Node: Local Variables, Next: Void Variables, Prev: Constant Variables, Up: Variables
235 Global variables have values that last until explicitly superseded
236 with new values. Sometimes it is useful to create variable values that
237 exist temporarily--only while within a certain part of the program.
238 These values are called "local", and the variables so used are called
241 For example, when a function is called, its argument variables
242 receive new local values that last until the function exits. The `let'
243 special form explicitly establishes new local values for specified
244 variables; these last until exit from the `let' form.
246 Establishing a local value saves away the previous value (or lack of
247 one) of the variable. When the life span of the local value is over,
248 the previous value is restored. In the mean time, we say that the
249 previous value is "shadowed" and "not visible". Both global and local
250 values may be shadowed (*note Scope::.).
252 If you set a variable (such as with `setq') while it is local, this
253 replaces the local value; it does not alter the global value, or
254 previous local values that are shadowed. To model this behavior, we
255 speak of a "local binding" of the variable as well as a local value.
257 The local binding is a conceptual place that holds a local value.
258 Entry to a function, or a special form such as `let', creates the local
259 binding; exit from the function or from the `let' removes the local
260 binding. As long as the local binding lasts, the variable's value is
261 stored within it. Use of `setq' or `set' while there is a local
262 binding stores a different value into the local binding; it does not
263 create a new binding.
265 We also speak of the "global binding", which is where (conceptually)
266 the global value is kept.
268 A variable can have more than one local binding at a time (for
269 example, if there are nested `let' forms that bind it). In such a
270 case, the most recently created local binding that still exists is the
271 "current binding" of the variable. (This is called "dynamic scoping";
272 see *Note Variable Scoping::.) If there are no local bindings, the
273 variable's global binding is its current binding. We also call the
274 current binding the "most-local existing binding", for emphasis.
275 Ordinary evaluation of a symbol always returns the value of its current
278 The special forms `let' and `let*' exist to create local bindings.
280 - Special Form: let (BINDINGS...) FORMS...
281 This special form binds variables according to BINDINGS and then
282 evaluates all of the FORMS in textual order. The `let'-form
283 returns the value of the last form in FORMS.
285 Each of the BINDINGS is either (i) a symbol, in which case that
286 symbol is bound to `nil'; or (ii) a list of the form `(SYMBOL
287 VALUE-FORM)', in which case SYMBOL is bound to the result of
288 evaluating VALUE-FORM. If VALUE-FORM is omitted, `nil' is used.
290 All of the VALUE-FORMs in BINDINGS are evaluated in the order they
291 appear and *before* any of the symbols are bound. Here is an
292 example of this: `Z' is bound to the old value of `Y', which is 2,
293 not the new value, 1.
302 - Special Form: let* (BINDINGS...) FORMS...
303 This special form is like `let', but it binds each variable right
304 after computing its local value, before computing the local value
305 for the next variable. Therefore, an expression in BINDINGS can
306 reasonably refer to the preceding symbols bound in this `let*'
307 form. Compare the following example with the example above for
313 (Z Y)) ; Use the just-established value of `Y'.
317 Here is a complete list of the other facilities that create local
320 * Function calls (*note Functions::.).
322 * Macro calls (*note Macros::.).
324 * `condition-case' (*note Errors::.).
326 Variables can also have buffer-local bindings (*note Buffer-Local
327 Variables::.). These kinds of bindings work somewhat like ordinary
328 local bindings, but they are localized depending on "where" you are in
329 Emacs, rather than localized in time.
331 - Variable: max-specpdl-size
332 This variable defines the limit on the total number of local
333 variable bindings and `unwind-protect' cleanups (*note Nonlocal
334 Exits::.) that are allowed before signaling an error (with data
335 `"Variable binding depth exceeds max-specpdl-size"').
337 This limit, with the associated error when it is exceeded, is one
338 way that Lisp avoids infinite recursion on an ill-defined function.
340 The default value is 600.
342 `max-lisp-eval-depth' provides another limit on depth of nesting.
346 File: lispref.info, Node: Void Variables, Next: Defining Variables, Prev: Local Variables, Up: Variables
348 When a Variable is "Void"
349 =========================
351 If you have never given a symbol any value as a global variable, we
352 say that that symbol's global value is "void". In other words, the
353 symbol's value cell does not have any Lisp object in it. If you try to
354 evaluate the symbol, you get a `void-variable' error rather than a
357 Note that a value of `nil' is not the same as void. The symbol
358 `nil' is a Lisp object and can be the value of a variable just as any
359 other object can be; but it is *a value*. A void variable does not
362 After you have given a variable a value, you can make it void once
363 more using `makunbound'.
365 - Function: makunbound SYMBOL
366 This function makes the current binding of SYMBOL void.
367 Subsequent attempts to use this symbol's value as a variable will
368 signal the error `void-variable', unless or until you set it again.
370 `makunbound' returns SYMBOL.
372 (makunbound 'x) ; Make the global value
376 error--> Symbol's value as variable is void: x
378 If SYMBOL is locally bound, `makunbound' affects the most local
379 existing binding. This is the only way a symbol can have a void
380 local binding, since all the constructs that create local bindings
381 create them with values. In this case, the voidness lasts at most
382 as long as the binding does; when the binding is removed due to
383 exit from the construct that made it, the previous or global
384 binding is reexposed as usual, and the variable is no longer void
385 unless the newly reexposed binding was void all along.
387 (setq x 1) ; Put a value in the global binding.
389 (let ((x 2)) ; Locally bind it.
390 (makunbound 'x) ; Void the local binding.
392 error--> Symbol's value as variable is void: x
394 x ; The global binding is unchanged.
397 (let ((x 2)) ; Locally bind it.
398 (let ((x 3)) ; And again.
399 (makunbound 'x) ; Void the innermost-local binding.
400 x)) ; And refer: it's void.
401 error--> Symbol's value as variable is void: x
405 (makunbound 'x)) ; Void inner binding, then remove it.
406 x) ; Now outer `let' binding is visible.
409 A variable that has been made void with `makunbound' is
410 indistinguishable from one that has never received a value and has
413 You can use the function `boundp' to test whether a variable is
416 - Function: boundp VARIABLE
417 `boundp' returns `t' if VARIABLE (a symbol) is not void; more
418 precisely, if its current binding is not void. It returns `nil'
421 (boundp 'abracadabra) ; Starts out void.
424 (let ((abracadabra 5)) ; Locally bind it.
425 (boundp 'abracadabra))
428 (boundp 'abracadabra) ; Still globally void.
431 (setq abracadabra 5) ; Make it globally nonvoid.
434 (boundp 'abracadabra)
438 File: lispref.info, Node: Defining Variables, Next: Accessing Variables, Prev: Void Variables, Up: Variables
440 Defining Global Variables
441 =========================
443 You may announce your intention to use a symbol as a global variable
444 with a "variable definition": a special form, either `defconst' or
447 In XEmacs Lisp, definitions serve three purposes. First, they inform
448 people who read the code that certain symbols are *intended* to be used
449 a certain way (as variables). Second, they inform the Lisp system of
450 these things, supplying a value and documentation. Third, they provide
451 information to utilities such as `etags' and `make-docfile', which
452 create data bases of the functions and variables in a program.
454 The difference between `defconst' and `defvar' is primarily a matter
455 of intent, serving to inform human readers of whether programs will
456 change the variable. XEmacs Lisp does not restrict the ways in which a
457 variable can be used based on `defconst' or `defvar' declarations.
458 However, it does make a difference for initialization: `defconst'
459 unconditionally initializes the variable, while `defvar' initializes it
462 One would expect user option variables to be defined with
463 `defconst', since programs do not change them. Unfortunately, this has
464 bad results if the definition is in a library that is not preloaded:
465 `defconst' would override any prior value when the library is loaded.
466 Users would like to be able to set user options in their init files,
467 and override the default values given in the definitions. For this
468 reason, user options must be defined with `defvar'.
470 - Special Form: defvar SYMBOL [VALUE [DOC-STRING]]
471 This special form defines SYMBOL as a value and initializes it.
472 The definition informs a person reading your code that SYMBOL is
473 used as a variable that programs are likely to set or change. It
474 is also used for all user option variables except in the preloaded
475 parts of XEmacs. Note that SYMBOL is not evaluated; the symbol to
476 be defined must appear explicitly in the `defvar'.
478 If SYMBOL already has a value (i.e., it is not void), VALUE is not
479 even evaluated, and SYMBOL's value remains unchanged. If SYMBOL
480 is void and VALUE is specified, `defvar' evaluates it and sets
481 SYMBOL to the result. (If VALUE is omitted, the value of SYMBOL
482 is not changed in any case.)
484 When you evaluate a top-level `defvar' form with `C-M-x' in Emacs
485 Lisp mode (`eval-defun'), a special feature of `eval-defun'
486 evaluates it as a `defconst'. The purpose of this is to make sure
487 the variable's value is reinitialized, when you ask for it
490 If SYMBOL has a buffer-local binding in the current buffer,
491 `defvar' sets the default value, not the local value. *Note
492 Buffer-Local Variables::.
494 If the DOC-STRING argument appears, it specifies the documentation
495 for the variable. (This opportunity to specify documentation is
496 one of the main benefits of defining the variable.) The
497 documentation is stored in the symbol's `variable-documentation'
498 property. The XEmacs help functions (*note Documentation::.) look
501 If the first character of DOC-STRING is `*', it means that this
502 variable is considered a user option. This lets users set the
503 variable conveniently using the commands `set-variable' and
506 For example, this form defines `foo' but does not set its value:
511 The following example sets the value of `bar' to `23', and gives
512 it a documentation string:
515 "The normal weight of a bar.")
518 The following form changes the documentation string for `bar',
519 making it a user option, but does not change the value, since `bar'
520 already has a value. (The addition `(1+ 23)' is not even
524 "*The normal weight of a bar.")
529 Here is an equivalent expression for the `defvar' special form:
531 (defvar SYMBOL VALUE DOC-STRING)
534 (if (not (boundp 'SYMBOL))
536 (put 'SYMBOL 'variable-documentation 'DOC-STRING)
539 The `defvar' form returns SYMBOL, but it is normally used at top
540 level in a file where its value does not matter.
542 - Special Form: defconst SYMBOL [VALUE [DOC-STRING]]
543 This special form defines SYMBOL as a value and initializes it.
544 It informs a person reading your code that SYMBOL has a global
545 value, established here, that will not normally be changed or
546 locally bound by the execution of the program. The user, however,
547 may be welcome to change it. Note that SYMBOL is not evaluated;
548 the symbol to be defined must appear explicitly in the `defconst'.
550 `defconst' always evaluates VALUE and sets the global value of
551 SYMBOL to the result, provided VALUE is given. If SYMBOL has a
552 buffer-local binding in the current buffer, `defconst' sets the
553 default value, not the local value.
555 *Please note:* Don't use `defconst' for user option variables in
556 libraries that are not standardly preloaded. The user should be
557 able to specify a value for such a variable in the `.emacs' file,
558 so that it will be in effect if and when the library is loaded
561 Here, `pi' is a constant that presumably ought not to be changed
562 by anyone (attempts by the Indiana State Legislature
563 notwithstanding). As the second form illustrates, however, this
566 (defconst pi 3.1415 "Pi to five places.")
573 - Function: user-variable-p VARIABLE
574 This function returns `t' if VARIABLE is a user option--a variable
575 intended to be set by the user for customization--and `nil'
576 otherwise. (Variables other than user options exist for the
577 internal purposes of Lisp programs, and users need not know about
580 User option variables are distinguished from other variables by the
581 first character of the `variable-documentation' property. If the
582 property exists and is a string, and its first character is `*',
583 then the variable is a user option.
585 If a user option variable has a `variable-interactive' property, the
586 `set-variable' command uses that value to control reading the new value
587 for the variable. The property's value is used as if it were the
588 argument to `interactive'.
590 *Warning:* If the `defconst' and `defvar' special forms are used
591 while the variable has a local binding, they set the local binding's
592 value; the global binding is not changed. This is not what we really
593 want. To prevent it, use these special forms at top level in a file,
594 where normally no local binding is in effect, and make sure to load the
595 file before making a local binding for the variable.
598 File: lispref.info, Node: Accessing Variables, Next: Setting Variables, Prev: Defining Variables, Up: Variables
600 Accessing Variable Values
601 =========================
603 The usual way to reference a variable is to write the symbol which
604 names it (*note Symbol Forms::.). This requires you to specify the
605 variable name when you write the program. Usually that is exactly what
606 you want to do. Occasionally you need to choose at run time which
607 variable to reference; then you can use `symbol-value'.
609 - Function: symbol-value SYMBOL
610 This function returns the value of SYMBOL. This is the value in
611 the innermost local binding of the symbol, or its global value if
612 it has no local bindings.
619 ;; Here the symbol `abracadabra'
620 ;; is the symbol whose value is examined.
621 (let ((abracadabra 'foo))
622 (symbol-value 'abracadabra))
625 ;; Here the value of `abracadabra',
627 ;; is the symbol whose value is examined.
628 (let ((abracadabra 'foo))
629 (symbol-value abracadabra))
632 (symbol-value 'abracadabra)
635 A `void-variable' error is signaled if SYMBOL has neither a local
636 binding nor a global value.
639 File: lispref.info, Node: Setting Variables, Next: Variable Scoping, Prev: Accessing Variables, Up: Variables
641 How to Alter a Variable Value
642 =============================
644 The usual way to change the value of a variable is with the special
645 form `setq'. When you need to compute the choice of variable at run
646 time, use the function `set'.
648 - Special Form: setq [SYMBOL FORM]...
649 This special form is the most common method of changing a
650 variable's value. Each SYMBOL is given a new value, which is the
651 result of evaluating the corresponding FORM. The most-local
652 existing binding of the symbol is changed.
654 `setq' does not evaluate SYMBOL; it sets the symbol that you
655 write. We say that this argument is "automatically quoted". The
656 `q' in `setq' stands for "quoted."
658 The value of the `setq' form is the value of the last FORM.
662 x ; `x' now has a global value.
665 (setq x 6) ; The local binding of `x' is set.
668 x ; The global value is unchanged.
671 Note that the first FORM is evaluated, then the first SYMBOL is
672 set, then the second FORM is evaluated, then the second SYMBOL is
675 (setq x 10 ; Notice that `x' is set before
676 y (1+ x)) ; the value of `y' is computed.
679 - Function: set SYMBOL VALUE
680 This function sets SYMBOL's value to VALUE, then returns VALUE.
681 Since `set' is a function, the expression written for SYMBOL is
682 evaluated to obtain the symbol to set.
684 The most-local existing binding of the variable is the binding
685 that is set; shadowed bindings are not affected.
688 error--> Symbol's value as variable is void: one
693 (set two 2) ; `two' evaluates to symbol `one'.
695 one ; So it is `one' that was set.
697 (let ((one 1)) ; This binding of `one' is set,
698 (set 'one 3) ; not the global value.
704 If SYMBOL is not actually a symbol, a `wrong-type-argument' error
708 error--> Wrong type argument: symbolp, (x y)
710 Logically speaking, `set' is a more fundamental primitive than
711 `setq'. Any use of `setq' can be trivially rewritten to use
712 `set'; `setq' could even be defined as a macro, given the
713 availability of `set'. However, `set' itself is rarely used;
714 beginners hardly need to know about it. It is useful only for
715 choosing at run time which variable to set. For example, the
716 command `set-variable', which reads a variable name from the user
717 and then sets the variable, needs to use `set'.
719 Common Lisp note: In Common Lisp, `set' always changes the
720 symbol's special value, ignoring any lexical bindings. In
721 XEmacs Lisp, all variables and all bindings are (in effect)
722 special, so `set' always affects the most local existing
725 One other function for setting a variable is designed to add an
726 element to a list if it is not already present in the list.
728 - Function: add-to-list SYMBOL ELEMENT
729 This function sets the variable SYMBOL by consing ELEMENT onto the
730 old value, if ELEMENT is not already a member of that value. It
731 returns the resulting list, whether updated or not. The value of
732 SYMBOL had better be a list already before the call.
734 The argument SYMBOL is not implicitly quoted; `add-to-list' is an
735 ordinary function, like `set' and unlike `setq'. Quote the
736 argument yourself if that is what you want.
738 Here's a scenario showing how to use `add-to-list':
743 (add-to-list 'foo 'c) ;; Add `c'.
746 (add-to-list 'foo 'b) ;; No effect.
749 foo ;; `foo' was changed.
752 An equivalent expression for `(add-to-list 'VAR VALUE)' is this:
754 (or (member VALUE VAR)
755 (setq VAR (cons VALUE VAR)))
758 File: lispref.info, Node: Variable Scoping, Next: Buffer-Local Variables, Prev: Setting Variables, Up: Variables
760 Scoping Rules for Variable Bindings
761 ===================================
763 A given symbol `foo' may have several local variable bindings,
764 established at different places in the Lisp program, as well as a global
765 binding. The most recently established binding takes precedence over
768 Local bindings in XEmacs Lisp have "indefinite scope" and "dynamic
769 extent". "Scope" refers to *where* textually in the source code the
770 binding can be accessed. Indefinite scope means that any part of the
771 program can potentially access the variable binding. "Extent" refers
772 to *when*, as the program is executing, the binding exists. Dynamic
773 extent means that the binding lasts as long as the activation of the
774 construct that established it.
776 The combination of dynamic extent and indefinite scope is called
777 "dynamic scoping". By contrast, most programming languages use
778 "lexical scoping", in which references to a local variable must be
779 located textually within the function or block that binds the variable.
781 Common Lisp note: Variables declared "special" in Common Lisp are
782 dynamically scoped, like variables in XEmacs Lisp.
786 * Scope:: Scope means where in the program a value is visible.
787 Comparison with other languages.
788 * Extent:: Extent means how long in time a value exists.
789 * Impl of Scope:: Two ways to implement dynamic scoping.
790 * Using Scoping:: How to use dynamic scoping carefully and avoid problems.
793 File: lispref.info, Node: Scope, Next: Extent, Up: Variable Scoping
798 XEmacs Lisp uses "indefinite scope" for local variable bindings.
799 This means that any function anywhere in the program text might access a
800 given binding of a variable. Consider the following function
803 (defun binder (x) ; `x' is bound in `binder'.
804 (foo 5)) ; `foo' is some other function.
806 (defun user () ; `x' is used in `user'.
809 In a lexically scoped language, the binding of `x' in `binder' would
810 never be accessible in `user', because `user' is not textually
811 contained within the function `binder'. However, in dynamically scoped
812 XEmacs Lisp, `user' may or may not refer to the binding of `x'
813 established in `binder', depending on circumstances:
815 * If we call `user' directly without calling `binder' at all, then
816 whatever binding of `x' is found, it cannot come from `binder'.
818 * If we define `foo' as follows and call `binder', then the binding
819 made in `binder' will be seen in `user':
824 * If we define `foo' as follows and call `binder', then the binding
825 made in `binder' *will not* be seen in `user':
830 Here, when `foo' is called by `binder', it binds `x'. (The
831 binding in `foo' is said to "shadow" the one made in `binder'.)
832 Therefore, `user' will access the `x' bound by `foo' instead of
833 the one bound by `binder'.
836 File: lispref.info, Node: Extent, Next: Impl of Scope, Prev: Scope, Up: Variable Scoping
841 "Extent" refers to the time during program execution that a variable
842 name is valid. In XEmacs Lisp, a variable is valid only while the form
843 that bound it is executing. This is called "dynamic extent". "Local"
844 or "automatic" variables in most languages, including C and Pascal,
847 One alternative to dynamic extent is "indefinite extent". This
848 means that a variable binding can live on past the exit from the form
849 that made the binding. Common Lisp and Scheme, for example, support
850 this, but XEmacs Lisp does not.
852 To illustrate this, the function below, `make-add', returns a
853 function that purports to add N to its own argument M. This would work
854 in Common Lisp, but it does not work as intended in XEmacs Lisp,
855 because after the call to `make-add' exits, the variable `n' is no
856 longer bound to the actual argument 2.
859 (function (lambda (m) (+ n m)))) ; Return a function.
861 (fset 'add2 (make-add 2)) ; Define function `add2'
862 ; with `(make-add 2)'.
863 => (lambda (m) (+ n m))
864 (add2 4) ; Try to add 2 to 4.
865 error--> Symbol's value as variable is void: n
867 Some Lisp dialects have "closures", objects that are like functions
868 but record additional variable bindings. XEmacs Lisp does not have
872 File: lispref.info, Node: Impl of Scope, Next: Using Scoping, Prev: Extent, Up: Variable Scoping
874 Implementation of Dynamic Scoping
875 ---------------------------------
877 A simple sample implementation (which is not how XEmacs Lisp actually
878 works) may help you understand dynamic binding. This technique is
879 called "deep binding" and was used in early Lisp systems.
881 Suppose there is a stack of bindings: variable-value pairs. At entry
882 to a function or to a `let' form, we can push bindings on the stack for
883 the arguments or local variables created there. We can pop those
884 bindings from the stack at exit from the binding construct.
886 We can find the value of a variable by searching the stack from top
887 to bottom for a binding for that variable; the value from that binding
888 is the value of the variable. To set the variable, we search for the
889 current binding, then store the new value into that binding.
891 As you can see, a function's bindings remain in effect as long as it
892 continues execution, even during its calls to other functions. That is
893 why we say the extent of the binding is dynamic. And any other function
894 can refer to the bindings, if it uses the same variables while the
895 bindings are in effect. That is why we say the scope is indefinite.
897 The actual implementation of variable scoping in XEmacs Lisp uses a
898 technique called "shallow binding". Each variable has a standard place
899 in which its current value is always found--the value cell of the
902 In shallow binding, setting the variable works by storing a value in
903 the value cell. Creating a new binding works by pushing the old value
904 (belonging to a previous binding) on a stack, and storing the local
905 value in the value cell. Eliminating a binding works by popping the
906 old value off the stack, into the value cell.
908 We use shallow binding because it has the same results as deep
909 binding, but runs faster, since there is never a need to search for a
913 File: lispref.info, Node: Using Scoping, Prev: Impl of Scope, Up: Variable Scoping
915 Proper Use of Dynamic Scoping
916 -----------------------------
918 Binding a variable in one function and using it in another is a
919 powerful technique, but if used without restraint, it can make programs
920 hard to understand. There are two clean ways to use this technique:
922 * Use or bind the variable only in a few related functions, written
923 close together in one file. Such a variable is used for
924 communication within one program.
926 You should write comments to inform other programmers that they
927 can see all uses of the variable before them, and to advise them
928 not to add uses elsewhere.
930 * Give the variable a well-defined, documented meaning, and make all
931 appropriate functions refer to it (but not bind it or set it)
932 wherever that meaning is relevant. For example, the variable
933 `case-fold-search' is defined as "non-`nil' means ignore case when
934 searching"; various search and replace functions refer to it
935 directly or through their subroutines, but do not bind or set it.
937 Then you can bind the variable in other programs, knowing reliably
938 what the effect will be.
940 In either case, you should define the variable with `defvar'. This
941 helps other people understand your program by telling them to look for
942 inter-function usage. It also avoids a warning from the byte compiler.
943 Choose the variable's name to avoid name conflicts--don't use short
947 File: lispref.info, Node: Buffer-Local Variables, Next: Variable Aliases, Prev: Variable Scoping, Up: Variables
949 Buffer-Local Variables
950 ======================
952 Global and local variable bindings are found in most programming
953 languages in one form or another. XEmacs also supports another, unusual
954 kind of variable binding: "buffer-local" bindings, which apply only to
955 one buffer. XEmacs Lisp is meant for programming editing commands, and
956 having different values for a variable in different buffers is an
957 important customization method.
961 * Intro to Buffer-Local:: Introduction and concepts.
962 * Creating Buffer-Local:: Creating and destroying buffer-local bindings.
963 * Default Value:: The default value is seen in buffers
964 that don't have their own local values.
967 File: lispref.info, Node: Intro to Buffer-Local, Next: Creating Buffer-Local, Up: Buffer-Local Variables
969 Introduction to Buffer-Local Variables
970 --------------------------------------
972 A buffer-local variable has a buffer-local binding associated with a
973 particular buffer. The binding is in effect when that buffer is
974 current; otherwise, it is not in effect. If you set the variable while
975 a buffer-local binding is in effect, the new value goes in that binding,
976 so the global binding is unchanged; this means that the change is
977 visible in that buffer alone.
979 A variable may have buffer-local bindings in some buffers but not in
980 others. The global binding is shared by all the buffers that don't have
981 their own bindings. Thus, if you set the variable in a buffer that does
982 not have a buffer-local binding for it, the new value is visible in all
983 buffers except those with buffer-local bindings. (Here we are assuming
984 that there are no `let'-style local bindings to complicate the issue.)
986 The most common use of buffer-local bindings is for major modes to
987 change variables that control the behavior of commands. For example, C
988 mode and Lisp mode both set the variable `paragraph-start' to specify
989 that only blank lines separate paragraphs. They do this by making the
990 variable buffer-local in the buffer that is being put into C mode or
991 Lisp mode, and then setting it to the new value for that mode.
993 The usual way to make a buffer-local binding is with
994 `make-local-variable', which is what major mode commands use. This
995 affects just the current buffer; all other buffers (including those yet
996 to be created) continue to share the global value.
998 A more powerful operation is to mark the variable as "automatically
999 buffer-local" by calling `make-variable-buffer-local'. You can think
1000 of this as making the variable local in all buffers, even those yet to
1001 be created. More precisely, the effect is that setting the variable
1002 automatically makes the variable local to the current buffer if it is
1003 not already so. All buffers start out by sharing the global value of
1004 the variable as usual, but any `setq' creates a buffer-local binding
1005 for the current buffer. The new value is stored in the buffer-local
1006 binding, leaving the (default) global binding untouched. The global
1007 value can no longer be changed with `setq'; you need to use
1008 `setq-default' to do that.
1010 Local variables in a file you edit are also represented by
1011 buffer-local bindings for the buffer that holds the file within XEmacs.
1012 *Note Auto Major Mode::.
1015 File: lispref.info, Node: Creating Buffer-Local, Next: Default Value, Prev: Intro to Buffer-Local, Up: Buffer-Local Variables
1017 Creating and Deleting Buffer-Local Bindings
1018 -------------------------------------------
1020 - Command: make-local-variable VARIABLE
1021 This function creates a buffer-local binding in the current buffer
1022 for VARIABLE (a symbol). Other buffers are not affected. The
1023 value returned is VARIABLE.
1025 The buffer-local value of VARIABLE starts out as the same value
1026 VARIABLE previously had. If VARIABLE was void, it remains void.
1029 (setq foo 5) ; Affects all buffers.
1031 (make-local-variable 'foo) ; Now it is local in `b1'.
1033 foo ; That did not change
1035 (setq foo 6) ; Change the value
1040 ;; In buffer `b2', the value hasn't changed.
1046 Making a variable buffer-local within a `let'-binding for that
1047 variable does not work. This is because `let' does not distinguish
1048 between different kinds of bindings; it knows only which variable
1049 the binding was made for.
1051 *Please note:* do not use `make-local-variable' for a hook
1052 variable. Instead, use `make-local-hook'. *Note Hooks::.
1054 - Command: make-variable-buffer-local VARIABLE
1055 This function marks VARIABLE (a symbol) automatically
1056 buffer-local, so that any subsequent attempt to set it will make it
1057 local to the current buffer at the time.
1059 The value returned is VARIABLE.
1061 - Function: local-variable-p VARIABLE &optional BUFFER
1062 This returns `t' if VARIABLE is buffer-local in buffer BUFFER
1063 (which defaults to the current buffer); otherwise, `nil'.
1065 - Function: buffer-local-variables &optional BUFFER
1066 This function returns a list describing the buffer-local variables
1067 in buffer BUFFER. It returns an association list (*note
1068 Association Lists::.) in which each association contains one
1069 buffer-local variable and its value. When a buffer-local variable
1070 is void in BUFFER, then it appears directly in the resulting list.
1071 If BUFFER is omitted, the current buffer is used.
1073 (make-local-variable 'foobar)
1074 (makunbound 'foobar)
1075 (make-local-variable 'bind-me)
1077 (setq lcl (buffer-local-variables))
1078 ;; First, built-in variables local in all buffers:
1079 => ((mark-active . nil)
1080 (buffer-undo-list nil)
1081 (mode-name . "Fundamental")
1083 ;; Next, non-built-in local variables.
1084 ;; This one is local and void:
1086 ;; This one is local and nonvoid:
1089 Note that storing new values into the CDRs of cons cells in this
1090 list does *not* change the local values of the variables.
1092 - Command: kill-local-variable VARIABLE
1093 This function deletes the buffer-local binding (if any) for
1094 VARIABLE (a symbol) in the current buffer. As a result, the
1095 global (default) binding of VARIABLE becomes visible in this
1096 buffer. Usually this results in a change in the value of
1097 VARIABLE, since the global value is usually different from the
1098 buffer-local value just eliminated.
1100 If you kill the local binding of a variable that automatically
1101 becomes local when set, this makes the global value visible in the
1102 current buffer. However, if you set the variable again, that will
1103 once again create a local binding for it.
1105 `kill-local-variable' returns VARIABLE.
1107 This function is a command because it is sometimes useful to kill
1108 one buffer-local variable interactively, just as it is useful to
1109 create buffer-local variables interactively.
1111 - Function: kill-all-local-variables
1112 This function eliminates all the buffer-local variable bindings of
1113 the current buffer except for variables marked as "permanent". As
1114 a result, the buffer will see the default values of most variables.
1116 This function also resets certain other information pertaining to
1117 the buffer: it sets the local keymap to `nil', the syntax table to
1118 the value of `standard-syntax-table', and the abbrev table to the
1119 value of `fundamental-mode-abbrev-table'.
1121 Every major mode command begins by calling this function, which
1122 has the effect of switching to Fundamental mode and erasing most
1123 of the effects of the previous major mode. To ensure that this
1124 does its job, the variables that major modes set should not be
1127 `kill-all-local-variables' returns `nil'.
1129 A local variable is "permanent" if the variable name (a symbol) has a
1130 `permanent-local' property that is non-`nil'. Permanent locals are
1131 appropriate for data pertaining to where the file came from or how to
1132 save it, rather than with how to edit the contents.
1135 File: lispref.info, Node: Default Value, Prev: Creating Buffer-Local, Up: Buffer-Local Variables
1137 The Default Value of a Buffer-Local Variable
1138 --------------------------------------------
1140 The global value of a variable with buffer-local bindings is also
1141 called the "default" value, because it is the value that is in effect
1142 except when specifically overridden.
1144 The functions `default-value' and `setq-default' access and change a
1145 variable's default value regardless of whether the current buffer has a
1146 buffer-local binding. For example, you could use `setq-default' to
1147 change the default setting of `paragraph-start' for most buffers; and
1148 this would work even when you are in a C or Lisp mode buffer that has a
1149 buffer-local value for this variable.
1151 The special forms `defvar' and `defconst' also set the default value
1152 (if they set the variable at all), rather than any local value.
1154 - Function: default-value SYMBOL
1155 This function returns SYMBOL's default value. This is the value
1156 that is seen in buffers that do not have their own values for this
1157 variable. If SYMBOL is not buffer-local, this is equivalent to
1158 `symbol-value' (*note Accessing Variables::.).
1160 - Function: default-boundp SYMBOL
1161 The function `default-boundp' tells you whether SYMBOL's default
1162 value is nonvoid. If `(default-boundp 'foo)' returns `nil', then
1163 `(default-value 'foo)' would get an error.
1165 `default-boundp' is to `default-value' as `boundp' is to
1168 - Special Form: setq-default SYMBOL VALUE
1169 This sets the default value of SYMBOL to VALUE. It does not
1170 evaluate SYMBOL, but does evaluate VALUE. The value of the
1171 `setq-default' form is VALUE.
1173 If a SYMBOL is not buffer-local for the current buffer, and is not
1174 marked automatically buffer-local, `setq-default' has the same
1175 effect as `setq'. If SYMBOL is buffer-local for the current
1176 buffer, then this changes the value that other buffers will see
1177 (as long as they don't have a buffer-local value), but not the
1178 value that the current buffer sees.
1181 (make-local-variable 'local)
1183 (setq local 'value-in-foo)
1185 (setq-default local 'new-default)
1189 (default-value 'local)
1192 ;; In (the new) buffer `bar':
1195 (default-value 'local)
1197 (setq local 'another-default)
1199 (default-value 'local)
1202 ;; Back in buffer `foo':
1205 (default-value 'local)
1208 - Function: set-default SYMBOL VALUE
1209 This function is like `setq-default', except that SYMBOL is
1212 (set-default (car '(a b c)) 23)