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