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