1 This is ../info/lispref.info, produced by makeinfo version 4.0 from
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: Handling Errors, Next: Error Symbols, Prev: Processing of Errors, Up: Errors
55 Writing Code to Handle Errors
56 .............................
58 The usual effect of signaling an error is to terminate the command
59 that is running and return immediately to the XEmacs editor command
60 loop. You can arrange to trap errors occurring in a part of your
61 program by establishing an error handler, with the special form
62 `condition-case'. A simple example looks like this:
65 (delete-file filename)
68 This deletes the file named FILENAME, catching any error and returning
69 `nil' if an error occurs.
71 The second argument of `condition-case' is called the "protected
72 form". (In the example above, the protected form is a call to
73 `delete-file'.) The error handlers go into effect when this form
74 begins execution and are deactivated when this form returns. They
75 remain in effect for all the intervening time. In particular, they are
76 in effect during the execution of functions called by this form, in
77 their subroutines, and so on. This is a good thing, since, strictly
78 speaking, errors can be signaled only by Lisp primitives (including
79 `signal' and `error') called by the protected form, not by the
80 protected form itself.
82 The arguments after the protected form are handlers. Each handler
83 lists one or more "condition names" (which are symbols) to specify
84 which errors it will handle. The error symbol specified when an error
85 is signaled also defines a list of condition names. A handler applies
86 to an error if they have any condition names in common. In the example
87 above, there is one handler, and it specifies one condition name,
88 `error', which covers all errors.
90 The search for an applicable handler checks all the established
91 handlers starting with the most recently established one. Thus, if two
92 nested `condition-case' forms offer to handle the same error, the inner
93 of the two will actually handle it.
95 When an error is handled, control returns to the handler. Before
96 this happens, XEmacs unbinds all variable bindings made by binding
97 constructs that are being exited and executes the cleanups of all
98 `unwind-protect' forms that are exited. Once control arrives at the
99 handler, the body of the handler is executed.
101 After execution of the handler body, execution continues by returning
102 from the `condition-case' form. Because the protected form is exited
103 completely before execution of the handler, the handler cannot resume
104 execution at the point of the error, nor can it examine variable
105 bindings that were made within the protected form. All it can do is
106 clean up and proceed.
108 `condition-case' is often used to trap errors that are predictable,
109 such as failure to open a file in a call to `insert-file-contents'. It
110 is also used to trap errors that are totally unpredictable, such as
111 when the program evaluates an expression read from the user.
113 Even when an error is handled, the debugger may still be called if
114 the variable `debug-on-signal' (*note Error Debugging::) is non-`nil'.
115 Note that this may yield unpredictable results with code that traps
116 expected errors as normal part of its operation. Do not set
117 `debug-on-signal' unless you know what you are doing.
119 Error signaling and handling have some resemblance to `throw' and
120 `catch', but they are entirely separate facilities. An error cannot be
121 caught by a `catch', and a `throw' cannot be handled by an error
122 handler (though using `throw' when there is no suitable `catch' signals
123 an error that can be handled).
125 - Special Form: condition-case var protected-form handlers...
126 This special form establishes the error handlers HANDLERS around
127 the execution of PROTECTED-FORM. If PROTECTED-FORM executes
128 without error, the value it returns becomes the value of the
129 `condition-case' form; in this case, the `condition-case' has no
130 effect. The `condition-case' form makes a difference when an
131 error occurs during PROTECTED-FORM.
133 Each of the HANDLERS is a list of the form `(CONDITIONS BODY...)'.
134 Here CONDITIONS is an error condition name to be handled, or a
135 list of condition names; BODY is one or more Lisp expressions to
136 be executed when this handler handles an error. Here are examples
141 (arith-error (message "Division by zero"))
143 ((arith-error file-error)
145 "Either division by zero or failure to open a file"))
147 Each error that occurs has an "error symbol" that describes what
148 kind of error it is. The `error-conditions' property of this
149 symbol is a list of condition names (*note Error Symbols::). Emacs
150 searches all the active `condition-case' forms for a handler that
151 specifies one or more of these condition names; the innermost
152 matching `condition-case' handles the error. Within this
153 `condition-case', the first applicable handler handles the error.
155 After executing the body of the handler, the `condition-case'
156 returns normally, using the value of the last form in the handler
157 body as the overall value.
159 The argument VAR is a variable. `condition-case' does not bind
160 this variable when executing the PROTECTED-FORM, only when it
161 handles an error. At that time, it binds VAR locally to a list of
162 the form `(ERROR-SYMBOL . DATA)', giving the particulars of the
163 error. The handler can refer to this list to decide what to do.
164 For example, if the error is for failure opening a file, the file
165 name is the second element of DATA--the third element of VAR.
167 If VAR is `nil', that means no variable is bound. Then the error
168 symbol and associated data are not available to the handler.
170 Here is an example of using `condition-case' to handle the error
171 that results from dividing by zero. The handler prints out a warning
172 message and returns a very large number.
174 (defun safe-divide (dividend divisor)
179 (arith-error ; Condition.
180 (princ (format "Arithmetic error: %s" err))
185 -| Arithmetic error: (arith-error)
188 The handler specifies condition name `arith-error' so that it will
189 handle only division-by-zero errors. Other kinds of errors will not be
190 handled, at least not by this `condition-case'. Thus,
193 error--> Wrong type argument: integer-or-marker-p, nil
195 Here is a `condition-case' that catches all kinds of errors,
196 including those signaled with `error':
204 ;; This is a call to the function `error'.
205 (error "Rats! The variable %s was %s, not 35" 'baz baz))
206 ;; This is the handler; it is not a form.
207 (error (princ (format "The error was: %s" err))
209 -| The error was: (error "Rats! The variable baz was 34, not 35")
213 File: lispref.info, Node: Error Symbols, Prev: Handling Errors, Up: Errors
215 Error Symbols and Condition Names
216 .................................
218 When you signal an error, you specify an "error symbol" to specify
219 the kind of error you have in mind. Each error has one and only one
220 error symbol to categorize it. This is the finest classification of
221 errors defined by the XEmacs Lisp language.
223 These narrow classifications are grouped into a hierarchy of wider
224 classes called "error conditions", identified by "condition names".
225 The narrowest such classes belong to the error symbols themselves: each
226 error symbol is also a condition name. There are also condition names
227 for more extensive classes, up to the condition name `error' which
228 takes in all kinds of errors. Thus, each error has one or more
229 condition names: `error', the error symbol if that is distinct from
230 `error', and perhaps some intermediate classifications.
232 In other words, each error condition "inherits" from another error
233 condition, with `error' sitting at the top of the inheritance hierarchy.
235 - Function: define-error error-symbol error-message &optional
237 This function defines a new error, denoted by ERROR-SYMBOL.
238 ERROR-MESSAGE is an informative message explaining the error, and
239 will be printed out when an unhandled error occurs. ERROR-SYMBOL
240 is a sub-error of INHERITS-FROM (which defaults to `error').
242 `define-error' internally works by putting on ERROR-SYMBOL an
243 `error-message' property whose value is ERROR-MESSAGE, and an
244 `error-conditions' property that is a list of ERROR-SYMBOL
245 followed by each of its super-errors, up to and including `error'.
246 You will sometimes see code that sets this up directly rather than
247 calling `define-error', but you should _not_ do this yourself,
248 unless you wish to maintain compatibility with FSF Emacs, which
249 does not provide `define-error'.
251 Here is how we define a new error symbol, `new-error', that belongs
252 to a range of errors called `my-own-errors':
254 (define-error 'my-own-errors "A whole range of errors" 'error)
255 (define-error 'new-error "A new error" 'my-own-errors)
257 `new-error' has three condition names: `new-error', the narrowest
258 classification; `my-own-errors', which we imagine is a wider
259 classification; and `error', which is the widest of all.
261 Note that it is not legal to try to define an error unless its
262 super-error is also defined. For instance, attempting to define
263 `new-error' before `my-own-errors' are defined will signal an error.
265 The error string should start with a capital letter but it should
266 not end with a period. This is for consistency with the rest of Emacs.
268 Naturally, XEmacs will never signal `new-error' on its own; only an
269 explicit call to `signal' (*note Signaling Errors::) in your code can
272 (signal 'new-error '(x y))
273 error--> A new error: x, y
275 This error can be handled through any of the three condition names.
276 This example handles `new-error' and any other errors in the class
283 The significant way that errors are classified is by their condition
284 names--the names used to match errors with handlers. An error symbol
285 serves only as a convenient way to specify the intended error message
286 and list of condition names. It would be cumbersome to give `signal' a
287 list of condition names rather than one error symbol.
289 By contrast, using only error symbols without condition names would
290 seriously decrease the power of `condition-case'. Condition names make
291 it possible to categorize errors at various levels of generality when
292 you write an error handler. Using error symbols alone would eliminate
293 all but the narrowest level of classification.
295 *Note Standard Errors::, for a list of all the standard error symbols
296 and their conditions.
299 File: lispref.info, Node: Cleanups, Prev: Errors, Up: Nonlocal Exits
301 Cleaning Up from Nonlocal Exits
302 -------------------------------
304 The `unwind-protect' construct is essential whenever you temporarily
305 put a data structure in an inconsistent state; it permits you to ensure
306 the data are consistent in the event of an error or throw.
308 - Special Form: unwind-protect body cleanup-forms...
309 `unwind-protect' executes the BODY with a guarantee that the
310 CLEANUP-FORMS will be evaluated if control leaves BODY, no matter
311 how that happens. The BODY may complete normally, or execute a
312 `throw' out of the `unwind-protect', or cause an error; in all
313 cases, the CLEANUP-FORMS will be evaluated.
315 If the BODY forms finish normally, `unwind-protect' returns the
316 value of the last BODY form, after it evaluates the CLEANUP-FORMS.
317 If the BODY forms do not finish, `unwind-protect' does not return
318 any value in the normal sense.
320 Only the BODY is actually protected by the `unwind-protect'. If
321 any of the CLEANUP-FORMS themselves exits nonlocally (e.g., via a
322 `throw' or an error), `unwind-protect' is _not_ guaranteed to
323 evaluate the rest of them. If the failure of one of the
324 CLEANUP-FORMS has the potential to cause trouble, then protect it
325 with another `unwind-protect' around that form.
327 The number of currently active `unwind-protect' forms counts,
328 together with the number of local variable bindings, against the
329 limit `max-specpdl-size' (*note Local Variables::).
331 For example, here we make an invisible buffer for temporary use, and
332 make sure to kill it before finishing:
335 (let ((buffer (get-buffer-create " *temp*")))
339 (kill-buffer buffer))))
341 You might think that we could just as well write `(kill-buffer
342 (current-buffer))' and dispense with the variable `buffer'. However,
343 the way shown above is safer, if BODY happens to get an error after
344 switching to a different buffer! (Alternatively, you could write
345 another `save-excursion' around the body, to ensure that the temporary
346 buffer becomes current in time to kill it.)
348 Here is an actual example taken from the file `ftp.el'. It creates
349 a process (*note Processes::) to try to establish a connection to a
350 remote machine. As the function `ftp-login' is highly susceptible to
351 numerous problems that the writer of the function cannot anticipate, it
352 is protected with a form that guarantees deletion of the process in the
353 event of failure. Otherwise, XEmacs might fill up with useless
359 (setq process (ftp-setup-buffer host file))
360 (if (setq win (ftp-login process host user password))
361 (message "Logged in")
362 (error "Ftp login failed")))
363 (or win (and process (delete-process process)))))
365 This example actually has a small bug: if the user types `C-g' to
366 quit, and the quit happens immediately after the function
367 `ftp-setup-buffer' returns but before the variable `process' is set,
368 the process will not be killed. There is no easy way to fix this bug,
369 but at least it is very unlikely.
371 Here is another example which uses `unwind-protect' to make sure to
372 kill a temporary buffer. In this example, the value returned by
373 `unwind-protect' is used.
375 (defun shell-command-string (cmd)
376 "Return the output of the shell command CMD, as a string."
378 (set-buffer (generate-new-buffer " OS*cmd"))
379 (shell-command cmd t)
382 (kill-buffer (current-buffer)))))
385 File: lispref.info, Node: Variables, Next: Functions, Prev: Control Structures, Up: Top
390 A "variable" is a name used in a program to stand for a value.
391 Nearly all programming languages have variables of some sort. In the
392 text of a Lisp program, variables are written using the syntax for
395 In Lisp, unlike most programming languages, programs are represented
396 primarily as Lisp objects and only secondarily as text. The Lisp
397 objects used for variables are symbols: the symbol name is the variable
398 name, and the variable's value is stored in the value cell of the
399 symbol. The use of a symbol as a variable is independent of its use as
400 a function name. *Note Symbol Components::.
402 The Lisp objects that constitute a Lisp program determine the textual
403 form of the program--it is simply the read syntax for those Lisp
404 objects. This is why, for example, a variable in a textual Lisp program
405 is written using the read syntax for the symbol that represents the
410 * Global Variables:: Variable values that exist permanently, everywhere.
411 * Constant Variables:: Certain "variables" have values that never change.
412 * Local Variables:: Variable values that exist only temporarily.
413 * Void Variables:: Symbols that lack values.
414 * Defining Variables:: A definition says a symbol is used as a variable.
415 * Accessing Variables:: Examining values of variables whose names
416 are known only at run time.
417 * Setting Variables:: Storing new values in variables.
418 * Variable Scoping:: How Lisp chooses among local and global values.
419 * Buffer-Local Variables:: Variable values in effect only in one buffer.
420 * Variable Aliases:: Making one variable point to another.
423 File: lispref.info, Node: Global Variables, Next: Constant Variables, Up: Variables
428 The simplest way to use a variable is "globally". This means that
429 the variable has just one value at a time, and this value is in effect
430 (at least for the moment) throughout the Lisp system. The value remains
431 in effect until you specify a new one. When a new value replaces the
432 old one, no trace of the old value remains in the variable.
434 You specify a value for a symbol with `setq'. For example,
438 gives the variable `x' the value `(a b)'. Note that `setq' does not
439 evaluate its first argument, the name of the variable, but it does
440 evaluate the second argument, the new value.
442 Once the variable has a value, you can refer to it by using the
443 symbol by itself as an expression. Thus,
447 assuming the `setq' form shown above has already been executed.
449 If you do another `setq', the new value replaces the old one:
459 File: lispref.info, Node: Constant Variables, Next: Local Variables, Prev: Global Variables, Up: Variables
461 Variables That Never Change
462 ===========================
464 In XEmacs Lisp, some symbols always evaluate to themselves: the two
465 special symbols `nil' and `t', as well as "keyword symbols", that is,
466 symbols whose name begins with the character ``:''. These symbols
467 cannot be rebound, nor can their value cells be changed. An attempt to
468 change the value of `nil' or `t' signals a `setting-constant' error.
473 error--> Attempt to set constant symbol: nil
476 File: lispref.info, Node: Local Variables, Next: Void Variables, Prev: Constant Variables, Up: Variables
481 Global variables have values that last until explicitly superseded
482 with new values. Sometimes it is useful to create variable values that
483 exist temporarily--only while within a certain part of the program.
484 These values are called "local", and the variables so used are called
487 For example, when a function is called, its argument variables
488 receive new local values that last until the function exits. The `let'
489 special form explicitly establishes new local values for specified
490 variables; these last until exit from the `let' form.
492 Establishing a local value saves away the previous value (or lack of
493 one) of the variable. When the life span of the local value is over,
494 the previous value is restored. In the mean time, we say that the
495 previous value is "shadowed" and "not visible". Both global and local
496 values may be shadowed (*note Scope::).
498 If you set a variable (such as with `setq') while it is local, this
499 replaces the local value; it does not alter the global value, or
500 previous local values that are shadowed. To model this behavior, we
501 speak of a "local binding" of the variable as well as a local value.
503 The local binding is a conceptual place that holds a local value.
504 Entry to a function, or a special form such as `let', creates the local
505 binding; exit from the function or from the `let' removes the local
506 binding. As long as the local binding lasts, the variable's value is
507 stored within it. Use of `setq' or `set' while there is a local
508 binding stores a different value into the local binding; it does not
509 create a new binding.
511 We also speak of the "global binding", which is where (conceptually)
512 the global value is kept.
514 A variable can have more than one local binding at a time (for
515 example, if there are nested `let' forms that bind it). In such a
516 case, the most recently created local binding that still exists is the
517 "current binding" of the variable. (This is called "dynamic scoping";
518 see *Note Variable Scoping::.) If there are no local bindings, the
519 variable's global binding is its current binding. We also call the
520 current binding the "most-local existing binding", for emphasis.
521 Ordinary evaluation of a symbol always returns the value of its current
524 The special forms `let' and `let*' exist to create local bindings.
526 - Special Form: let (bindings...) forms...
527 This special form binds variables according to BINDINGS and then
528 evaluates all of the FORMS in textual order. The `let'-form
529 returns the value of the last form in FORMS.
531 Each of the BINDINGS is either (i) a symbol, in which case that
532 symbol is bound to `nil'; or (ii) a list of the form `(SYMBOL
533 VALUE-FORM)', in which case SYMBOL is bound to the result of
534 evaluating VALUE-FORM. If VALUE-FORM is omitted, `nil' is used.
536 All of the VALUE-FORMs in BINDINGS are evaluated in the order they
537 appear and _before_ any of the symbols are bound. Here is an
538 example of this: `Z' is bound to the old value of `Y', which is 2,
539 not the new value, 1.
548 - Special Form: let* (bindings...) forms...
549 This special form is like `let', but it binds each variable right
550 after computing its local value, before computing the local value
551 for the next variable. Therefore, an expression in BINDINGS can
552 reasonably refer to the preceding symbols bound in this `let*'
553 form. Compare the following example with the example above for
559 (Z Y)) ; Use the just-established value of `Y'.
563 Here is a complete list of the other facilities that create local
566 * Function calls (*note Functions::).
568 * Macro calls (*note Macros::).
570 * `condition-case' (*note Errors::).
572 Variables can also have buffer-local bindings (*note Buffer-Local
573 Variables::). These kinds of bindings work somewhat like ordinary local
574 bindings, but they are localized depending on "where" you are in Emacs,
575 rather than localized in time.
577 - Variable: max-specpdl-size
578 This variable defines the limit on the total number of local
579 variable bindings and `unwind-protect' cleanups (*note Nonlocal
580 Exits::) that are allowed before signaling an error (with data
581 `"Variable binding depth exceeds max-specpdl-size"').
583 This limit, with the associated error when it is exceeded, is one
584 way that Lisp avoids infinite recursion on an ill-defined function.
586 The default value is 600.
588 `max-lisp-eval-depth' provides another limit on depth of nesting.
592 File: lispref.info, Node: Void Variables, Next: Defining Variables, Prev: Local Variables, Up: Variables
594 When a Variable is "Void"
595 =========================
597 If you have never given a symbol any value as a global variable, we
598 say that that symbol's global value is "void". In other words, the
599 symbol's value cell does not have any Lisp object in it. If you try to
600 evaluate the symbol, you get a `void-variable' error rather than a
603 Note that a value of `nil' is not the same as void. The symbol
604 `nil' is a Lisp object and can be the value of a variable just as any
605 other object can be; but it is _a value_. A void variable does not
608 After you have given a variable a value, you can make it void once
609 more using `makunbound'.
611 - Function: makunbound symbol
612 This function makes the current binding of SYMBOL void.
613 Subsequent attempts to use this symbol's value as a variable will
614 signal the error `void-variable', unless or until you set it again.
616 `makunbound' returns SYMBOL.
618 (makunbound 'x) ; Make the global value
622 error--> Symbol's value as variable is void: x
624 If SYMBOL is locally bound, `makunbound' affects the most local
625 existing binding. This is the only way a symbol can have a void
626 local binding, since all the constructs that create local bindings
627 create them with values. In this case, the voidness lasts at most
628 as long as the binding does; when the binding is removed due to
629 exit from the construct that made it, the previous or global
630 binding is reexposed as usual, and the variable is no longer void
631 unless the newly reexposed binding was void all along.
633 (setq x 1) ; Put a value in the global binding.
635 (let ((x 2)) ; Locally bind it.
636 (makunbound 'x) ; Void the local binding.
638 error--> Symbol's value as variable is void: x
639 x ; The global binding is unchanged.
642 (let ((x 2)) ; Locally bind it.
643 (let ((x 3)) ; And again.
644 (makunbound 'x) ; Void the innermost-local binding.
645 x)) ; And refer: it's void.
646 error--> Symbol's value as variable is void: x
650 (makunbound 'x)) ; Void inner binding, then remove it.
651 x) ; Now outer `let' binding is visible.
654 A variable that has been made void with `makunbound' is
655 indistinguishable from one that has never received a value and has
658 You can use the function `boundp' to test whether a variable is
661 - Function: boundp variable
662 `boundp' returns `t' if VARIABLE (a symbol) is not void; more
663 precisely, if its current binding is not void. It returns `nil'
666 (boundp 'abracadabra) ; Starts out void.
668 (let ((abracadabra 5)) ; Locally bind it.
669 (boundp 'abracadabra))
671 (boundp 'abracadabra) ; Still globally void.
673 (setq abracadabra 5) ; Make it globally nonvoid.
675 (boundp 'abracadabra)
679 File: lispref.info, Node: Defining Variables, Next: Accessing Variables, Prev: Void Variables, Up: Variables
681 Defining Global Variables
682 =========================
684 You may announce your intention to use a symbol as a global variable
685 with a "variable definition": a special form, either `defconst' or
688 In XEmacs Lisp, definitions serve three purposes. First, they inform
689 people who read the code that certain symbols are _intended_ to be used
690 a certain way (as variables). Second, they inform the Lisp system of
691 these things, supplying a value and documentation. Third, they provide
692 information to utilities such as `etags' and `make-docfile', which
693 create data bases of the functions and variables in a program.
695 The difference between `defconst' and `defvar' is primarily a matter
696 of intent, serving to inform human readers of whether programs will
697 change the variable. XEmacs Lisp does not restrict the ways in which a
698 variable can be used based on `defconst' or `defvar' declarations.
699 However, it does make a difference for initialization: `defconst'
700 unconditionally initializes the variable, while `defvar' initializes it
703 One would expect user option variables to be defined with
704 `defconst', since programs do not change them. Unfortunately, this has
705 bad results if the definition is in a library that is not preloaded:
706 `defconst' would override any prior value when the library is loaded.
707 Users would like to be able to set user options in their init files,
708 and override the default values given in the definitions. For this
709 reason, user options must be defined with `defvar'.
711 - Special Form: defvar symbol [value [doc-string]]
712 This special form defines SYMBOL as a value and initializes it.
713 The definition informs a person reading your code that SYMBOL is
714 used as a variable that programs are likely to set or change. It
715 is also used for all user option variables except in the preloaded
716 parts of XEmacs. Note that SYMBOL is not evaluated; the symbol to
717 be defined must appear explicitly in the `defvar'.
719 If SYMBOL already has a value (i.e., it is not void), VALUE is not
720 even evaluated, and SYMBOL's value remains unchanged. If SYMBOL
721 is void and VALUE is specified, `defvar' evaluates it and sets
722 SYMBOL to the result. (If VALUE is omitted, the value of SYMBOL
723 is not changed in any case.)
725 When you evaluate a top-level `defvar' form with `C-M-x' in Emacs
726 Lisp mode (`eval-defun'), a special feature of `eval-defun'
727 evaluates it as a `defconst'. The purpose of this is to make sure
728 the variable's value is reinitialized, when you ask for it
731 If SYMBOL has a buffer-local binding in the current buffer,
732 `defvar' sets the default value, not the local value. *Note
733 Buffer-Local Variables::.
735 If the DOC-STRING argument appears, it specifies the documentation
736 for the variable. (This opportunity to specify documentation is
737 one of the main benefits of defining the variable.) The
738 documentation is stored in the symbol's `variable-documentation'
739 property. The XEmacs help functions (*note Documentation::) look
742 If the first character of DOC-STRING is `*', it means that this
743 variable is considered a user option. This lets users set the
744 variable conveniently using the commands `set-variable' and
747 For example, this form defines `foo' but does not set its value:
752 The following example sets the value of `bar' to `23', and gives
753 it a documentation string:
756 "The normal weight of a bar.")
759 The following form changes the documentation string for `bar',
760 making it a user option, but does not change the value, since `bar'
761 already has a value. (The addition `(1+ 23)' is not even
765 "*The normal weight of a bar.")
770 Here is an equivalent expression for the `defvar' special form:
772 (defvar SYMBOL VALUE DOC-STRING)
775 (if (not (boundp 'SYMBOL))
777 (put 'SYMBOL 'variable-documentation 'DOC-STRING)
780 The `defvar' form returns SYMBOL, but it is normally used at top
781 level in a file where its value does not matter.
783 - Special Form: defconst symbol [value [doc-string]]
784 This special form defines SYMBOL as a value and initializes it.
785 It informs a person reading your code that SYMBOL has a global
786 value, established here, that will not normally be changed or
787 locally bound by the execution of the program. The user, however,
788 may be welcome to change it. Note that SYMBOL is not evaluated;
789 the symbol to be defined must appear explicitly in the `defconst'.
791 `defconst' always evaluates VALUE and sets the global value of
792 SYMBOL to the result, provided VALUE is given. If SYMBOL has a
793 buffer-local binding in the current buffer, `defconst' sets the
794 default value, not the local value.
796 *Please note:* Don't use `defconst' for user option variables in
797 libraries that are not standardly preloaded. The user should be
798 able to specify a value for such a variable in the `.emacs' file,
799 so that it will be in effect if and when the library is loaded
802 Here, `pi' is a constant that presumably ought not to be changed
803 by anyone (attempts by the Indiana State Legislature
804 notwithstanding). As the second form illustrates, however, this
807 (defconst pi 3.1415 "Pi to five places.")
814 - Function: user-variable-p variable
815 This function returns `t' if VARIABLE is a user option--a variable
816 intended to be set by the user for customization--and `nil'
817 otherwise. (Variables other than user options exist for the
818 internal purposes of Lisp programs, and users need not know about
821 User option variables are distinguished from other variables by the
822 first character of the `variable-documentation' property. If the
823 property exists and is a string, and its first character is `*',
824 then the variable is a user option.
826 If a user option variable has a `variable-interactive' property, the
827 `set-variable' command uses that value to control reading the new value
828 for the variable. The property's value is used as if it were the
829 argument to `interactive'.
831 *Warning:* If the `defconst' and `defvar' special forms are used
832 while the variable has a local binding, they set the local binding's
833 value; the global binding is not changed. This is not what we really
834 want. To prevent it, use these special forms at top level in a file,
835 where normally no local binding is in effect, and make sure to load the
836 file before making a local binding for the variable.
839 File: lispref.info, Node: Accessing Variables, Next: Setting Variables, Prev: Defining Variables, Up: Variables
841 Accessing Variable Values
842 =========================
844 The usual way to reference a variable is to write the symbol which
845 names it (*note Symbol Forms::). This requires you to specify the
846 variable name when you write the program. Usually that is exactly what
847 you want to do. Occasionally you need to choose at run time which
848 variable to reference; then you can use `symbol-value'.
850 - Function: symbol-value symbol
851 This function returns the value of SYMBOL. This is the value in
852 the innermost local binding of the symbol, or its global value if
853 it has no local bindings.
860 ;; Here the symbol `abracadabra'
861 ;; is the symbol whose value is examined.
862 (let ((abracadabra 'foo))
863 (symbol-value 'abracadabra))
866 ;; Here the value of `abracadabra',
868 ;; is the symbol whose value is examined.
869 (let ((abracadabra 'foo))
870 (symbol-value abracadabra))
873 (symbol-value 'abracadabra)
876 A `void-variable' error is signaled if SYMBOL has neither a local
877 binding nor a global value.
880 File: lispref.info, Node: Setting Variables, Next: Variable Scoping, Prev: Accessing Variables, Up: Variables
882 How to Alter a Variable Value
883 =============================
885 The usual way to change the value of a variable is with the special
886 form `setq'. When you need to compute the choice of variable at run
887 time, use the function `set'.
889 - Special Form: setq [symbol form]...
890 This special form is the most common method of changing a
891 variable's value. Each SYMBOL is given a new value, which is the
892 result of evaluating the corresponding FORM. The most-local
893 existing binding of the symbol is changed.
895 `setq' does not evaluate SYMBOL; it sets the symbol that you
896 write. We say that this argument is "automatically quoted". The
897 `q' in `setq' stands for "quoted."
899 The value of the `setq' form is the value of the last FORM.
903 x ; `x' now has a global value.
906 (setq x 6) ; The local binding of `x' is set.
909 x ; The global value is unchanged.
912 Note that the first FORM is evaluated, then the first SYMBOL is
913 set, then the second FORM is evaluated, then the second SYMBOL is
916 (setq x 10 ; Notice that `x' is set before
917 y (1+ x)) ; the value of `y' is computed.
920 - Function: set symbol value
921 This function sets SYMBOL's value to VALUE, then returns VALUE.
922 Since `set' is a function, the expression written for SYMBOL is
923 evaluated to obtain the symbol to set.
925 The most-local existing binding of the variable is the binding
926 that is set; shadowed bindings are not affected.
929 error--> Symbol's value as variable is void: one
934 (set two 2) ; `two' evaluates to symbol `one'.
936 one ; So it is `one' that was set.
938 (let ((one 1)) ; This binding of `one' is set,
939 (set 'one 3) ; not the global value.
945 If SYMBOL is not actually a symbol, a `wrong-type-argument' error
949 error--> Wrong type argument: symbolp, (x y)
951 Logically speaking, `set' is a more fundamental primitive than
952 `setq'. Any use of `setq' can be trivially rewritten to use
953 `set'; `setq' could even be defined as a macro, given the
954 availability of `set'. However, `set' itself is rarely used;
955 beginners hardly need to know about it. It is useful only for
956 choosing at run time which variable to set. For example, the
957 command `set-variable', which reads a variable name from the user
958 and then sets the variable, needs to use `set'.
960 Common Lisp note: In Common Lisp, `set' always changes the
961 symbol's special value, ignoring any lexical bindings. In
962 XEmacs Lisp, all variables and all bindings are (in effect)
963 special, so `set' always affects the most local existing
966 One other function for setting a variable is designed to add an
967 element to a list if it is not already present in the list.
969 - Function: add-to-list symbol element
970 This function sets the variable SYMBOL by consing ELEMENT onto the
971 old value, if ELEMENT is not already a member of that value. It
972 returns the resulting list, whether updated or not. The value of
973 SYMBOL had better be a list already before the call.
975 The argument SYMBOL is not implicitly quoted; `add-to-list' is an
976 ordinary function, like `set' and unlike `setq'. Quote the
977 argument yourself if that is what you want.
979 Here's a scenario showing how to use `add-to-list':
984 (add-to-list 'foo 'c) ;; Add `c'.
987 (add-to-list 'foo 'b) ;; No effect.
990 foo ;; `foo' was changed.
993 An equivalent expression for `(add-to-list 'VAR VALUE)' is this:
995 (or (member VALUE VAR)
996 (setq VAR (cons VALUE VAR)))
999 File: lispref.info, Node: Variable Scoping, Next: Buffer-Local Variables, Prev: Setting Variables, Up: Variables
1001 Scoping Rules for Variable Bindings
1002 ===================================
1004 A given symbol `foo' may have several local variable bindings,
1005 established at different places in the Lisp program, as well as a global
1006 binding. The most recently established binding takes precedence over
1009 Local bindings in XEmacs Lisp have "indefinite scope" and "dynamic
1010 extent". "Scope" refers to _where_ textually in the source code the
1011 binding can be accessed. Indefinite scope means that any part of the
1012 program can potentially access the variable binding. "Extent" refers
1013 to _when_, as the program is executing, the binding exists. Dynamic
1014 extent means that the binding lasts as long as the activation of the
1015 construct that established it.
1017 The combination of dynamic extent and indefinite scope is called
1018 "dynamic scoping". By contrast, most programming languages use
1019 "lexical scoping", in which references to a local variable must be
1020 located textually within the function or block that binds the variable.
1022 Common Lisp note: Variables declared "special" in Common Lisp are
1023 dynamically scoped, like variables in XEmacs Lisp.
1027 * Scope:: Scope means where in the program a value is visible.
1028 Comparison with other languages.
1029 * Extent:: Extent means how long in time a value exists.
1030 * Impl of Scope:: Two ways to implement dynamic scoping.
1031 * Using Scoping:: How to use dynamic scoping carefully and avoid problems.
1034 File: lispref.info, Node: Scope, Next: Extent, Up: Variable Scoping
1039 XEmacs Lisp uses "indefinite scope" for local variable bindings.
1040 This means that any function anywhere in the program text might access a
1041 given binding of a variable. Consider the following function
1044 (defun binder (x) ; `x' is bound in `binder'.
1045 (foo 5)) ; `foo' is some other function.
1047 (defun user () ; `x' is used in `user'.
1050 In a lexically scoped language, the binding of `x' in `binder' would
1051 never be accessible in `user', because `user' is not textually
1052 contained within the function `binder'. However, in dynamically scoped
1053 XEmacs Lisp, `user' may or may not refer to the binding of `x'
1054 established in `binder', depending on circumstances:
1056 * If we call `user' directly without calling `binder' at all, then
1057 whatever binding of `x' is found, it cannot come from `binder'.
1059 * If we define `foo' as follows and call `binder', then the binding
1060 made in `binder' will be seen in `user':
1065 * If we define `foo' as follows and call `binder', then the binding
1066 made in `binder' _will not_ be seen in `user':
1071 Here, when `foo' is called by `binder', it binds `x'. (The
1072 binding in `foo' is said to "shadow" the one made in `binder'.)
1073 Therefore, `user' will access the `x' bound by `foo' instead of
1074 the one bound by `binder'.
1077 File: lispref.info, Node: Extent, Next: Impl of Scope, Prev: Scope, Up: Variable Scoping
1082 "Extent" refers to the time during program execution that a variable
1083 name is valid. In XEmacs Lisp, a variable is valid only while the form
1084 that bound it is executing. This is called "dynamic extent". "Local"
1085 or "automatic" variables in most languages, including C and Pascal,
1086 have dynamic extent.
1088 One alternative to dynamic extent is "indefinite extent". This
1089 means that a variable binding can live on past the exit from the form
1090 that made the binding. Common Lisp and Scheme, for example, support
1091 this, but XEmacs Lisp does not.
1093 To illustrate this, the function below, `make-add', returns a
1094 function that purports to add N to its own argument M. This would work
1095 in Common Lisp, but it does not work as intended in XEmacs Lisp,
1096 because after the call to `make-add' exits, the variable `n' is no
1097 longer bound to the actual argument 2.
1100 (function (lambda (m) (+ n m)))) ; Return a function.
1102 (fset 'add2 (make-add 2)) ; Define function `add2'
1103 ; with `(make-add 2)'.
1104 => (lambda (m) (+ n m))
1105 (add2 4) ; Try to add 2 to 4.
1106 error--> Symbol's value as variable is void: n
1108 Some Lisp dialects have "closures", objects that are like functions
1109 but record additional variable bindings. XEmacs Lisp does not have
1113 File: lispref.info, Node: Impl of Scope, Next: Using Scoping, Prev: Extent, Up: Variable Scoping
1115 Implementation of Dynamic Scoping
1116 ---------------------------------
1118 A simple sample implementation (which is not how XEmacs Lisp actually
1119 works) may help you understand dynamic binding. This technique is
1120 called "deep binding" and was used in early Lisp systems.
1122 Suppose there is a stack of bindings: variable-value pairs. At entry
1123 to a function or to a `let' form, we can push bindings on the stack for
1124 the arguments or local variables created there. We can pop those
1125 bindings from the stack at exit from the binding construct.
1127 We can find the value of a variable by searching the stack from top
1128 to bottom for a binding for that variable; the value from that binding
1129 is the value of the variable. To set the variable, we search for the
1130 current binding, then store the new value into that binding.
1132 As you can see, a function's bindings remain in effect as long as it
1133 continues execution, even during its calls to other functions. That is
1134 why we say the extent of the binding is dynamic. And any other function
1135 can refer to the bindings, if it uses the same variables while the
1136 bindings are in effect. That is why we say the scope is indefinite.
1138 The actual implementation of variable scoping in XEmacs Lisp uses a
1139 technique called "shallow binding". Each variable has a standard place
1140 in which its current value is always found--the value cell of the
1143 In shallow binding, setting the variable works by storing a value in
1144 the value cell. Creating a new binding works by pushing the old value
1145 (belonging to a previous binding) on a stack, and storing the local
1146 value in the value cell. Eliminating a binding works by popping the
1147 old value off the stack, into the value cell.
1149 We use shallow binding because it has the same results as deep
1150 binding, but runs faster, since there is never a need to search for a
1154 File: lispref.info, Node: Using Scoping, Prev: Impl of Scope, Up: Variable Scoping
1156 Proper Use of Dynamic Scoping
1157 -----------------------------
1159 Binding a variable in one function and using it in another is a
1160 powerful technique, but if used without restraint, it can make programs
1161 hard to understand. There are two clean ways to use this technique:
1163 * Use or bind the variable only in a few related functions, written
1164 close together in one file. Such a variable is used for
1165 communication within one program.
1167 You should write comments to inform other programmers that they
1168 can see all uses of the variable before them, and to advise them
1169 not to add uses elsewhere.
1171 * Give the variable a well-defined, documented meaning, and make all
1172 appropriate functions refer to it (but not bind it or set it)
1173 wherever that meaning is relevant. For example, the variable
1174 `case-fold-search' is defined as "non-`nil' means ignore case when
1175 searching"; various search and replace functions refer to it
1176 directly or through their subroutines, but do not bind or set it.
1178 Then you can bind the variable in other programs, knowing reliably
1179 what the effect will be.
1181 In either case, you should define the variable with `defvar'. This
1182 helps other people understand your program by telling them to look for
1183 inter-function usage. It also avoids a warning from the byte compiler.
1184 Choose the variable's name to avoid name conflicts--don't use short
1188 File: lispref.info, Node: Buffer-Local Variables, Next: Variable Aliases, Prev: Variable Scoping, Up: Variables
1190 Buffer-Local Variables
1191 ======================
1193 Global and local variable bindings are found in most programming
1194 languages in one form or another. XEmacs also supports another, unusual
1195 kind of variable binding: "buffer-local" bindings, which apply only to
1196 one buffer. XEmacs Lisp is meant for programming editing commands, and
1197 having different values for a variable in different buffers is an
1198 important customization method.
1202 * Intro to Buffer-Local:: Introduction and concepts.
1203 * Creating Buffer-Local:: Creating and destroying buffer-local bindings.
1204 * Default Value:: The default value is seen in buffers
1205 that don't have their own local values.