home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / unix / info / elisp.i06 (.txt) < prev    next >
GNU Info File  |  1993-06-14  |  51KB  |  927 lines

  1. This is Info file elisp, produced by Makeinfo-1.47 from the input file
  2. elisp.texi.
  3.    This file documents GNU Emacs Lisp.
  4.    This is edition 1.03 of the GNU Emacs Lisp Reference Manual, for
  5. Emacs Version 18.
  6.    Published by the Free Software Foundation, 675 Massachusetts Avenue,
  7. Cambridge, MA 02139 USA
  8.    Copyright (C) 1990 Free Software Foundation, Inc.
  9.    Permission is granted to make and distribute verbatim copies of this
  10. manual provided the copyright notice and this permission notice are
  11. preserved on all copies.
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided that
  14. the entire resulting derived work is distributed under the terms of a
  15. permission notice identical to this one.
  16.    Permission is granted to copy and distribute translations of this
  17. manual into another language, under the above conditions for modified
  18. versions, except that this permission notice may be stated in a
  19. translation approved by the Foundation.
  20. File: elisp,  Node: Nonlocal Exits,  Prev: Iteration,  Up: Control Structures
  21. Nonlocal Exits
  22. ==============
  23.    A "nonlocal exit" is a transfer of control from one point in a
  24. program to another remote point.  Nonlocal exits can occur in Emacs Lisp
  25. as a result of errors; you can also use them under explicit control.
  26. * Menu:
  27. * Catch and Throw::     Nonlocal exits for the program's own purposes.
  28. * Examples of Catch::   Showing how such nonlocal exits can be written.
  29. * Errors::              How errors are signaled and handled.
  30. * Cleanups::            Arranging to run a cleanup form if an error happens.
  31. File: elisp,  Node: Catch and Throw,  Next: Examples of Catch,  Prev: Nonlocal Exits,  Up: Nonlocal Exits
  32. Explicit Nonlocal Exits: `catch' and `throw'
  33. --------------------------------------------
  34.    Most control constructs affect only the flow of control within the
  35. construct itself.  The function `throw' is the sole exception: it
  36. performs a nonlocal exit on request.  `throw' is used inside a `catch',
  37. and jumps back to that `catch'.  For example:
  38.      (catch 'foo
  39.        (progn
  40.          ...
  41.            (throw 'foo t)
  42.          ...))
  43. The `throw' transfers control straight back to the corresponding
  44. `catch', which returns immediately.  The code following the `throw' is
  45. not executed.  The second argument of `throw' is used as the return
  46. value of the `catch'.
  47.    The `throw' and the `catch' are matched through the first argument:
  48. `throw' searches for a `catch' whose first argument is `eq' to the one
  49. specified.  Thus, in the above example, the `throw' specifies `foo',
  50. and the `catch' specifies the same symbol, so that `catch' is
  51. applicable.  If there is more than one applicable `catch', the
  52. innermost one takes precedence.
  53.    All Lisp constructs between the `catch' and the `throw', including
  54. function calls, are exited automatically along with the `catch'.  When
  55. binding constructs such as `let' or function calls are exited in this
  56. way, the bindings are unbound, just as they are when the binding
  57. construct is exited normally (*note Local Variables::.). Likewise, the
  58. buffer and position saved by `save-excursion' (*note Excursions::.) are
  59. restored, and so is the narrowing status saved by `save-restriction'
  60. and the window selection saved by `save-window-excursion' (*note Window
  61. Configurations::.).  Any cleanups established with the `unwind-protect'
  62. special form are executed if the `unwind-protect' is exited with a
  63. `throw'.
  64.    The `throw' need not appear lexically within the `catch' that it
  65. jumps to.  It can equally well be called from another function called
  66. within the `catch'.  As long as the `throw' takes place chronologically
  67. after entry to the `catch', and chronologically before exit from it, it
  68. has access to that `catch'.  This is why `throw' can be used in
  69. commands such as `exit-recursive-edit' which throw back to the editor
  70. command loop (*note Recursive Editing::.).
  71.      Common Lisp note: most other versions of Lisp, including Common
  72.      Lisp, have several ways of transferring control nonsequentially:
  73.      `return', `return-from', and `go', for example.  Emacs Lisp has
  74.      only `throw'.
  75.  -- Special Form: catch TAG BODY...
  76.      `catch' establishes a return point for the `throw' function.  The
  77.      return point is distinguished from other such return points by TAG,
  78.      which may be any Lisp object.  The argument TAG is evaluated
  79.      normally before the return point is established.
  80.      With the return point in effect, the forms of the BODY are
  81.      evaluated in textual order.  If the forms execute normally,
  82.      without error or nonlocal exit, the value of the last body form is
  83.      returned from the `catch'.
  84.      If a `throw' is done within BODY specifying the same value TAG,
  85.      the `catch' exits immediately; the value it returns is whatever
  86.      was specified as the second argument of `throw'.
  87.  -- Function: throw TAG VALUE
  88.      The purpose of `throw' is to return from a return point previously
  89.      established with `catch'.  The argument TAG is used to choose
  90.      among the various existing return points; it must be `eq' to the
  91.      value specified in the `catch'.  If multiple return points match
  92.      TAG, the innermost one is used.
  93.      The argument VALUE is used as the value to return from that
  94.      `catch'.
  95.      If no return point is in effect with tag TAG, then a `no-catch'
  96.      error is signaled with data `(TAG VALUE)'.
  97. File: elisp,  Node: Examples of Catch,  Next: Errors,  Prev: Catch and Throw,  Up: Nonlocal Exits
  98. Examples of `catch' and `throw'
  99. -------------------------------
  100.    One way to use `catch' and `throw' is to exit from a doubly nested
  101. loop.  (In most languages, this would be done with a "go to".) Here we
  102. compute `(foo I J)' for I and J varying from 0 to 9:
  103.      (defun search-foo ()
  104.        (catch 'loop
  105.          (let ((i 0))
  106.            (while (< i 10)
  107.              (let ((j 0))
  108.                (while (< j 10)
  109.                  (if (foo i j)
  110.                      (throw 'loop (list i j)))
  111.                  (setq j (1+ j))))
  112.              (setq i (1+ i))))))
  113. If `foo' ever returns non-`nil', we stop immediately and return a list
  114. of I and J.  If `foo' always returns `nil', the `catch' returns
  115. normally, and the value is `nil', since that is the result of the
  116. `while'.
  117.    Here are two tricky examples, slightly different, showing two return
  118. points at once.  First, two return points with the same tag, `hack':
  119.      (defun catch2 (tag)
  120.        (catch tag
  121.          (throw 'hack 'yes)))
  122.      => catch2
  123.      
  124.      (catch 'hack
  125.        (print (catch2 'hack))
  126.        'no)
  127.      -| yes
  128.      => no
  129. Since both return points have tags that match the `throw', it goes to
  130. the inner one, the one established in `catch2'.  Therefore, `catch2'
  131. returns normally with value `yes', and this value is printed.  Finally
  132. the second body form in the outer `catch', which is `'no', is evaluated
  133. and returned from the outer `catch'.
  134.    Now let's change the argument given to `catch2':
  135.      (defun catch2 (tag)
  136.        (catch tag
  137.          (throw 'hack 'yes)))
  138.      => catch2
  139.      
  140.      (catch 'hack
  141.        (print (catch2 'quux))
  142.        'no)
  143.      => yes
  144. We still have two return points, but this time only the outer one has
  145. the tag `hack'; the inner one has the tag `quux' instead.  Therefore,
  146. the `throw' returns the value `yes' from the outer return point. The
  147. function `print' is never called, and the body-form `'no' is never
  148. evaluated.
  149. File: elisp,  Node: Errors,  Next: Cleanups,  Prev: Examples of Catch,  Up: Nonlocal Exits
  150. Errors
  151. ------
  152.    When Emacs Lisp attempts to evaluate a form that, for some reason,
  153. cannot be evaluated, it "signals" an "error".
  154.    When an error is signaled, Emacs's default reaction is to print an
  155. error message and terminate execution of the current command.  This is
  156. the right thing to do in most cases, such as if you type `C-f' at the
  157. end of the buffer.
  158.    In complicated programs, simple termination may not be what you want.
  159. For example, the program may have made temporary changes in data
  160. structures, or created temporary buffers which should be deleted before
  161. the program is finished.  In such cases, you would use `unwind-protect'
  162. to establish "cleanup expressions" to be evaluated in case of error. 
  163. Occasionally, you may wish the program to continue execution despite an
  164. error in a subroutine.  In these cases, you would use `condition-case'
  165. to establish "error handlers" to recover control in case of error.
  166.    Resist the temptation to use error handling to transfer control from
  167. one part of the program to another; use `catch' and `throw'. *Note
  168. Catch and Throw::.
  169. * Menu:
  170. * Signaling Errors::      How to report an error.
  171. * Processing of Errors::  What Emacs does when you report an error.
  172. * Handling Errors::       How you can trap errors and continue execution.
  173. * Error Names::           How errors are classified for trapping them.
  174. File: elisp,  Node: Signaling Errors,  Next: Processing of Errors,  Prev: Errors,  Up: Errors
  175. How to Signal an Error
  176. ......................
  177.    Most errors are signaled "automatically" within Lisp primitives
  178. which you call for other purposes, such as if you try to take the CAR
  179. of an integer or move forward a character at the end of the buffer; you
  180. can also signal errors explicitly with the functions `error' and
  181. `signal'.
  182.  -- Function: error FORMAT-STRING &rest ARGS
  183.      This function signals an error with an error message constructed by
  184.      applying `format' (*note String Conversion::.) to FORMAT-STRING
  185.      and ARGS.
  186.      Typical uses of `error' is shown in the following examples:
  187.           (error "You have committed an error.  Try something else.")
  188.                error--> You have committed an error.  Try something else.
  189.           
  190.           (error "You have committed %d errors.  You don't learn fast." 10)
  191.                error--> You have committed 10 errors.  You don't learn fast.
  192.      `error' works by calling `signal' with two arguments: the error
  193.      symbol `error', and a list containing the string returned by
  194.      `format'.
  195.      If you want to use a user-supplied string as an error message
  196.      verbatim, don't just write `(error STRING)'.  If STRING contains
  197.      `%', it will be interpreted as a format specifier, with undesirable
  198.      results.  Instead, use `(error "%s" STRING)'.
  199.  -- Function: signal ERROR-SYMBOL DATA
  200.      This function signals an error named by ERROR-SYMBOL.  The
  201.      argument DATA is a list of additional Lisp objects relevant to the
  202.      circumstances of the error.
  203.      The argument ERROR-SYMBOL must be an "error symbol"--a symbol that
  204.      has an `error-conditions' property whose value is a list of
  205.      condition names.  This is how different sorts of errors are
  206.      classified.
  207.      The number and significance of the objects in DATA depends on
  208.      ERROR-SYMBOL.  For example, with a `wrong-type-arg' error, there
  209.      are two objects in the list: a predicate which describes the type
  210.      that was expected, and the object which failed to fit that type.
  211.      *Note Error Names::, for a description of error symbols.
  212.      Both ERROR-SYMBOL and DATA are available to any error handlers
  213.      which handle the error: a list `(ERROR-SYMBOL . DATA)' is
  214.      constructed to become the value of the local variable bound in the
  215.      `condition-case' form (*note Handling Errors::.).  If the error is
  216.      not handled, both of them are used in printing the error message.
  217.           (signal 'wrong-number-of-arguments '(x y))
  218.                error--> Wrong number of arguments: x, y
  219.           
  220.           (signal 'no-such-error '("My unknown error condition."))
  221.                error--> peculiar error: "My unknown error condition."
  222.      Common Lisp note: Emacs Lisp has nothing like the Common Lisp
  223.      concept of continuable errors.
  224. File: elisp,  Node: Processing of Errors,  Next: Handling Errors,  Prev: Signaling Errors,  Up: Errors
  225. How Emacs Processes Errors
  226. ..........................
  227.    When an error is signaled, Emacs searches for an active "handler"
  228. for the error.  A handler is a specially marked place in the Lisp code
  229. of the current function or any of the functions by which it was called.
  230. If an applicable handler exists, its code is executed, and control
  231. resumes following the handler.  The handler executes in the environment
  232. of the `condition-case' which established it; all functions called
  233. within that `condition-case' have already been exited, and the handler
  234. cannot return to them.
  235.    If no applicable handler is in effect in your program, the current
  236. command is terminated and control returns to the editor command loop,
  237. because the command loop has an implicit handler for all kinds of
  238. errors.  The command loop's handler uses the error symbol and associated
  239. data to print an error message.
  240.    When an error is not handled explicitly, it may cause the Lisp
  241. debugger to be called.  The debugger is enabled if the variable
  242. `debug-on-error' (*note Error Debugging::.) is non-`nil'. Unlike error
  243. handlers, the debugger runs in the environment of the error, so that
  244. you can examine values of variables precisely as they were at the time
  245. of the error.
  246. File: elisp,  Node: Handling Errors,  Next: Error Names,  Prev: Processing of Errors,  Up: Errors
  247. Writing Code to Handle Errors
  248. .............................
  249.    The usual effect of signaling an error is to terminate the command
  250. that is running and return immediately to the Emacs editor command loop.
  251. You can arrange to trap errors occurring in a part of your program by
  252. establishing an "error handler" with the special form `condition-case'.
  253.  A simple example looks like this:
  254.      (condition-case nil
  255.          (delete-file filename)
  256.        (error nil))
  257. This deletes the file named FILENAME, catching any error and returning
  258. `nil' if an error occurs.
  259.    The second argument of `condition-case' is called the "protected
  260. form".  (In the example above, the protected form is a call to
  261. `delete-file'.)  The error handlers go into effect when this form
  262. begins execution and are deactivated when this form returns. They
  263. remain in effect for all the intervening time.  In particular, they are
  264. in effect during the execution of subroutines called by this form, and
  265. their subroutines, and so on.  This is a good thing, since, strictly
  266. speaking, errors can be signaled only by Lisp primitives (including
  267. `signal' and `error') called by the protected form, not by the
  268. protected form itself.
  269.    The arguments after the protected form are handlers.  Each handler
  270. lists one or more "condition names" (which are symbols) to specify
  271. which errors it will handle.  The error symbol specified when an error
  272. is signaled also defines a list of condition names.  A handler applies
  273. to an error if they have any condition names in common.  In the example
  274. above, there is one handler, and it specifies one condition name,
  275. `error', which covers all errors.
  276.    The search for an applicable handler checks all the established
  277. handlers starting with the most recently established one.  Thus, if two
  278. nested `condition-case' forms try to handle the same error, the inner of
  279. the two will actually handle it.
  280.    When an error is handled, control returns to the handler, unbinding
  281. all variable bindings made by binding constructs that are exited and
  282. executing the cleanups of all `unwind-protect' forms that are exited by
  283. doing so.  Then the body of the handler is executed.  After this,
  284. execution continues by returning from the `condition-case' form. 
  285. Because the protected form is exited completely before execution of the
  286. handler, the handler cannot resume execution at the point of the error,
  287. nor can it examine variable bindings that were made within the
  288. protected form.  All it can do is clean up and proceed.
  289.    Error signaling and handling have some resemblance to `throw' and
  290. `catch', but they are entirely separate facilities.  An error cannot be
  291. caught by a `catch', and a `throw' cannot be handled by an error
  292. handler (though if there is no `catch', `throw' will signal an error
  293. which can be handled).
  294.  -- Special Form: condition-case VAR PROTECTED-FORM HANDLERS...
  295.      This special form establishes the error handlers HANDLERS around
  296.      the execution of PROTECTED-FORM.  If PROTECTED-FORM executes
  297.      without error, the value it returns becomes the value of the
  298.      `condition-case' form; in this case, the `condition-case' has no
  299.      effect.  The `condition-case' form makes a difference when an
  300.      error occurs during PROTECTED-FORM.
  301.      Each of the HANDLERS is a list of the form `(CONDITIONS BODY...)'.
  302.       CONDITIONS is a condition name to be handled, or a list of
  303.      condition names; BODY is one or more Lisp expressions to be
  304.      executed when this handler handles an error.
  305.      Each error that occurs has an "error symbol" which describes what
  306.      kind of error it is.  The `error-conditions' property of this
  307.      symbol is a list of condition names (*note Error Names::.).  Emacs
  308.      searches all the active `condition-case' forms for a handler which
  309.      specifies one or more of these names; the innermost matching
  310.      `condition-case' handles the error.  The handlers in this
  311.      `condition-case' are tested in the order in which they appear.
  312.      The body of the handler is then executed, and the `condition-case'
  313.      returns normally, using the value of the last form in the body as
  314.      the overall value.
  315.      The argument VAR is a variable.  `condition-case' does not bind
  316.      this variable when executing the PROTECTED-FORM, only when it
  317.      handles an error.  At that time, VAR is bound locally to a list of
  318.      the form `(ERROR-SYMBOL . DATA)', giving the particulars of the
  319.      error.  The handler can refer to this list to decide what to do. 
  320.      For example, if the error is for failure opening a file, the file
  321.      name is the second element of DATA--the third element of VAR.
  322.      If VAR is `nil', that means no variable is bound.  Then the error
  323.      symbol and associated data are not made available to the handler.
  324.    Here is an example of using `condition-case' to handle the error
  325. that results from dividing by zero.  The handler prints out a warning
  326. message and returns a very large number.
  327.      (defun safe-divide (dividend divisor)
  328.        (condition-case err
  329.            ;; Protected form.
  330.            (/ dividend divisor)
  331.          ;; The handler.
  332.          (arith-error                        ; Condition.
  333.           (princ (format "Arithmetic error: %s" err))
  334.           1000000)))
  335.      => safe-divide
  336.      
  337.      (safe-divide 5 0)
  338.           -| Arithmetic error: (arith-error)
  339.      => 1000000
  340. The handler specifies condition name `arith-error' so that it will
  341. handle only division-by-zero errors.  Other kinds of errors will not be
  342. handled, at least not by this `condition-case'.  Thus,
  343.      (safe-divide nil 3)
  344.           error--> Wrong type argument: integer-or-marker-p, nil
  345.    Here is a `condition-case' that catches all kinds of errors,
  346. including those signaled with `error':
  347.      (setq baz 34)
  348.           => 34
  349.      
  350.      (condition-case err
  351.          (if (eq baz 35)
  352.              t
  353.            ;; This is a call to the function `error'.
  354.            (error "Rats!  The variable %s was %s, not 35." 'baz baz))
  355.        ;; This is the handler; it is not a form.
  356.        (error (princ (format "The error was: %s" err))
  357.               2))
  358.      
  359.           -| The error was: (error "Rats!  The variable baz was 34, not 35.")
  360.           => 2
  361.    `condition-case' is often used to trap errors that are predictable,
  362. such as failure to open a file in a call to `insert-file-contents'.  It
  363. is also used to trap errors that are totally unpredictable, such as
  364. when the program evaluates an expression read from the user.
  365. File: elisp,  Node: Error Names,  Prev: Handling Errors,  Up: Errors
  366. Error Symbols and Condition Names
  367. .................................
  368.    When you signal an error, you specify an "error symbol" to specify
  369. the kind of error you have in mind.  Each error has one and only one
  370. error symbol to categorize it.  This is the finest classification of
  371. errors defined by the Lisp language.
  372.    These narrow classifications are grouped into a hierarchy of wider
  373. classes called "error conditions", identified by "condition names". 
  374. The narrowest such classes belong to the error symbols themselves: each
  375. error symbol is also a condition name.  There are also condition names
  376. for more extensive classes, up to the condition name `error' which
  377. takes in all kinds of errors.  Thus, each error has one or more
  378. condition names: `error', the error symbol if that is distinct from
  379. `error', and perhaps some intermediate classifications.
  380.    In order for a symbol to be usable as an error symbol, it must have
  381. an `error-conditions' property which gives a list of condition names.
  382. This list defines the conditions which this kind of error belongs to.
  383. (The error symbol itself, and the symbol `error', should always be
  384. members of this list.)  Thus, the hierarchy of condition names is
  385. defined by the `error-conditions' properties of the error symbols.
  386.    In addition to the `error-conditions' list, the error symbol should
  387. have an `error-message' property whose value is a string to be printed
  388. when that error is signaled but not handled.  If the `error-message'
  389. property exists, but is not a string, the error message `peculiar
  390. error' is used.
  391.    Here is how we define a new error symbol, `new-error':
  392.      (put 'new-error 'error-conditions '(error my-own-errors new-error))
  393.           => (error my-own-errors new-error)
  394.      (put 'new-error 'error-message "A new error")
  395.           => "A new error"
  396. This error has three condition names: `new-error', the narrowest
  397. classification; `my-own-errors', which we imagine is a wider
  398. classification; and `error', which is the widest of all.
  399.    Naturally, Emacs will never signal a `new-error' on its own; only an
  400. explicit call to `signal' (*note Errors::.) in your code can do this:
  401.      (signal 'new-error '(x y))
  402.           error--> A new error: x, y
  403.    This error can be handled through any of the three condition names.
  404. This example handles `new-error' and any other errors in the class
  405. `my-own-errors':
  406.      (condition-case foo
  407.          (bar nil t)
  408.        (my-own-errors nil))
  409.    The significant way that errors are classified is by their condition
  410. names--the names used to match errors with handlers.  An error symbol
  411. serves only as a convenient way to specify the intended error message
  412. and list of condition names.  If `signal' were given a list of
  413. condition names rather than one error symbol, that would be cumbersome.
  414.    By contrast, using only error symbols without condition names would
  415. seriously decrease the power of `condition-case'.  Condition names make
  416. it possible to categorize errors at various levels of generality when
  417. you write an error handler.  Using error symbols alone would eliminate
  418. all but the narrowest level of classification.
  419.    *Note Standard Errors::, for a list of all the standard error symbols
  420. and their conditions.
  421. File: elisp,  Node: Cleanups,  Prev: Errors,  Up: Nonlocal Exits
  422. Cleaning up from Nonlocal Exits
  423. -------------------------------
  424.    The `unwind-protect' construct is essential whenever you temporarily
  425. put a data structure in an inconsistent state; it permits you to ensure
  426. the data are consistent in the event of an error.
  427.  -- Special Form: unwind-protect BODY CLEANUP-FORMS...
  428.      `unwind-protect' executes the BODY with a guarantee that the
  429.      CLEANUP-FORMS will be evaluated if control leaves BODY, no matter
  430.      how that happens.  The BODY may complete normally, or execute a
  431.      `throw' out of the `unwind-protect', or cause an error; in all
  432.      cases, the CLEANUP-FORMS will be evaluated.
  433.      Only the BODY is actually protected by the `unwind-protect'. If
  434.      any of the CLEANUP-FORMS themselves exit nonlocally (e.g., via a
  435.      `throw' or an error), it is *not* guaranteed that the rest of them
  436.      will be executed.  If the failure of one of the CLEANUP-FORMS has
  437.      the potential to cause trouble, then it should be protected by
  438.      another `unwind-protect' around that form.
  439.      The number of currently active `unwind-protect' forms counts,
  440.      together with the number of local variable bindings, against the
  441.      limit `max-specpdl-size' (*note Local Variables::.).
  442.    For example, here we make an invisible buffer for temporary use, and
  443. make sure to kill it before finishing:
  444.      (save-excursion
  445.        (let ((buffer (get-buffer-create " *temp*")))
  446.          (set-buffer buffer)
  447.          (unwind-protect
  448.              BODY
  449.            (kill-buffer buffer))))
  450. You might think that we could just as well write `(kill-buffer
  451. (current-buffer))' and dispense with the variable `buffer'. However,
  452. the way shown above is safer, if BODY happens to get an error after
  453. switching to a different buffer!  (Alternatively, you could write
  454. another `save-excursion' around the body, to ensure that the temporary
  455. buffer becomes current in time to kill it.)
  456.    Here is an actual example taken from the file `ftp.el'.  It creates
  457. a process (*note Processes::.) to try to establish a connection to a
  458. remote machine.  As the function `ftp-login' is highly susceptible to
  459. numerous problems which the writer of the function cannot anticipate,
  460. it is protected with a form that guarantees deletion of the process in
  461. the event of failure.  Otherwise, Emacs might fill up with useless
  462. subprocesses.
  463.      (let ((win nil))
  464.        (unwind-protect
  465.            (progn
  466.              (setq process (ftp-setup-buffer host file))
  467.              (if (setq win (ftp-login process host user password))
  468.                  (message "Logged in")
  469.                (error "Ftp login failed")))
  470.          (or win (and process (delete-process process)))))
  471.    This example actually has a small bug: if the user types `C-g' to
  472. quit, and the quit happens immediately after the function
  473. `ftp-setup-buffer' returns but before the variable `process' is set,
  474. the process will not be killed.  There is no easy way to fix this bug,
  475. but at least it is very unlikely.
  476. File: elisp,  Node: Variables,  Next: Functions,  Prev: Control Structures,  Up: Top
  477. Variables
  478. *********
  479.    A "variable" is a name used in a program to stand for a value.
  480. Nearly all programming languages have variables of some sort.  In the
  481. text for a Lisp program, variables are written using the syntax for
  482. symbols.
  483.    In Lisp, unlike most programming languages, programs are represented
  484. primarily as Lisp objects and only secondarily as text.  The Lisp
  485. objects used for variables are symbols: the symbol name is the variable
  486. name, and the variable's value is stored in the value cell of the
  487. symbol.  The use of a symbol as a variable is independent of whether
  488. the same symbol has a function definition.  *Note Symbol Components::.
  489.    The textual form of a program is determined by its Lisp object
  490. representation; it is the read syntax for the Lisp object which
  491. constitutes the program.  This is why a variable in a textual Lisp
  492. program is written as the read syntax for the symbol that represents the
  493. variable.
  494. * Menu:
  495. * Global Variables::      Variable values that exist permanently, everywhere.
  496. * Constant Variables::    Certain "variables" have values that never change.
  497. * Local Variables::       Variable values that exist only temporarily.
  498. * Void Variables::        Symbols that lack values.
  499. * Defining Variables::    A definition says a symbol is used as a variable.
  500. * Accessing Variables::   Examining values of variables whose names
  501.                             are known only at run time.
  502. * Setting Variables::     Storing new values in variables.
  503. * Variable Scoping::      How Lisp chooses among local and global values.
  504. * Buffer-Local Variables::  Variable values in effect only in one buffer.
  505. File: elisp,  Node: Global Variables,  Next: Constant Variables,  Prev: Variables,  Up: Variables
  506. Global Variables
  507. ================
  508.    The simplest way to use a variable is "globally".  This means that
  509. the variable has just one value at a time, and this value is in effect
  510. (at least for the moment) throughout the Lisp system.  The value remains
  511. in effect until you specify a new one.  When a new value replaces the
  512. old one, no trace of the old value remains in the variable.
  513.    You specify a value for a symbol with `setq'.  For example,
  514.      (setq x '(a b))
  515. gives the variable `x' the value `(a b)'.  Note that the first argument
  516. of `setq', the name of the variable, is not evaluated, but the second
  517. argument, the desired value, is evaluated normally.
  518.    Once the variable has a value, you can refer to it by using the
  519. symbol by itself as an expression.  Thus,
  520.      x
  521.           => (a b)
  522. assuming the `setq' form shown above has already been executed.
  523.    If you do another `setq', the new value replaces the old one:
  524.      x
  525.           => (a b)
  526.      (setq x 4)
  527.           => 4
  528.      x
  529.           => 4
  530. File: elisp,  Node: Constant Variables,  Next: Local Variables,  Prev: Global Variables,  Up: Variables
  531. Variables that Never Change
  532. ===========================
  533.    Emacs Lisp has two special symbols, `nil' and `t', that always
  534. evaluate to themselves.  These symbols cannot be rebound, nor can their
  535. value cells be changed.  An attempt to change the value of `nil' or `t'
  536. signals a `setting-constant' error.
  537.      nil == 'nil
  538.           => nil
  539.      (setq nil 500)
  540.      error--> Attempt to set constant symbol: nil
  541. File: elisp,  Node: Local Variables,  Next: Void Variables,  Prev: Constant Variables,  Up: Variables
  542. Local Variables
  543. ===============
  544.    Global variables are given values that last until explicitly
  545. superseded with new values.  Sometimes it is useful to create variable
  546. values that exist temporarily--only while within a certain part of the
  547. program.  These values are called "local", and the variables so used
  548. are called "local variables".
  549.    For example, when a function is called, its argument variables
  550. receive new local values which last until the function exits. 
  551. Similarly, the `let' special form explicitly establishes new local
  552. values for specified variables; these last until exit from the `let'
  553. form.
  554.    When a local value is established, the previous value (or lack of
  555. one) of the variable is saved away.  When the life span of the local
  556. value is over, the previous value is restored.  In the mean time, we
  557. say that the previous value is "shadowed" and "not visible".  Both
  558. global and local values may be shadowed.
  559.    If you set a variable (such as with `setq') while it is local, this
  560. replaces the local value; it does not alter the global value, or
  561. previous local values that are shadowed.  To model this behavior, we
  562. speak of a "local binding" of the variable as well as a local value.
  563.    The local binding is a conceptual place that holds a local value.
  564. Entry to a function, or a special form such as `let', creates the local
  565. binding; exit from the function or from the `let' removes the local
  566. binding.  As long as the local binding lasts, the variable's value is
  567. stored within it.  Use of `setq' or `set' while there is a local
  568. binding stores a different value into the local binding; it does not
  569. create a new binding.
  570.    We also speak of the "global binding", which is where (conceptually)
  571. the global value is kept.
  572.    A variable can have more than one local binding at a time (for
  573. example, if there are nested `let' forms that bind it).  In such a
  574. case, the most recently created local binding that still exists is the
  575. "current binding" of the variable.  (This is called "dynamic scoping";
  576. see *Note Variable Scoping::.)  If there are no local bindings, the
  577. variable's global binding is its current binding.  We also call the
  578. current binding the "most-local existing binding", for emphasis.
  579. Ordinary evaluation of a symbol always returns the value of its current
  580. binding.
  581.    The special forms `let' and `let*' exist to create local bindings.
  582.  -- Special Form: let (BINDINGS...) FORMS...
  583.      This function binds variables according to BINDINGS and then
  584.      evaluates all of the FORMS in textual order.  The `let'-form
  585.      returns the value of the last form in FORMS.
  586.      Each of the BINDINGS is either (i) a symbol, in which case that
  587.      symbol is bound to `nil'; or (ii) a list of the form `(SYMBOL
  588.      VALUE-FORM)', in which case SYMBOL is bound to the result of
  589.      evaluating VALUE-FORM.  If VALUE-FORM is omitted, `nil' is used.
  590.      All of the VALUE-FORMs in BINDINGS are evaluated in the order they
  591.      appear and *before* any of the symbols are bound.  Here is an
  592.      example of this: `Z' is bound to the old value of `Y', which is 2,
  593.      not the new value, 1.
  594.           (setq Y 2)
  595.                => 2
  596.           (let ((Y 1)
  597.                 (Z Y))
  598.             (list Y Z))
  599.                => (1 2)
  600.  -- Special Form: let* (BINDINGS...) FORMS...
  601.      This special form is like `let', except that each symbol in
  602.      BINDINGS is bound as soon as its new value is computed, before the
  603.      computation of the values of the following local bindings. 
  604.      Therefore, an expression in BINDINGS may reasonably refer to the
  605.      preceding symbols bound in this `let*' form.  Compare the
  606.      following example with the example above for `let'.
  607.           (setq Y 2)
  608.                => 2
  609.           (let* ((Y 1)
  610.                  (Z Y))    ; Use the just-established value of `Y'.
  611.             (list Y Z))
  612.                => (1 1)
  613.    Here is a complete list of the other facilities which create local
  614. bindings:
  615.    * Function calls (*note Functions::.).
  616.    * Macro calls (*note Macros::.).
  617.    * `condition-case' (*note Errors::.).
  618.  -- Variable: max-specpdl-size
  619.      This variable defines the limit on the number of local variable
  620.      bindings and `unwind-protect' cleanups (*note Nonlocal Exits::.)
  621.      that are allowed before signaling an error (with data `"Variable
  622.      binding depth exceeds max-specpdl-size"').
  623.      This limit, with the associated error when it is exceeded, is one
  624.      way that Lisp avoids infinite recursion on an ill-defined function.
  625.      The default value is 600.
  626. File: elisp,  Node: Void Variables,  Next: Defining Variables,  Prev: Local Variables,  Up: Variables
  627. When a Variable is "Void"
  628. =========================
  629.    If you have never given a symbol any value as a global variable, we
  630. say that that symbol's global value is "void".  In other words, the
  631. symbol's value cell does not have any Lisp object in it.  If you try to
  632. evaluate the symbol, you get a `void-variable' error rather than a
  633. value.
  634.    Note that a value of `nil' is not the same as void.  The symbol
  635. `nil' is a Lisp object and can be the value of a variable just as any
  636. other object can be; but it is *a value*.  A void variable does not
  637. have any value.
  638.    After you have given a variable a value, you can make it void once
  639. more using `makunbound'.
  640.  -- Function: makunbound SYMBOL
  641.      This function makes the current binding of SYMBOL void.  This
  642.      causes any future attempt to use this symbol as a variable to
  643.      signal the error `void-variable', unless or until you set it again.
  644.      `makunbound' returns SYMBOL.
  645.           (makunbound 'x)          ; Make the global value of `x' void.
  646.                => x
  647.           x
  648.           error--> Symbol's value as variable is void: x
  649.      If SYMBOL is locally bound, `makunbound' affects the most local
  650.      existing binding.  This is the only way a symbol can have a void
  651.      local binding, since all the constructs that create local bindings
  652.      create them with values.  In this case, the voidness lasts at most
  653.      as long as the binding does; when the binding is removed due to
  654.      exit from the construct that made it, the previous or global
  655.      binding is reexposed as usual, and the variable is no longer void
  656.      unless the newly reexposed binding was void all along.
  657.           (setq x 1)               ; Put a value in the global binding.
  658.                => 1
  659.           (let ((x 2))             ; Locally bind it.
  660.             (makunbound 'x)        ; Void the local binding.
  661.             x)
  662.           error--> Symbol's value as variable is void: x
  663.           x                        ; The global binding is unchanged.
  664.                => 1
  665.           
  666.           (let ((x 2))             ; Locally bind it.
  667.             (let ((x 3))           ; And again.
  668.               (makunbound 'x)      ; Void the innermost-local binding.
  669.               x))                  ; And refer: it's void.
  670.           error--> Symbol's value as variable is void: x
  671.           
  672.           (let ((x 2))
  673.             (let ((x 3))
  674.               (makunbound 'x))     ; Void inner binding, then remove it.
  675.             x)                     ; Now outer `let' binding is visible.
  676.                => 2
  677.    A variable that has been made void with `makunbound' is
  678. indistinguishable from one that has never received a value and has
  679. always been void.
  680.    You can use the function `boundp' to test whether a variable is
  681. currently void.
  682.  -- Function: boundp VARIABLE
  683.      `boundp' returns `t' if VARIABLE (a symbol) is not void; more
  684.      precisely, if its current binding is not void.  It returns `nil'
  685.      otherwise.
  686.           (boundp 'abracadabra)                ; Starts out void.
  687.                => nil
  688.           (let ((abracadabra 5))               ; Locally bind it.
  689.             (boundp 'abracadabra))
  690.                => t
  691.           (boundp 'abracadabra)                ; Still globally void.
  692.                => nil
  693.           (setq abracadabra 5)                 ; Make it globally nonvoid.
  694.                => 5
  695.           (boundp 'abracadabra)
  696.                => t
  697. File: elisp,  Node: Defining Variables,  Next: Accessing Variables,  Prev: Void Variables,  Up: Variables
  698. Defining Global Variables
  699. =========================
  700.    You may announce your intention to use a symbol as a global variable
  701. with a definition, using `defconst' or `defvar'.
  702.    In Emacs Lisp, definitions serve three purposes.  First, they inform
  703. the user who reads the code that certain symbols are *intended* to be
  704. used as variables.  Second, they inform the Lisp system of these things,
  705. supplying a value and documentation.  Third, they provide information to
  706. utilities such as `etags' and `make-docfile', which create data bases
  707. of the functions and variables in a program.
  708.    The difference between `defconst' and `defvar' is primarily a matter
  709. of intent, serving to inform human readers of whether programs will
  710. change the variable.  Emacs Lisp does not restrict the ways in which a
  711. variable can be used based on `defconst' or `defvar' declarations. 
  712. However, it also makes a difference for initialization: `defconst'
  713. unconditionally initializes the variable, while `defvar' initializes it
  714. only if it is void.
  715.    One would expect user option variables to be defined with
  716. `defconst', since programs do not change them.  Unfortunately, this has
  717. bad results if the definition is in a library that is not preloaded:
  718. `defconst' would override any prior value when the library is loaded. 
  719. Users would like to be able to set the option in their init files, and
  720. override the default value given in the definition.  For this reason,
  721. user options must be defined with `defvar'.
  722.  -- Special Form: defvar SYMBOL [VALUE [DOC-STRING]]
  723.      This special form informs a person reading your code that SYMBOL
  724.      will be used as a variable that the programs are likely to set or
  725.      change.  It is also used for all user option variables except in
  726.      the preloaded parts of Emacs.  Note that SYMBOL is not evaluated;
  727.      the symbol to be defined must appear explicitly in the `defvar'.
  728.      If SYMBOL already has a value (i.e., it is not void), VALUE is not
  729.      even evaluated, and SYMBOL's value remains unchanged.  If SYMBOL
  730.      is void and VALUE is specified, it is evaluated and SYMBOL is set
  731.      to the result.  (If VALUE is not specified, the value of SYMBOL is
  732.      not changed in any case.)
  733.      If the DOC-STRING argument appears, it specifies the documentation
  734.      for the variable.  (This opportunity to specify documentation is
  735.      one of the main benefits of defining the variable.)  The
  736.      documentation is stored in the symbol's `variable-documentation'
  737.      property.  The Emacs help functions (*note Documentation::.) look
  738.      for this property.
  739.      If the first character of DOC-STRING is `*', it means that this
  740.      variable is considered to be a user option.  This affects commands
  741.      such as `set-variable' and `edit-options'.
  742.      For example, this form defines `foo' but does not set its value:
  743.           (defvar foo)
  744.                => foo
  745.      The following example sets the value of `bar' to `23', and gives
  746.      it a documentation string:
  747.           (defvar bar 23 "The normal weight of a bar.")
  748.                => bar
  749.      The following form changes the documentation string for `bar',
  750.      making it a user option, but does not change the value, since `bar'
  751.      already has a value.  (The addition `(1+ 23)' is not even
  752.      performed.)
  753.           (defvar bar (1+ 23) "*The normal weight of a bar.")
  754.                => bar
  755.           bar
  756.                => 23
  757.      Here is an equivalent expression for the `defvar' special form:
  758.           (defvar SYMBOL VALUE DOC-STRING)
  759.           ==
  760.           (progn
  761.             (if (not (boundp 'SYMBOL))
  762.                 (setq SYMBOL VALUE))
  763.             (put 'SYMBOL 'variable-documentation 'DOC-STRING)
  764.             'SYMBOL)
  765.      The `defvar' form returns SYMBOL, but it is normally used at top
  766.      level in a file where its value does not matter.
  767.  -- Special Form: defconst SYMBOL [VALUE [DOC-STRING]]
  768.      This special form informs a person reading your code that SYMBOL
  769.      has a global value, established here, that will not normally be
  770.      changed or locally bound by the execution of the program.  The
  771.      user, however, may be welcome to change it.  Note that SYMBOL is
  772.      not evaluated; the symbol to be defined must appear explicitly in
  773.      the `defconst'.
  774.      `defconst' always evaluates VALUE and sets the global value of
  775.      SYMBOL to the result, provided VALUE is given.
  776.      *Note:* don't use `defconst' for user option variables in
  777.      libraries that are not normally loaded.  The user should be able to
  778.      specify a value for such a variable in the `.emacs' file, so that
  779.      it will be in effect if and when the library is loaded later.
  780.      Here, `pi' is a constant that presumably ought not to be changed
  781.      by anyone (attempts by the Indiana State Legislature
  782.      notwithstanding). As the second form illustrates, however, this is
  783.      only advisory.
  784.           (defconst pi 3 "Pi to one place.")
  785.                => pi
  786.           (setq pi 4)
  787.                => pi
  788.           pi
  789.                => 4
  790.  -- Function: user-variable-p VARIABLE
  791.      This function returns `t' if VARIABLE is a user option, intended
  792.      to be set by the user for customization, `nil' otherwise.
  793.      (Variables other than user options exist for the internal purposes
  794.      of Lisp programs, and users need not know about them.)
  795.      User option variables are distinguished from other variables by the
  796.      first character of the `variable-documentation' property.  If the
  797.      property exists and is a string, and its first character is `*',
  798.      then the variable is a user option.
  799.    Note that if the `defconst' and `defvar' special forms are used
  800. while the variable has a local binding, the local binding's value is
  801. set, and the global binding is not changed.  This would be confusing.
  802. But the normal way to use these special forms is at top level in a file,
  803. where no local binding should be in effect.
  804. File: elisp,  Node: Accessing Variables,  Next: Setting Variables,  Prev: Defining Variables,  Up: Variables
  805. Accessing Variable Values
  806. =========================
  807.    The usual way to reference a variable is to write the symbol which
  808. names it (*note Symbol Forms::.).  This requires you to specify the
  809. variable name when you write the program.  Usually that is exactly what
  810. you want to do.  Occasionally you need to choose at run time which
  811. variable to reference; then you can use `symbol-value'.
  812.  -- Function: symbol-value SYMBOL
  813.      This function returns the value of SYMBOL.  This is the value in
  814.      the innermost local binding of the symbol, or its global value if
  815.      it has no local bindings.
  816.           (setq abracadabra 5)
  817.                => 5
  818.           (setq foo 9)
  819.                => 9
  820.           
  821.           ;; Here the symbol `abracadabra'
  822.           ;; is the symbol whose value is examined.
  823.           (let ((abracadabra 'foo))
  824.             (symbol-value 'abracadabra))
  825.                => foo
  826.           
  827.           ;; Here the value of `abracadabra',
  828.           ;; which is `foo',
  829.           ;; is the symbol whose value is examined.
  830.           (let ((abracadabra 'foo))
  831.             (symbol-value abracadabra))
  832.                => 9
  833.           
  834.           (symbol-value 'abracadabra)
  835.                => 5
  836.      A `void-variable' error is signaled if SYMBOL has neither a local
  837.      binding nor a global value.
  838. File: elisp,  Node: Setting Variables,  Next: Variable Scoping,  Prev: Accessing Variables,  Up: Variables
  839. How to Alter a Variable Value
  840. =============================
  841.    The usual way to change the value of a variable is with the special
  842. form `setq'.  When you need to compute the choice of variable at run
  843. time, use the function `set'.
  844.  -- Special Form: setq [SYMBOL FORM]...
  845.      This special form is the most common method of changing a
  846.      variable's value.  Each SYMBOL is given a new value, which is the
  847.      result of evaluating the corresponding FORM.  The most-local
  848.      existing binding of the symbol is changed.
  849.      The value of the `setq' form is the value of the last FORM.
  850.           (setq x (1+ 2))
  851.                => 3
  852.           x                     ; `x' now has a global value.
  853.                => 3
  854.           (let ((x 5))
  855.             (setq x 6)          ; The local binding of `x' is set.
  856.             x)
  857.                => 6
  858.           x                     ; The global value is unchanged.
  859.                => 3
  860.      Note that the first FORM is evaluated, then the first SYMBOL is
  861.      set, then the second FORM is evaluated, then the second SYMBOL is
  862.      set, and so on:
  863.           (setq x 10            ; Notice that `x' is set
  864.                 y (1+ x))       ; before the value of `y' is computed.
  865.                => 11
  866.  -- Function: set SYMBOL VALUE
  867.      This function sets SYMBOL's value to VALUE, then returns VALUE. 
  868.      Since `set' is a function, the expression written for SYMBOL is
  869.      evaluated to obtain the symbol to be set.
  870.      The most-local existing binding of the variable is the binding
  871.      that is set; shadowed bindings are not affected.  If SYMBOL is not
  872.      actually a symbol, a `wrong-type-argument' error is signaled.
  873.           (set one 1)
  874.           error--> Symbol's value as variable is void: one
  875.           (set 'one 1)
  876.                => 1
  877.           (set 'two 'one)
  878.                => one
  879.           (set two 2)            ; `two' evaluates to symbol `one'.
  880.                => 2
  881.           one                    ; So it is `one' that was set.
  882.                => 2
  883.           (let ((one 1))         ; This binding of `one' is set,
  884.             (set 'one 3)         ; not the global value.
  885.             one)
  886.                => 3
  887.           one
  888.                => 2
  889.      Logically speaking, `set' is a more fundamental primitive that
  890.      `setq'.  Any use of `setq' can be trivially rewritten to use
  891.      `set'; `setq' could even be defined as a macro, given the
  892.      availability of `set'.  However, `set' itself is rarely used;
  893.      beginners hardly need to know about it.  It is needed only when the
  894.      choice of variable to be set is made at run time.  For example, the
  895.      command `set-variable', which reads a variable name from the user
  896.      and then sets the variable, needs to use `set'.
  897.           Common Lisp note: in Common Lisp, `set' always changes the
  898.           symbol's special value, ignoring any lexical bindings.  In
  899.           Emacs Lisp, all variables and all bindings are special, so
  900.           `set' always affects the most local existing binding.
  901. File: elisp,  Node: Variable Scoping,  Next: Buffer-Local Variables,  Prev: Setting Variables,  Up: Variables
  902. Scoping Rules for Variable Bindings
  903. ===================================
  904.    A given symbol `foo' may have several local variable bindings,
  905. established at different places in the Lisp program, as well as a global
  906. binding.  The most recently established binding takes precedence over
  907. the others.
  908.    Local bindings in Emacs Lisp have "indefinite scope" and "dynamic
  909. extent".  "Scope" refers to *where* textually in the source code the
  910. binding can be accessed.  Indefinite scope means that any part of the
  911. program can potentially access the variable binding.  "Extent" refers
  912. to *when*, as the program is executing, the binding exists.  Dynamic
  913. extent means that the binding lasts as long as the activation of the
  914. construct that established it.
  915.    The combination of dynamic extent and indefinite scope is called
  916. "dynamic scoping".  By contrast, most programming languages use
  917. "lexical scoping", in which references to a local variable must be
  918. textually within the function or block that binds the variable.
  919.      Common Lisp note: variables declared "special" in Common Lisp are
  920.      dynamically scoped like variables in Emacs Lisp.
  921. * Menu:
  922. * Scope::          Scope means where in the program a value is visible.
  923.                      Comparison with other languages.
  924. * Extent::         Extent means how long in time a value exists.
  925. * Impl of Scope::  Two ways to implement dynamic scoping.
  926. * Using Scoping::  How to use dynamic scoping carefully and avoid problems.
  927.