XEmacs 21.2.22 "Mercedes".
[chise/xemacs-chise.git.1] / info / lispref.info-9
1 This is ../info/lispref.info, produced by makeinfo version 4.0 from
2 lispref/lispref.texi.
3
4 INFO-DIR-SECTION XEmacs Editor
5 START-INFO-DIR-ENTRY
6 * Lispref: (lispref).           XEmacs Lisp Reference Manual.
7 END-INFO-DIR-ENTRY
8
9    Edition History:
10
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
20
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.
24
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.
28
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.
33
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.
38
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.
45
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.
51
52 \1f
53 File: lispref.info,  Node: Cleanups,  Prev: Errors,  Up: Nonlocal Exits
54
55 Cleaning Up from Nonlocal Exits
56 -------------------------------
57
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.
61
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.
68
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.
73
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.
80
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::).
84
85    For example, here we make an invisible buffer for temporary use, and
86 make sure to kill it before finishing:
87
88      (save-excursion
89        (let ((buffer (get-buffer-create " *temp*")))
90          (set-buffer buffer)
91          (unwind-protect
92              BODY
93            (kill-buffer buffer))))
94
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.)
101
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
108 subprocesses.
109
110      (let ((win nil))
111        (unwind-protect
112            (progn
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)))))
118
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.
124
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.
128
129      (defun shell-command-string (cmd)
130        "Return the output of the shell command CMD, as a string."
131        (save-excursion
132          (set-buffer (generate-new-buffer " OS*cmd"))
133          (shell-command cmd t)
134          (unwind-protect
135              (buffer-string)
136            (kill-buffer (current-buffer)))))
137
138 \1f
139 File: lispref.info,  Node: Variables,  Next: Functions,  Prev: Control Structures,  Up: Top
140
141 Variables
142 *********
143
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
147 symbols.
148
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::.
155
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
160 variable.
161
162 * Menu:
163
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.
175
176 \1f
177 File: lispref.info,  Node: Global Variables,  Next: Constant Variables,  Up: Variables
178
179 Global Variables
180 ================
181
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.
187
188    You specify a value for a symbol with `setq'.  For example,
189
190      (setq x '(a b))
191
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.
195
196    Once the variable has a value, you can refer to it by using the
197 symbol by itself as an expression.  Thus,
198
199      x => (a b)
200
201 assuming the `setq' form shown above has already been executed.
202
203    If you do another `setq', the new value replaces the old one:
204
205      x
206           => (a b)
207      (setq x 4)
208           => 4
209      x
210           => 4
211
212 \1f
213 File: lispref.info,  Node: Constant Variables,  Next: Local Variables,  Prev: Global Variables,  Up: Variables
214
215 Variables That Never Change
216 ===========================
217
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.
223
224      nil == 'nil
225           => nil
226      (setq nil 500)
227      error--> Attempt to set constant symbol: nil
228
229 \1f
230 File: lispref.info,  Node: Local Variables,  Next: Void Variables,  Prev: Constant Variables,  Up: Variables
231
232 Local Variables
233 ===============
234
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
239 "local variables".
240
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.
245
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::).
251
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.
256
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.
264
265    We also speak of the "global binding", which is where (conceptually)
266 the global value is kept.
267
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
276 binding.
277
278    The special forms `let' and `let*' exist to create local bindings.
279
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.
284
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.
289
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.
294
295           (setq Y 2)
296                => 2
297           (let ((Y 1)
298                 (Z Y))
299             (list Y Z))
300                => (1 2)
301
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
308      `let'.
309
310           (setq Y 2)
311                => 2
312           (let* ((Y 1)
313                  (Z Y))    ; Use the just-established value of `Y'.
314             (list Y Z))
315                => (1 1)
316
317    Here is a complete list of the other facilities that create local
318 bindings:
319
320    * Function calls (*note Functions::).
321
322    * Macro calls (*note Macros::).
323
324    * `condition-case' (*note Errors::).
325
326    Variables can also have buffer-local bindings (*note Buffer-Local
327 Variables::).  These kinds of bindings work somewhat like ordinary local
328 bindings, but they are localized depending on "where" you are in Emacs,
329 rather than localized in time.
330
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"').
336
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.
339
340      The default value is 600.
341
342      `max-lisp-eval-depth' provides another limit on depth of nesting.
343      *Note Eval::.
344
345 \1f
346 File: lispref.info,  Node: Void Variables,  Next: Defining Variables,  Prev: Local Variables,  Up: Variables
347
348 When a Variable is "Void"
349 =========================
350
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
355 value.
356
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
360 have any value.
361
362    After you have given a variable a value, you can make it void once
363 more using `makunbound'.
364
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.
369
370      `makunbound' returns SYMBOL.
371
372           (makunbound 'x)      ; Make the global value
373                                ;   of `x' void.
374                => x
375           x
376           error--> Symbol's value as variable is void: x
377
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.
386
387           (setq x 1)               ; Put a value in the global binding.
388                => 1
389           (let ((x 2))             ; Locally bind it.
390             (makunbound 'x)        ; Void the local binding.
391             x)
392           error--> Symbol's value as variable is void: x
393           x                        ; The global binding is unchanged.
394                => 1
395           
396           (let ((x 2))             ; Locally bind it.
397             (let ((x 3))           ; And again.
398               (makunbound 'x)      ; Void the innermost-local binding.
399               x))                  ; And refer: it's void.
400           error--> Symbol's value as variable is void: x
401           
402           (let ((x 2))
403             (let ((x 3))
404               (makunbound 'x))     ; Void inner binding, then remove it.
405             x)                     ; Now outer `let' binding is visible.
406                => 2
407
408    A variable that has been made void with `makunbound' is
409 indistinguishable from one that has never received a value and has
410 always been void.
411
412    You can use the function `boundp' to test whether a variable is
413 currently void.
414
415  - Function: boundp variable
416      `boundp' returns `t' if VARIABLE (a symbol) is not void; more
417      precisely, if its current binding is not void.  It returns `nil'
418      otherwise.
419
420           (boundp 'abracadabra)          ; Starts out void.
421                => nil
422           (let ((abracadabra 5))         ; Locally bind it.
423             (boundp 'abracadabra))
424                => t
425           (boundp 'abracadabra)          ; Still globally void.
426                => nil
427           (setq abracadabra 5)           ; Make it globally nonvoid.
428                => 5
429           (boundp 'abracadabra)
430                => t
431
432 \1f
433 File: lispref.info,  Node: Defining Variables,  Next: Accessing Variables,  Prev: Void Variables,  Up: Variables
434
435 Defining Global Variables
436 =========================
437
438    You may announce your intention to use a symbol as a global variable
439 with a "variable definition": a special form, either `defconst' or
440 `defvar'.
441
442    In XEmacs Lisp, definitions serve three purposes.  First, they inform
443 people who read the code that certain symbols are _intended_ to be used
444 a certain way (as variables).  Second, they inform the Lisp system of
445 these things, supplying a value and documentation.  Third, they provide
446 information to utilities such as `etags' and `make-docfile', which
447 create data bases of the functions and variables in a program.
448
449    The difference between `defconst' and `defvar' is primarily a matter
450 of intent, serving to inform human readers of whether programs will
451 change the variable.  XEmacs Lisp does not restrict the ways in which a
452 variable can be used based on `defconst' or `defvar' declarations.
453 However, it does make a difference for initialization: `defconst'
454 unconditionally initializes the variable, while `defvar' initializes it
455 only if it is void.
456
457    One would expect user option variables to be defined with
458 `defconst', since programs do not change them.  Unfortunately, this has
459 bad results if the definition is in a library that is not preloaded:
460 `defconst' would override any prior value when the library is loaded.
461 Users would like to be able to set user options in their init files,
462 and override the default values given in the definitions.  For this
463 reason, user options must be defined with `defvar'.
464
465  - Special Form: defvar symbol [value [doc-string]]
466      This special form defines SYMBOL as a value and initializes it.
467      The definition informs a person reading your code that SYMBOL is
468      used as a variable that programs are likely to set or change.  It
469      is also used for all user option variables except in the preloaded
470      parts of XEmacs.  Note that SYMBOL is not evaluated; the symbol to
471      be defined must appear explicitly in the `defvar'.
472
473      If SYMBOL already has a value (i.e., it is not void), VALUE is not
474      even evaluated, and SYMBOL's value remains unchanged.  If SYMBOL
475      is void and VALUE is specified, `defvar' evaluates it and sets
476      SYMBOL to the result.  (If VALUE is omitted, the value of SYMBOL
477      is not changed in any case.)
478
479      When you evaluate a top-level `defvar' form with `C-M-x' in Emacs
480      Lisp mode (`eval-defun'), a special feature of `eval-defun'
481      evaluates it as a `defconst'.  The purpose of this is to make sure
482      the variable's value is reinitialized, when you ask for it
483      specifically.
484
485      If SYMBOL has a buffer-local binding in the current buffer,
486      `defvar' sets the default value, not the local value.  *Note
487      Buffer-Local Variables::.
488
489      If the DOC-STRING argument appears, it specifies the documentation
490      for the variable.  (This opportunity to specify documentation is
491      one of the main benefits of defining the variable.)  The
492      documentation is stored in the symbol's `variable-documentation'
493      property.  The XEmacs help functions (*note Documentation::) look
494      for this property.
495
496      If the first character of DOC-STRING is `*', it means that this
497      variable is considered a user option.  This lets users set the
498      variable conveniently using the commands `set-variable' and
499      `edit-options'.
500
501      For example, this form defines `foo' but does not set its value:
502
503           (defvar foo)
504                => foo
505
506      The following example sets the value of `bar' to `23', and gives
507      it a documentation string:
508
509           (defvar bar 23
510             "The normal weight of a bar.")
511                => bar
512
513      The following form changes the documentation string for `bar',
514      making it a user option, but does not change the value, since `bar'
515      already has a value.  (The addition `(1+ 23)' is not even
516      performed.)
517
518           (defvar bar (1+ 23)
519             "*The normal weight of a bar.")
520                => bar
521           bar
522                => 23
523
524      Here is an equivalent expression for the `defvar' special form:
525
526           (defvar SYMBOL VALUE DOC-STRING)
527           ==
528           (progn
529             (if (not (boundp 'SYMBOL))
530                 (setq SYMBOL VALUE))
531             (put 'SYMBOL 'variable-documentation 'DOC-STRING)
532             'SYMBOL)
533
534      The `defvar' form returns SYMBOL, but it is normally used at top
535      level in a file where its value does not matter.
536
537  - Special Form: defconst symbol [value [doc-string]]
538      This special form defines SYMBOL as a value and initializes it.
539      It informs a person reading your code that SYMBOL has a global
540      value, established here, that will not normally be changed or
541      locally bound by the execution of the program.  The user, however,
542      may be welcome to change it.  Note that SYMBOL is not evaluated;
543      the symbol to be defined must appear explicitly in the `defconst'.
544
545      `defconst' always evaluates VALUE and sets the global value of
546      SYMBOL to the result, provided VALUE is given.  If SYMBOL has a
547      buffer-local binding in the current buffer, `defconst' sets the
548      default value, not the local value.
549
550      *Please note:* Don't use `defconst' for user option variables in
551      libraries that are not standardly preloaded.  The user should be
552      able to specify a value for such a variable in the `.emacs' file,
553      so that it will be in effect if and when the library is loaded
554      later.
555
556      Here, `pi' is a constant that presumably ought not to be changed
557      by anyone (attempts by the Indiana State Legislature
558      notwithstanding).  As the second form illustrates, however, this
559      is only advisory.
560
561           (defconst pi 3.1415 "Pi to five places.")
562                => pi
563           (setq pi 3)
564                => pi
565           pi
566                => 3
567
568  - Function: user-variable-p variable
569      This function returns `t' if VARIABLE is a user option--a variable
570      intended to be set by the user for customization--and `nil'
571      otherwise.  (Variables other than user options exist for the
572      internal purposes of Lisp programs, and users need not know about
573      them.)
574
575      User option variables are distinguished from other variables by the
576      first character of the `variable-documentation' property.  If the
577      property exists and is a string, and its first character is `*',
578      then the variable is a user option.
579
580    If a user option variable has a `variable-interactive' property, the
581 `set-variable' command uses that value to control reading the new value
582 for the variable.  The property's value is used as if it were the
583 argument to `interactive'.
584
585    *Warning:* If the `defconst' and `defvar' special forms are used
586 while the variable has a local binding, they set the local binding's
587 value; the global binding is not changed.  This is not what we really
588 want.  To prevent it, use these special forms at top level in a file,
589 where normally no local binding is in effect, and make sure to load the
590 file before making a local binding for the variable.
591
592 \1f
593 File: lispref.info,  Node: Accessing Variables,  Next: Setting Variables,  Prev: Defining Variables,  Up: Variables
594
595 Accessing Variable Values
596 =========================
597
598    The usual way to reference a variable is to write the symbol which
599 names it (*note Symbol Forms::).  This requires you to specify the
600 variable name when you write the program.  Usually that is exactly what
601 you want to do.  Occasionally you need to choose at run time which
602 variable to reference; then you can use `symbol-value'.
603
604  - Function: symbol-value symbol
605      This function returns the value of SYMBOL.  This is the value in
606      the innermost local binding of the symbol, or its global value if
607      it has no local bindings.
608
609           (setq abracadabra 5)
610                => 5
611           (setq foo 9)
612                => 9
613           
614           ;; Here the symbol `abracadabra'
615           ;;   is the symbol whose value is examined.
616           (let ((abracadabra 'foo))
617             (symbol-value 'abracadabra))
618                => foo
619           
620           ;; Here the value of `abracadabra',
621           ;;   which is `foo',
622           ;;   is the symbol whose value is examined.
623           (let ((abracadabra 'foo))
624             (symbol-value abracadabra))
625                => 9
626           
627           (symbol-value 'abracadabra)
628                => 5
629
630      A `void-variable' error is signaled if SYMBOL has neither a local
631      binding nor a global value.
632
633 \1f
634 File: lispref.info,  Node: Setting Variables,  Next: Variable Scoping,  Prev: Accessing Variables,  Up: Variables
635
636 How to Alter a Variable Value
637 =============================
638
639    The usual way to change the value of a variable is with the special
640 form `setq'.  When you need to compute the choice of variable at run
641 time, use the function `set'.
642
643  - Special Form: setq [symbol form]...
644      This special form is the most common method of changing a
645      variable's value.  Each SYMBOL is given a new value, which is the
646      result of evaluating the corresponding FORM.  The most-local
647      existing binding of the symbol is changed.
648
649      `setq' does not evaluate SYMBOL; it sets the symbol that you
650      write.  We say that this argument is "automatically quoted".  The
651      `q' in `setq' stands for "quoted."
652
653      The value of the `setq' form is the value of the last FORM.
654
655           (setq x (1+ 2))
656                => 3
657           x                   ; `x' now has a global value.
658                => 3
659           (let ((x 5))
660             (setq x 6)        ; The local binding of `x' is set.
661             x)
662                => 6
663           x                   ; The global value is unchanged.
664                => 3
665
666      Note that the first FORM is evaluated, then the first SYMBOL is
667      set, then the second FORM is evaluated, then the second SYMBOL is
668      set, and so on:
669
670           (setq x 10          ; Notice that `x' is set before
671                 y (1+ x))     ;   the value of `y' is computed.
672                => 11
673
674  - Function: set symbol value
675      This function sets SYMBOL's value to VALUE, then returns VALUE.
676      Since `set' is a function, the expression written for SYMBOL is
677      evaluated to obtain the symbol to set.
678
679      The most-local existing binding of the variable is the binding
680      that is set; shadowed bindings are not affected.
681
682           (set one 1)
683           error--> Symbol's value as variable is void: one
684           (set 'one 1)
685                => 1
686           (set 'two 'one)
687                => one
688           (set two 2)         ; `two' evaluates to symbol `one'.
689                => 2
690           one                 ; So it is `one' that was set.
691                => 2
692           (let ((one 1))      ; This binding of `one' is set,
693             (set 'one 3)      ;   not the global value.
694             one)
695                => 3
696           one
697                => 2
698
699      If SYMBOL is not actually a symbol, a `wrong-type-argument' error
700      is signaled.
701
702           (set '(x y) 'z)
703           error--> Wrong type argument: symbolp, (x y)
704
705      Logically speaking, `set' is a more fundamental primitive than
706      `setq'.  Any use of `setq' can be trivially rewritten to use
707      `set'; `setq' could even be defined as a macro, given the
708      availability of `set'.  However, `set' itself is rarely used;
709      beginners hardly need to know about it.  It is useful only for
710      choosing at run time which variable to set.  For example, the
711      command `set-variable', which reads a variable name from the user
712      and then sets the variable, needs to use `set'.
713
714           Common Lisp note: In Common Lisp, `set' always changes the
715           symbol's special value, ignoring any lexical bindings.  In
716           XEmacs Lisp, all variables and all bindings are (in effect)
717           special, so `set' always affects the most local existing
718           binding.
719
720    One other function for setting a variable is designed to add an
721 element to a list if it is not already present in the list.
722
723  - Function: add-to-list symbol element
724      This function sets the variable SYMBOL by consing ELEMENT onto the
725      old value, if ELEMENT is not already a member of that value.  It
726      returns the resulting list, whether updated or not.  The value of
727      SYMBOL had better be a list already before the call.
728
729      The argument SYMBOL is not implicitly quoted; `add-to-list' is an
730      ordinary function, like `set' and unlike `setq'.  Quote the
731      argument yourself if that is what you want.
732
733      Here's a scenario showing how to use `add-to-list':
734
735           (setq foo '(a b))
736                => (a b)
737           
738           (add-to-list 'foo 'c)     ;; Add `c'.
739                => (c a b)
740           
741           (add-to-list 'foo 'b)     ;; No effect.
742                => (c a b)
743           
744           foo                       ;; `foo' was changed.
745                => (c a b)
746
747    An equivalent expression for `(add-to-list 'VAR VALUE)' is this:
748
749      (or (member VALUE VAR)
750          (setq VAR (cons VALUE VAR)))
751
752 \1f
753 File: lispref.info,  Node: Variable Scoping,  Next: Buffer-Local Variables,  Prev: Setting Variables,  Up: Variables
754
755 Scoping Rules for Variable Bindings
756 ===================================
757
758    A given symbol `foo' may have several local variable bindings,
759 established at different places in the Lisp program, as well as a global
760 binding.  The most recently established binding takes precedence over
761 the others.
762
763    Local bindings in XEmacs Lisp have "indefinite scope" and "dynamic
764 extent".  "Scope" refers to _where_ textually in the source code the
765 binding can be accessed.  Indefinite scope means that any part of the
766 program can potentially access the variable binding.  "Extent" refers
767 to _when_, as the program is executing, the binding exists.  Dynamic
768 extent means that the binding lasts as long as the activation of the
769 construct that established it.
770
771    The combination of dynamic extent and indefinite scope is called
772 "dynamic scoping".  By contrast, most programming languages use
773 "lexical scoping", in which references to a local variable must be
774 located textually within the function or block that binds the variable.
775
776      Common Lisp note: Variables declared "special" in Common Lisp are
777      dynamically scoped, like variables in XEmacs Lisp.
778
779 * Menu:
780
781 * Scope::          Scope means where in the program a value is visible.
782                      Comparison with other languages.
783 * Extent::         Extent means how long in time a value exists.
784 * Impl of Scope::  Two ways to implement dynamic scoping.
785 * Using Scoping::  How to use dynamic scoping carefully and avoid problems.
786
787 \1f
788 File: lispref.info,  Node: Scope,  Next: Extent,  Up: Variable Scoping
789
790 Scope
791 -----
792
793    XEmacs Lisp uses "indefinite scope" for local variable bindings.
794 This means that any function anywhere in the program text might access a
795 given binding of a variable.  Consider the following function
796 definitions:
797
798      (defun binder (x)   ; `x' is bound in `binder'.
799         (foo 5))         ; `foo' is some other function.
800      
801      (defun user ()      ; `x' is used in `user'.
802        (list x))
803
804    In a lexically scoped language, the binding of `x' in `binder' would
805 never be accessible in `user', because `user' is not textually
806 contained within the function `binder'.  However, in dynamically scoped
807 XEmacs Lisp, `user' may or may not refer to the binding of `x'
808 established in `binder', depending on circumstances:
809
810    * If we call `user' directly without calling `binder' at all, then
811      whatever binding of `x' is found, it cannot come from `binder'.
812
813    * If we define `foo' as follows and call `binder', then the binding
814      made in `binder' will be seen in `user':
815
816           (defun foo (lose)
817             (user))
818
819    * If we define `foo' as follows and call `binder', then the binding
820      made in `binder' _will not_ be seen in `user':
821
822           (defun foo (x)
823             (user))
824
825      Here, when `foo' is called by `binder', it binds `x'.  (The
826      binding in `foo' is said to "shadow" the one made in `binder'.)
827      Therefore, `user' will access the `x' bound by `foo' instead of
828      the one bound by `binder'.
829
830 \1f
831 File: lispref.info,  Node: Extent,  Next: Impl of Scope,  Prev: Scope,  Up: Variable Scoping
832
833 Extent
834 ------
835
836    "Extent" refers to the time during program execution that a variable
837 name is valid.  In XEmacs Lisp, a variable is valid only while the form
838 that bound it is executing.  This is called "dynamic extent".  "Local"
839 or "automatic" variables in most languages, including C and Pascal,
840 have dynamic extent.
841
842    One alternative to dynamic extent is "indefinite extent".  This
843 means that a variable binding can live on past the exit from the form
844 that made the binding.  Common Lisp and Scheme, for example, support
845 this, but XEmacs Lisp does not.
846
847    To illustrate this, the function below, `make-add', returns a
848 function that purports to add N to its own argument M.  This would work
849 in Common Lisp, but it does not work as intended in XEmacs Lisp,
850 because after the call to `make-add' exits, the variable `n' is no
851 longer bound to the actual argument 2.
852
853      (defun make-add (n)
854          (function (lambda (m) (+ n m))))  ; Return a function.
855           => make-add
856      (fset 'add2 (make-add 2))  ; Define function `add2'
857                                 ;   with `(make-add 2)'.
858           => (lambda (m) (+ n m))
859      (add2 4)                   ; Try to add 2 to 4.
860      error--> Symbol's value as variable is void: n
861
862    Some Lisp dialects have "closures", objects that are like functions
863 but record additional variable bindings.  XEmacs Lisp does not have
864 closures.
865
866 \1f
867 File: lispref.info,  Node: Impl of Scope,  Next: Using Scoping,  Prev: Extent,  Up: Variable Scoping
868
869 Implementation of Dynamic Scoping
870 ---------------------------------
871
872    A simple sample implementation (which is not how XEmacs Lisp actually
873 works) may help you understand dynamic binding.  This technique is
874 called "deep binding" and was used in early Lisp systems.
875
876    Suppose there is a stack of bindings: variable-value pairs.  At entry
877 to a function or to a `let' form, we can push bindings on the stack for
878 the arguments or local variables created there.  We can pop those
879 bindings from the stack at exit from the binding construct.
880
881    We can find the value of a variable by searching the stack from top
882 to bottom for a binding for that variable; the value from that binding
883 is the value of the variable.  To set the variable, we search for the
884 current binding, then store the new value into that binding.
885
886    As you can see, a function's bindings remain in effect as long as it
887 continues execution, even during its calls to other functions.  That is
888 why we say the extent of the binding is dynamic.  And any other function
889 can refer to the bindings, if it uses the same variables while the
890 bindings are in effect.  That is why we say the scope is indefinite.
891
892    The actual implementation of variable scoping in XEmacs Lisp uses a
893 technique called "shallow binding".  Each variable has a standard place
894 in which its current value is always found--the value cell of the
895 symbol.
896
897    In shallow binding, setting the variable works by storing a value in
898 the value cell.  Creating a new binding works by pushing the old value
899 (belonging to a previous binding) on a stack, and storing the local
900 value in the value cell.  Eliminating a binding works by popping the
901 old value off the stack, into the value cell.
902
903    We use shallow binding because it has the same results as deep
904 binding, but runs faster, since there is never a need to search for a
905 binding.
906
907 \1f
908 File: lispref.info,  Node: Using Scoping,  Prev: Impl of Scope,  Up: Variable Scoping
909
910 Proper Use of Dynamic Scoping
911 -----------------------------
912
913    Binding a variable in one function and using it in another is a
914 powerful technique, but if used without restraint, it can make programs
915 hard to understand.  There are two clean ways to use this technique:
916
917    * Use or bind the variable only in a few related functions, written
918      close together in one file.  Such a variable is used for
919      communication within one program.
920
921      You should write comments to inform other programmers that they
922      can see all uses of the variable before them, and to advise them
923      not to add uses elsewhere.
924
925    * Give the variable a well-defined, documented meaning, and make all
926      appropriate functions refer to it (but not bind it or set it)
927      wherever that meaning is relevant.  For example, the variable
928      `case-fold-search' is defined as "non-`nil' means ignore case when
929      searching"; various search and replace functions refer to it
930      directly or through their subroutines, but do not bind or set it.
931
932      Then you can bind the variable in other programs, knowing reliably
933      what the effect will be.
934
935    In either case, you should define the variable with `defvar'.  This
936 helps other people understand your program by telling them to look for
937 inter-function usage.  It also avoids a warning from the byte compiler.
938 Choose the variable's name to avoid name conflicts--don't use short
939 names like `x'.
940
941 \1f
942 File: lispref.info,  Node: Buffer-Local Variables,  Next: Variable Aliases,  Prev: Variable Scoping,  Up: Variables
943
944 Buffer-Local Variables
945 ======================
946
947    Global and local variable bindings are found in most programming
948 languages in one form or another.  XEmacs also supports another, unusual
949 kind of variable binding: "buffer-local" bindings, which apply only to
950 one buffer.  XEmacs Lisp is meant for programming editing commands, and
951 having different values for a variable in different buffers is an
952 important customization method.
953
954 * Menu:
955
956 * Intro to Buffer-Local::      Introduction and concepts.
957 * Creating Buffer-Local::      Creating and destroying buffer-local bindings.
958 * Default Value::              The default value is seen in buffers
959                                  that don't have their own local values.
960
961 \1f
962 File: lispref.info,  Node: Intro to Buffer-Local,  Next: Creating Buffer-Local,  Up: Buffer-Local Variables
963
964 Introduction to Buffer-Local Variables
965 --------------------------------------
966
967    A buffer-local variable has a buffer-local binding associated with a
968 particular buffer.  The binding is in effect when that buffer is
969 current; otherwise, it is not in effect.  If you set the variable while
970 a buffer-local binding is in effect, the new value goes in that binding,
971 so the global binding is unchanged; this means that the change is
972 visible in that buffer alone.
973
974    A variable may have buffer-local bindings in some buffers but not in
975 others.  The global binding is shared by all the buffers that don't have
976 their own bindings.  Thus, if you set the variable in a buffer that does
977 not have a buffer-local binding for it, the new value is visible in all
978 buffers except those with buffer-local bindings.  (Here we are assuming
979 that there are no `let'-style local bindings to complicate the issue.)
980
981    The most common use of buffer-local bindings is for major modes to
982 change variables that control the behavior of commands.  For example, C
983 mode and Lisp mode both set the variable `paragraph-start' to specify
984 that only blank lines separate paragraphs.  They do this by making the
985 variable buffer-local in the buffer that is being put into C mode or
986 Lisp mode, and then setting it to the new value for that mode.
987
988    The usual way to make a buffer-local binding is with
989 `make-local-variable', which is what major mode commands use.  This
990 affects just the current buffer; all other buffers (including those yet
991 to be created) continue to share the global value.
992
993    A more powerful operation is to mark the variable as "automatically
994 buffer-local" by calling `make-variable-buffer-local'.  You can think
995 of this as making the variable local in all buffers, even those yet to
996 be created.  More precisely, the effect is that setting the variable
997 automatically makes the variable local to the current buffer if it is
998 not already so.  All buffers start out by sharing the global value of
999 the variable as usual, but any `setq' creates a buffer-local binding
1000 for the current buffer.  The new value is stored in the buffer-local
1001 binding, leaving the (default) global binding untouched.  The global
1002 value can no longer be changed with `setq'; you need to use
1003 `setq-default' to do that.
1004
1005    Local variables in a file you edit are also represented by
1006 buffer-local bindings for the buffer that holds the file within XEmacs.
1007 *Note Auto Major Mode::.
1008
1009 \1f
1010 File: lispref.info,  Node: Creating Buffer-Local,  Next: Default Value,  Prev: Intro to Buffer-Local,  Up: Buffer-Local Variables
1011
1012 Creating and Deleting Buffer-Local Bindings
1013 -------------------------------------------
1014
1015  - Command: make-local-variable variable
1016      This function creates a buffer-local binding in the current buffer
1017      for VARIABLE (a symbol).  Other buffers are not affected.  The
1018      value returned is VARIABLE.
1019
1020      The buffer-local value of VARIABLE starts out as the same value
1021      VARIABLE previously had.  If VARIABLE was void, it remains void.
1022
1023           ;; In buffer `b1':
1024           (setq foo 5)                ; Affects all buffers.
1025                => 5
1026           (make-local-variable 'foo)  ; Now it is local in `b1'.
1027                => foo
1028           foo                         ; That did not change
1029                => 5                   ;   the value.
1030           (setq foo 6)                ; Change the value
1031                => 6                   ;   in `b1'.
1032           foo
1033                => 6
1034           
1035           ;; In buffer `b2', the value hasn't changed.
1036           (save-excursion
1037             (set-buffer "b2")
1038             foo)
1039                => 5
1040
1041      Making a variable buffer-local within a `let'-binding for that
1042      variable does not work.  This is because `let' does not distinguish
1043      between different kinds of bindings; it knows only which variable
1044      the binding was made for.
1045
1046      *Please note:* do not use `make-local-variable' for a hook
1047      variable.  Instead, use `make-local-hook'.  *Note Hooks::.
1048
1049  - Command: make-variable-buffer-local variable
1050      This function marks VARIABLE (a symbol) automatically
1051      buffer-local, so that any subsequent attempt to set it will make it
1052      local to the current buffer at the time.
1053
1054      The value returned is VARIABLE.
1055
1056  - Function: local-variable-p variable &optional buffer
1057      This returns `t' if VARIABLE is buffer-local in buffer BUFFER
1058      (which defaults to the current buffer); otherwise, `nil'.
1059
1060  - Function: buffer-local-variables &optional buffer
1061      This function returns a list describing the buffer-local variables
1062      in buffer BUFFER.  It returns an association list (*note
1063      Association Lists::) in which each association contains one
1064      buffer-local variable and its value.  When a buffer-local variable
1065      is void in BUFFER, then it appears directly in the resulting list.
1066      If BUFFER is omitted, the current buffer is used.
1067
1068           (make-local-variable 'foobar)
1069           (makunbound 'foobar)
1070           (make-local-variable 'bind-me)
1071           (setq bind-me 69)
1072           (setq lcl (buffer-local-variables))
1073               ;; First, built-in variables local in all buffers:
1074           => ((mark-active . nil)
1075               (buffer-undo-list nil)
1076               (mode-name . "Fundamental")
1077               ...
1078               ;; Next, non-built-in local variables.
1079               ;; This one is local and void:
1080               foobar
1081               ;; This one is local and nonvoid:
1082               (bind-me . 69))
1083
1084      Note that storing new values into the CDRs of cons cells in this
1085      list does _not_ change the local values of the variables.
1086
1087  - Command: kill-local-variable variable
1088      This function deletes the buffer-local binding (if any) for
1089      VARIABLE (a symbol) in the current buffer.  As a result, the
1090      global (default) binding of VARIABLE becomes visible in this
1091      buffer.  Usually this results in a change in the value of
1092      VARIABLE, since the global value is usually different from the
1093      buffer-local value just eliminated.
1094
1095      If you kill the local binding of a variable that automatically
1096      becomes local when set, this makes the global value visible in the
1097      current buffer.  However, if you set the variable again, that will
1098      once again create a local binding for it.
1099
1100      `kill-local-variable' returns VARIABLE.
1101
1102      This function is a command because it is sometimes useful to kill
1103      one buffer-local variable interactively, just as it is useful to
1104      create buffer-local variables interactively.
1105
1106  - Function: kill-all-local-variables
1107      This function eliminates all the buffer-local variable bindings of
1108      the current buffer except for variables marked as "permanent".  As
1109      a result, the buffer will see the default values of most variables.
1110
1111      This function also resets certain other information pertaining to
1112      the buffer: it sets the local keymap to `nil', the syntax table to
1113      the value of `standard-syntax-table', and the abbrev table to the
1114      value of `fundamental-mode-abbrev-table'.
1115
1116      Every major mode command begins by calling this function, which
1117      has the effect of switching to Fundamental mode and erasing most
1118      of the effects of the previous major mode.  To ensure that this
1119      does its job, the variables that major modes set should not be
1120      marked permanent.
1121
1122      `kill-all-local-variables' returns `nil'.
1123
1124    A local variable is "permanent" if the variable name (a symbol) has a
1125 `permanent-local' property that is non-`nil'.  Permanent locals are
1126 appropriate for data pertaining to where the file came from or how to
1127 save it, rather than with how to edit the contents.
1128
1129 \1f
1130 File: lispref.info,  Node: Default Value,  Prev: Creating Buffer-Local,  Up: Buffer-Local Variables
1131
1132 The Default Value of a Buffer-Local Variable
1133 --------------------------------------------
1134
1135    The global value of a variable with buffer-local bindings is also
1136 called the "default" value, because it is the value that is in effect
1137 except when specifically overridden.
1138
1139    The functions `default-value' and `setq-default' access and change a
1140 variable's default value regardless of whether the current buffer has a
1141 buffer-local binding.  For example, you could use `setq-default' to
1142 change the default setting of `paragraph-start' for most buffers; and
1143 this would work even when you are in a C or Lisp mode buffer that has a
1144 buffer-local value for this variable.
1145
1146    The special forms `defvar' and `defconst' also set the default value
1147 (if they set the variable at all), rather than any local value.
1148
1149  - Function: default-value symbol
1150      This function returns SYMBOL's default value.  This is the value
1151      that is seen in buffers that do not have their own values for this
1152      variable.  If SYMBOL is not buffer-local, this is equivalent to
1153      `symbol-value' (*note Accessing Variables::).
1154
1155  - Function: default-boundp symbol
1156      The function `default-boundp' tells you whether SYMBOL's default
1157      value is nonvoid.  If `(default-boundp 'foo)' returns `nil', then
1158      `(default-value 'foo)' would get an error.
1159
1160      `default-boundp' is to `default-value' as `boundp' is to
1161      `symbol-value'.
1162
1163  - Special Form: setq-default symbol value
1164      This sets the default value of SYMBOL to VALUE.  It does not
1165      evaluate SYMBOL, but does evaluate VALUE.  The value of the
1166      `setq-default' form is VALUE.
1167
1168      If a SYMBOL is not buffer-local for the current buffer, and is not
1169      marked automatically buffer-local, `setq-default' has the same
1170      effect as `setq'.  If SYMBOL is buffer-local for the current
1171      buffer, then this changes the value that other buffers will see
1172      (as long as they don't have a buffer-local value), but not the
1173      value that the current buffer sees.
1174
1175           ;; In buffer `foo':
1176           (make-local-variable 'local)
1177                => local
1178           (setq local 'value-in-foo)
1179                => value-in-foo
1180           (setq-default local 'new-default)
1181                => new-default
1182           local
1183                => value-in-foo
1184           (default-value 'local)
1185                => new-default
1186           
1187           ;; In (the new) buffer `bar':
1188           local
1189                => new-default
1190           (default-value 'local)
1191                => new-default
1192           (setq local 'another-default)
1193                => another-default
1194           (default-value 'local)
1195                => another-default
1196           
1197           ;; Back in buffer `foo':
1198           local
1199                => value-in-foo
1200           (default-value 'local)
1201                => another-default
1202
1203  - Function: set-default symbol value
1204      This function is like `setq-default', except that SYMBOL is
1205      evaluated.
1206
1207           (set-default (car '(a b c)) 23)
1208                => 23
1209           (default-value 'a)
1210                => 23
1211