home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / unix / info / elisp.i05 (.txt) < prev    next >
GNU Info File  |  1993-06-14  |  52KB  |  980 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: Symbol Components,  Next: Definitions,  Prev: Symbols,  Up: Symbols
  21. Symbol Components
  22. =================
  23.    Each symbol has four components (or "cells"), each of which
  24. references another object:
  25. Print name
  26.      The "print name cell" holds a string which names the symbol for
  27.      reading and printing.  See `symbol-name' in *Note Creating
  28.      Symbols::.
  29. Value
  30.      The "value cell" holds the current value of the symbol as a
  31.      variable.  When a symbol is used as a form, the value of the form
  32.      is the contents of the symbol's value cell.  See `symbol-value' in
  33.      *Note Accessing Variables::.
  34. Function
  35.      The "function cell" holds the function definition of the symbol.
  36.      When a symbol is used as a function, its function definition is
  37.      used in its place.  This cell is also used by the editor command
  38.      loop to record keymaps and keyboard macros.  Because each symbol
  39.      has separate value and function cells, variables and function
  40.      names do not conflict.  See `symbol-function' in *Note Function
  41.      Cells::.
  42. Property list
  43.      The "property list cell" holds the property list of the symbol. 
  44.      See `symbol-plist' in *Note Property Lists::.
  45.    The print name cell always holds a string, and cannot be changed. 
  46. The other three cells can be set individually to any specified Lisp
  47. object.
  48.    The print name cell holds the string that is the name of the symbol.
  49. Since symbols are represented textually by their names, it is important
  50. not to have two symbols with the same name.  The Lisp reader ensures
  51. this: every time it reads a symbol, it looks for an existing symbol with
  52. the specified name before it creates a new one.  (In GNU Emacs Lisp,
  53. this is done with a hashing algorithm that uses an obarray; see *Note
  54. Creating Symbols::.)
  55.    In normal usage, the function cell usually contains a function or
  56. macro, as that is what the Lisp interpreter expects to see there (*note
  57. Evaluation::.).  Keyboard macros (*note Keyboard Macros::.), keymaps
  58. (*note Keymaps::.) and autoload objects (*note Autoloading::.) are also
  59. sometimes stored in the function cell of symbols.  We often refer to
  60. "the function `foo'" when we really mean the function stored in the
  61. function cell of the symbol `foo'.  The distinction will be made only
  62. when necessary.
  63.    Similarly, the property list cell normally holds a correctly
  64. formatted property list (*note Property Lists::.), as a number of
  65. functions will expect to see a property list there.
  66.    The function cell or the value cell may be "void", which means that
  67. the cell does not reference any object.  (This is not the same thing as
  68. holding the symbol `void', nor the same as holding the symbol `nil'.) 
  69. Examining the value of a cell which is void results in an error, such
  70. as `Symbol's value as variable is void'.
  71.    The four functions `symbol-name', `symbol-value', `symbol-plist',
  72. and `symbol-function' return the contents of the four cells.  Here as
  73. an example we show the contents of the four cells of the symbol
  74. `buffer-file-name':
  75.      (symbol-name 'buffer-file-name)
  76.           => "buffer-file-name"
  77.      (symbol-value 'buffer-file-name)
  78.           => "/gnu/elisp/symbols.texi"
  79.      (symbol-plist 'buffer-file-name)
  80.           => (variable-documentation 29529)
  81.      (symbol-function 'buffer-file-name)
  82.           => #<subr buffer-file-name>
  83. Because this symbol is the variable which holds the name of the file
  84. being visited in the current buffer, the value cell contents we see are
  85. the name of the source file of this chapter of the Emacs Lisp Manual.
  86. The property list cell contains the list `(variable-documentation
  87. 29529)' which tells the documentation functions where to find
  88. documentation about `buffer-file-name' in the `DOC' file. (29529 is the
  89. offset from the beginning of the `DOC' file where the documentation for
  90. the function begins.)  The function cell contains the function for
  91. returning the name of the file.  Since `buffer-file-name' is a
  92. primitive function, its function definition has no read syntax and
  93. prints in hash notation (*note Primitive Function Type::.).  A function
  94. definition written in Lisp will have a lambda expression (or byte-code)
  95. in this cell.
  96. File: elisp,  Node: Definitions,  Next: Creating Symbols,  Prev: Symbol Components,  Up: Symbols
  97. Defining Symbols
  98. ================
  99.    A "definition" in Lisp is a special form that announces your
  100. intention to use a certain symbol in a particular way.  In Emacs Lisp,
  101. you can define a symbol as a variable, or define it as a function (or
  102. macro), or both independently.
  103.    A definition construct typically specifies a value or meaning for the
  104. symbol for one kind of use, plus documentation for its meaning when used
  105. in this way.  Thus, when you define a symbol as a variable, you can
  106. supply an initial value for the variable, plus documentation for the
  107. variable.
  108.    `defvar' and `defconst' are definitions that establish a symbol as a
  109. global variable.  They are documented in detail in *Note Defining
  110. Variables::.
  111.    `defun' defines a symbol as a function, creating a lambda expression
  112. and storing it in the function cell of the symbol.  This lambda
  113. expression thus becomes the function definition of the symbol. (The
  114. term "function definition", meaning the contents of the function cell,
  115. is derived from the idea that `defun' gives the symbol its definition
  116. as a function.)  *Note Functions::.
  117.    `defmacro' defines a symbol as a macro.  It creates a macro object
  118. and stores it in the function cell of the symbol.  Note that a given
  119. symbol can be a macro or a function, but not both at once, because both
  120. macro and function definitions are kept in the function cell, and that
  121. cell can hold only one Lisp object at any given time. *Note Macros::.
  122.    In GNU Emacs Lisp, a definition is not required in order to use a
  123. symbol as a variable or function.  Thus, you can make a symbol a global
  124. variable with `setq', whether you define it first or not.  The real
  125. purpose of definitions is to guide programmers and programming tools.
  126. They inform programmers who read the code that certain symbols are
  127. *intended* to be used as variables, or as functions.  In addition,
  128. utilities such as `etags' and `make-docfile' can recognize definitions,
  129. and add the appropriate information to tag tables and the
  130. `emacs/etc/DOC-VERSION' file. *Note Accessing Documentation::.
  131. File: elisp,  Node: Creating Symbols,  Next: Property Lists,  Prev: Definitions,  Up: Symbols
  132. Creating and Interning Symbols
  133. ==============================
  134.    To understand how symbols are created in GNU Emacs Lisp, it is
  135. necessary to know how Lisp reads them.  It is essential to ensure that
  136. every time Lisp reads the same set of characters, it finds the same
  137. symbol. Failure to do so would be disastrous.
  138.    When the Lisp reader encounters a symbol, it reads all the characters
  139. of the name.  Then it "hashes" those characters to find an index in a
  140. table called an "obarray".  Hashing is an efficient method of looking
  141. something up.  For example, instead of searching a telephone book cover
  142. to cover when looking up Jan Jones, you start with the J's and go from
  143. there.  That is a simple version of hashing.  Each element of the
  144. obarray is a "bucket" which holds all the symbols with a given hash
  145. code; to look for a given name, it is sufficient to look through all
  146. the symbols in the bucket for that name's hash code.
  147.    If a symbol with the desired name is found, then it is used.  If no
  148. such symbol is found, then a new symbol is created and added to the
  149. obarray bucket.  Adding a symbol to an obarray is called "interning"
  150. it, and the symbol is then called an "interned symbol".  In Emacs Lisp,
  151. a symbol may be interned in only one obarray.
  152.      Common Lisp note: in Common Lisp, a symbol may be interned in
  153.      several obarrays at once.
  154.    If a symbol is not in the obarray, then there is no way for Lisp to
  155. find it when its name is read.  Such a symbol is called an "uninterned
  156. symbol" relative to the obarray.  An uninterned symbol has all the
  157. other characteristics of symbols.  It is possible, though uncommon, for
  158. two different symbols to have the same name in different obarrays; they
  159. are not `eq' or `equal'.
  160.    In Emacs Lisp, an obarray is represented as a vector.  Each element
  161. of the vector is a bucket; its value is either an interned symbol whose
  162. name hashes to that bucket, or 0 if the bucket is empty.  Each interned
  163. symbol has an internal link (invisible to the user) to the next symbol
  164. in the bucket.  Because these links are invisible, there is no way to
  165. scan the symbols in an obarray except using `mapatoms' (below). The
  166. order of symbols in a bucket is not significant.
  167.    In an empty obarray, every element is 0, and you can create an
  168. obarray with `(make-vector LENGTH 0)'.  Prime numbers as lengths tend
  169. to result in good hashing; lengths one less than a power of two are also
  170. good.
  171.    Most of the functions below take a name and sometimes an obarray as
  172. arguments.  A `wrong-type-argument' error is signaled if the name is
  173. not a string, or if the obarray is not a vector.
  174.  -- Function: symbol-name SYMBOL
  175.      This function returns the string that is SYMBOL's name.  For
  176.      example:
  177.           (symbol-name 'foo)
  178.                => "foo"
  179.      Changing the string by substituting characters, etc, will change
  180.      the name of the symbol, but will fail to update the obarray, so
  181.      don't do it!
  182.  -- Function: make-symbol NAME
  183.      This function returns a newly-allocated uninterned symbol whose
  184.      name is NAME (which must be a string).  Its value and function
  185.      definition are void, and its property list is `nil'.  In the
  186.      example below, the value of `sym' is not `eq' to `foo' because it
  187.      is a distinct uninterned symbol whose name is also `foo'.
  188.           (setq sym (make-symbol "foo"))
  189.                => foo
  190.           (eq sym 'foo)
  191.                => nil
  192.  -- Function: intern NAME &optional OBARRAY
  193.      This function returns the interned symbol whose name is NAME.  If
  194.      there is no such symbol in the obarray, a new one is created,
  195.      added to the obarray, and returned.  If OBARRAY is supplied, it
  196.      specifies the obarray to use; otherwise, the value of the global
  197.      variable `obarray' is used.
  198.           (setq sym (intern "foo"))
  199.                => foo
  200.           (eq sym 'foo)
  201.                => t
  202.  -- Function: intern-soft NAME &optional OBARRAY
  203.      This function returns the symbol whose name is NAME, or `nil' if a
  204.      symbol with that name is not found in the obarray.  Therefore, you
  205.      can use `intern-soft' to test whether a symbol with a given name is
  206.      interned.  If OBARRAY is supplied, it specifies the obarray to
  207.      use; otherwise the value of the global variable `obarray' is used.
  208.           (intern-soft "frazzle")                ; No such symbol exists.
  209.                => nil
  210.           (make-symbol "frazzle")                ; Create an uninterned one.
  211.                => frazzle
  212.           (intern-soft "frazzle")                ; That one cannot be found.
  213.                => nil
  214.           (setq sym (intern "frazzle"))          ; Create an interned one.
  215.                => frazzle
  216.           (intern-soft "frazzle")                ; That one can be found!
  217.                => frazzle
  218.           (eq sym 'frazzle)                      ; And it is the same one.
  219.                => t
  220.  -- Variable: obarray
  221.      This variable is the standard obarray for use by `intern' and
  222.      `read'.
  223.  -- Function: mapatoms FUNCTION &optional OBARRAY
  224.      This function applies FUNCTION to every symbol in OBARRAY. It
  225.      returns `nil'.  If OBARRAY is not supplied, it defaults to the
  226.      value of `obarray', the standard obarray for ordinary symbols.
  227.           (setq count 0)
  228.                => 0
  229.           (defun count-syms (s)
  230.             (setq count (1+ count)))
  231.                => count-syms
  232.           (mapatoms 'count-syms)
  233.                => nil
  234.           count
  235.                => 1871
  236.      See `documentation' in *Note Accessing Documentation::, for another
  237.      example using `mapatoms'.
  238. File: elisp,  Node: Property Lists,  Prev: Creating Symbols,  Up: Symbols
  239. Property Lists
  240. ==============
  241.    A "property list" ("plist" for short) is a list of paired elements
  242. stored in the property list cell of a symbol.  Each of the pairs
  243. associates a property name (usually a symbol) with a property or value.
  244.  Property lists are generally used to record information about a
  245. symbol, such as how to compile it, the name of the file where it was
  246. defined, or perhaps even the grammatical class of the symbol
  247. (representing a word) in a language understanding system.
  248.    The property names and property values may be any Lisp objects, but
  249. the names are usually symbols.  They are compared using `eq'.  Here is
  250. an example of a property list, found on the symbol `progn' when the
  251. compiler is loaded:
  252.      (lisp-indent-hook 0 byte-compile byte-compile-progn)
  253. Here `lisp-indent-hook' and `byte-compile' are property names, and the
  254. other two elements are the corresponding values.
  255.    Association lists (*note Association Lists::.) are very similar to
  256. property lists.  In contrast to association lists, the order of the
  257. pairs in the property list is not significant since the property names
  258. must be distinct.
  259.    Property lists are better than association lists when it is necessary
  260. to attach information to various Lisp function names or variables.  If
  261. all the pairs are recorded in one association list, it will be necessary
  262. to search that entire list each time a function or variable is to be
  263. operated on.  By contrast, if the information is recorded in the
  264. property lists of the function names or variables themselves, each
  265. search will scan only the length of one property list, which is usually
  266. short.  For this reason, the documentation for a variable is recorded in
  267. a property named `variable-documentation'.  The byte compiler likewise
  268. uses properties to record those functions needing special treatment.
  269.    However, association lists have their own advantages.  Depending on
  270. your application, it may be faster to add an association to the front of
  271. an association list than to update a property.  All properties for a
  272. symbol are stored in the same property list, so there is a possibility
  273. of a conflict between different uses of a property name.  (For this
  274. reason, it is a good idea to use property names that are probably
  275. unique, such as by including the name of the library in the property
  276. name.)  An association list may be used like a stack where associations
  277. are pushed on the front of the list and later discarded; this is not
  278. possible with a property list.
  279.  -- Function: symbol-plist SYMBOL
  280.      This function returns the property list of SYMBOL.
  281.  -- Function: setplist SYMBOL PLIST
  282.      This function sets SYMBOL's property list to PLIST. Normally,
  283.      PLIST should be a well-formed property list, but this is not
  284.      enforced.
  285.           (setplist 'foo '(a 1 b (2 3) c nil))
  286.                => (a 1 b (2 3) c nil)
  287.           (symbol-plist 'foo)
  288.                => (a 1 b (2 3) c nil)
  289.      For symbols in special obarrays, which are not used for ordinary
  290.      purposes, it may make sense to use the property list cell in a
  291.      nonstandard fashion; in fact, the abbrev mechanism does so (*note
  292.      Abbrevs::.).
  293.  -- Function: get SYMBOL PROPERTY
  294.      This function finds the value of the property named PROPERTY in
  295.      SYMBOL's property list.  If there is no such property, `nil' is
  296.      returned.  Thus, there is no distinction between a value of `nil'
  297.      and the absence of the property.
  298.      The name PROPERTY is compared with the existing property names
  299.      using `eq', so any object is a legitimate property.
  300.      See `put' for an example.
  301.  -- Function: put SYMBOL PROPERTY VALUE
  302.      This function puts VALUE onto SYMBOL's property list under the
  303.      property name PROPERTY, replacing any previous value.
  304.           (put 'fly 'verb 'transitive)
  305.                =>'transitive
  306.           (put 'fly 'noun '(a buzzing little bug))
  307.                => (a buzzing little bug)
  308.           (get 'fly 'verb)
  309.                => transitive
  310.           (symbol-plist 'fly)
  311.                => (verb transitive noun (a buzzing little bug))
  312. File: elisp,  Node: Evaluation,  Next: Control Structures,  Prev: Symbols,  Up: Top
  313. Evaluation
  314. **********
  315.    The "evaluation" of expressions in Emacs Lisp is performed by the
  316. "Lisp interpreter"--a program that receives a Lisp object as input and
  317. computes its "value as an expression".  The value is computed in a
  318. fashion that depends on the data type of the object, following rules
  319. described in this chapter.  The interpreter runs automatically to
  320. evaluate portions of your program, but can also be called explicitly
  321. via the Lisp primitive function `eval'.
  322. * Menu:
  323. * Intro Eval::  Evaluation in the scheme of things.
  324. * Eval::        How to invoke the Lisp interpreter explicitly.
  325. * Forms::       How various sorts of objects are evaluated.
  326. * Quoting::     Avoiding evaluation (to put constants in the program).
  327. File: elisp,  Node: Intro Eval,  Next: Eval,  Prev: Evaluation,  Up: Evaluation
  328. Introduction to Evaluation
  329. ==========================
  330.    The Lisp interpreter, or evaluator, is the program which computes
  331. the value of an expression which is given to it.  When a function
  332. written in Lisp is called, the evaluator computes the value of the
  333. function by evaluating the expressions in the function body.  Thus,
  334. running any Lisp program really means running the Lisp interpreter.
  335.    How the evaluator handles an object depends primarily on the data
  336. type of the object.
  337.    A Lisp object which is intended for evaluation is called an
  338. "expression" or a "form".  The fact that expressions are data objects
  339. and not merely text is one of the fundamental differences between
  340. Lisp-like languages and typical programming languages.  Any object can
  341. be evaluated, but in practice only numbers, symbols, lists and strings
  342. are evaluated very often.
  343.    It is very common to read a Lisp expression and then evaluate the
  344. expression, but reading and evaluation are separate activities, and
  345. either can be performed alone.  Reading per se does not evaluate
  346. anything; it converts the printed representation of a Lisp object to the
  347. object itself.  It is up to the caller of `read' whether this object is
  348. a form to be evaluated, or serves some entirely different purpose. 
  349. *Note Input Functions::.
  350.    Do not confuse evaluation with command key interpretation.  The
  351. editor command loop translates keyboard input into a command (an
  352. interactively callable function) using the current keymaps, and then
  353. uses `call-interactively' to invoke the command.  The execution of the
  354. command itself involves evaluation if the command is written in Lisp,
  355. but that is not a part of command key interpretation itself. *Note
  356. Command Loop::.
  357.    Evaluation is a recursive process.  That is, evaluation of a form may
  358. cause `eval' to be called again in order to evaluate parts of the form.
  359.  For example, evaluation of a function call first evaluates each
  360. argument of the function call, and then evaluates each form in the
  361. function body.  Consider evaluation of the form `(car x)': the subform
  362. `x' must first be evaluated recursively, so that its value can be
  363. passed as an argument to the function `car'.
  364.    The evaluation of forms takes place in a context called the
  365. "environment", which consists of the current values and bindings of all
  366. Lisp variables.  Whenever the form refers to a variable without
  367. creating a new binding for it, the value of the current binding is used.
  368. *Note Variables::.
  369.    Evaluation of a form may create new environments for recursive
  370. evaluation by binding variables (*note Local Variables::.).  These
  371. environments are temporary and will be gone by the time evaluation of
  372. the form is complete.  The form may also make changes that persist;
  373. these changes are called "side-effects".  An example of a form that
  374. produces side-effects is `(setq foo 1)'.
  375.    Finally, evaluation of one particular function call, `byte-code',
  376. invokes the "byte-code interpreter" on its arguments.  Although the
  377. byte-code interpreter is not the same as the Lisp interpreter, it uses
  378. the same environment as the Lisp interpreter, and may on occasion invoke
  379. the Lisp interpreter.  (*Note Byte Compilation::.)
  380.    The details of what evaluation means for each kind of form are
  381. described below (*note Forms::.).
  382. File: elisp,  Node: Eval,  Next: Forms,  Prev: Intro Eval,  Up: Evaluation
  383.    Most often, forms are evaluated automatically, by virtue of their
  384. occurrence in a program being run.  On rare occasions, you may need to
  385. write code that evaluates a form that is computed at run time, such as
  386. when the form is read from text being edited or found on a property
  387. list.  On these occasions, use the `eval' function.
  388.    The functions and variables described in this section evaluate
  389. forms, specify limits to the evaluation process, or record recently
  390. returned values.  Evaluation is also performed by `load' (*note
  391. Loading::.).
  392.  -- Function: eval FORM
  393.      This is the basic function for performing evaluation.  It evaluates
  394.      FORM in the current environment and returns the result.  How the
  395.      evaluation proceeds depends on the type of the object (*note
  396.      Forms::.).
  397.      Since `eval' is a function, the argument expression that appears
  398.      in a call to `eval' is evaluated twice: once as preparation before
  399.      `eval' is called, and again by the `eval' function itself. Here is
  400.      an example:
  401.           (setq foo 'bar)
  402.                => bar
  403.           (setq bar 'baz)
  404.                => baz
  405.           ;; `eval' is called on the form `bar', which is the value of `foo'
  406.           (eval foo)
  407.                => baz
  408.      The number of currently active calls to `eval' is limited to
  409.      `max-lisp-eval-depth'.
  410.  -- Command: eval-current-buffer &optional STREAM
  411.      This function evaluates the forms in the current buffer.  It reads
  412.      forms from the buffer and calls `eval' on them until the end of the
  413.      buffer is reached, or until an error is signaled and not handled.
  414.      If STREAM is supplied, the variable `standard-output' is bound to
  415.      STREAM during the evaluation (*note Output Functions::.).
  416.      `eval-current-buffer' always returns `nil'.
  417.  -- Command: eval-region START END &optional STREAM
  418.      This function evaluates the forms in the current buffer in the
  419.      region defined by the positions START and END.  It reads forms from
  420.      the region and calls `eval' on them until the end of the region is
  421.      reached, or until an error is signaled and not handled.
  422.      If STREAM is supplied, `standard-output' is bound to it for the
  423.      duration of the command.
  424.      `eval-region' always returns `nil'.
  425.  -- Variable: max-lisp-eval-depth
  426.      This variable defines the maximum depth allowed in calls to
  427.      `eval', `apply', and `funcall' before an error is signaled (with
  428.      error message `"Lisp nesting exceeds max-lisp-eval-depth"'). 
  429.      `eval' is called recursively to evaluate the arguments of Lisp
  430.      function calls and to evaluate bodies of functions.
  431.      This limit, with the associated error when it is exceeded, is one
  432.      way that Lisp avoids infinite recursion on an ill-defined function.
  433.      The default value of this variable is 200.  If you set it to a
  434.      value less than 100, Lisp will reset it to 100 if the given value
  435.      is reached.
  436.  -- Variable: values
  437.      The value of this variable is a list of values returned by all
  438.      expressions which were read from buffers (including the
  439.      minibuffer), evaluated, and printed.  The elements are in order,
  440.      most recent first.
  441.           (setq x 1)
  442.                => 1
  443.           (list 'A (1+ 2) auto-save-default)
  444.                => (A 3 t)
  445.           values
  446.                => ((A 3 t) 1 ...)
  447.      This variable is useful for referring back to values of forms
  448.      recently evaluated.  It is generally a bad idea to print the value
  449.      of `values' itself, since this may be very long.  Instead, examine
  450.      particular elements, like this:
  451.           ;; Refer to the most recent evaluation result.
  452.           (nth 0 values)
  453.                => (A 3 t)
  454.           ;; That put a new element on, so all elements move back one.
  455.           (nth 1 values)
  456.                => (A 3 t)
  457.           ;; This gets the element that was next-to-last before this example.
  458.           (nth 3 values)
  459.                => 1
  460. File: elisp,  Node: Forms,  Next: Quoting,  Prev: Eval,  Up: Evaluation
  461. Kinds of Forms
  462. ==============
  463.    A Lisp object that is intended to be evaluated is called a "form".
  464. How Emacs evaluates a form depends on its data type.  Emacs has three
  465. different kinds of form that are evaluated differently: symbols, lists,
  466. and "all other types".  All three kinds are described in this section,
  467. starting with "all other types" which are self-evaluating forms.
  468. * Menu:
  469. * Self-Evaluating Forms::   Forms that evaluate to themselves.
  470. * Symbol Forms::            Symbols evaluate as variables.
  471. * Classifying Lists::       How to distinguish various sorts of list forms.
  472. * Function Forms::          Forms that call functions.
  473. * Macro Forms::             Forms that call macros.
  474. * Special Forms::           "Special forms" are idiosyncratic primitives,
  475.                               most of them extremely important.
  476. * Autoloading::             Functions set up to load files
  477.                               containing their real definitions.
  478. File: elisp,  Node: Self-Evaluating Forms,  Next: Symbol Forms,  Prev: Forms,  Up: Forms
  479. Self-Evaluating Forms
  480. ---------------------
  481.    A "self-evaluating form" is any form that is not a list or symbol.
  482. Self-evaluating forms evaluate to themselves: the result of evaluation
  483. is the same object that was evaluated.  Thus, the number 25 evaluates to
  484. 25, and the string `"foo"' evaluates to the string `"foo"'. Likewise,
  485. evaluation of a vector does not cause evaluation of the elements of the
  486. vector--it returns the same vector with its contents unchanged.
  487.      '123               ; An object, shown without evaluation.
  488.           => 123
  489.      123                ; Evaluated as usual---result is the same.
  490.           => 123
  491.      (eval '123)        ; Evaluated ``by hand''---result is the same.
  492.           => 123
  493.      (eval (eval '123)) ; Evaluating twice changes nothing.
  494.           => 123
  495.    It is common to write numbers, characters, strings, and even vectors
  496. in Lisp code, taking advantage of the fact that they self-evaluate.
  497. However, it is quite unusual to do this for types that lack a read
  498. syntax, because it is inconvenient and not very useful; however, it is
  499. possible to put them inside Lisp programs when they are constructed
  500. from subexpressions rather than read.  Here is an example:
  501.      ;; Build such an expression.
  502.      (setq buffer (list 'print (current-buffer)))
  503.           => (print #<buffer eval.texi>)
  504.      ;; Evaluate it.
  505.      (eval buffer)
  506.           -| #<buffer eval.texi>
  507.           => #<buffer eval.texi>
  508. File: elisp,  Node: Symbol Forms,  Next: Classifying Lists,  Prev: Self-Evaluating Forms,  Up: Forms
  509. Symbol Forms
  510. ------------
  511.    When a symbol is evaluated, it is treated as a variable.  The result
  512. is the variable's value, if it has one.  If it has none (if its value
  513. cell is void), an error is signaled.  For more information on the use of
  514. variables, see *Note Variables::.
  515.    In the following example, the value of a symbol is set with `setq'. 
  516. When the symbol is later evaluated, that value is returned.
  517.      (setq a 123)
  518.           => 123
  519.      (eval 'a)
  520.           => 123
  521.      a
  522.           => 123
  523.    The symbols `nil' and `t' are treated specially, so that the value
  524. of `nil' is always `nil', and the value of `t' is always `t'.  Thus,
  525. these two symbols act like self-evaluating forms, even though `eval'
  526. treats them like any other symbol.
  527. File: elisp,  Node: Classifying Lists,  Next: Function Forms,  Prev: Symbol Forms,  Up: Forms
  528. Classification of List Forms
  529. ----------------------------
  530.    A form that is a nonempty list is either a function call, a macro
  531. call, or a special form, according to its first element.  These three
  532. kinds of forms are evaluated in different ways, described below.  The
  533. rest of the list consists of "arguments" for the function, macro or
  534. special form.
  535.    The first step in evaluating a nonempty list is to examine its first
  536. element.  This element alone determines what kind of form the list is
  537. and how the rest of the list is to be processed.  The first element is
  538. *not* evaluated, as it would be in some Lisp dialects including Scheme.
  539.    If the first element of the list is a symbol, as it most commonly is,
  540. then the symbol's function cell is examined, and its contents are used
  541. instead of the original symbol.  If the contents are another symbol,
  542. this process, called "symbol function indirection", is repeated until a
  543. non-symbol is obtained.
  544.    One possible consequence of this process is an infinite loop, in the
  545. event that a symbol's function cell refers to the same symbol.  Or a
  546. symbol may have a void function cell, causing a `void-function' error. 
  547. But if neither of these things happens, we eventually obtain a
  548. non-symbol, which ought to be a function or other suitable object.
  549.    More precisely, we should now have a Lisp function (a lambda
  550. expression), a primitive function, a Lisp macro, a special form, or an
  551. autoload object.  Each of these types is a case described in one of the
  552. following sections.  If the object is not one of these types, the error
  553. `invalid-function' is signaled.
  554.    The following example illustrates the symbol indirection process.  We
  555. use `fset' to set the function cell of a symbol and `symbol-function'
  556. to get the function cell contents (*note Function Cells::.). 
  557. Specifically, we store the symbol `car' into the function cell of
  558. `first', and the symbol `first' into the function cell of `erste'.
  559.      ;; Build this function cell linkage:
  560.      ;;    -------------       -----        -------        -------
  561.      ;;   | #<subr car> | <-- | car |  <-- | first |  <-- | erste |
  562.      ;;    -------------       -----        -------        -------
  563.      
  564.      (symbol-function 'car)
  565.           => #<subr car>
  566.      (fset 'first 'car)
  567.           => car
  568.      (fset 'erste 'first)
  569.           => first
  570.      (erste '(1 2 3))           ; Call the function referenced by `erste'.
  571.           => 1
  572.    By contrast, the following example calls a function without any
  573. symbol function indirection, because the first element is an anonymous
  574. Lisp function, not a symbol.
  575.      ((lambda (arg) (erste arg))
  576.       '(1 2 3))
  577.           => 1
  578. After that function is called, its body is evaluated; this does involve
  579. symbol function indirection when calling `erste'.
  580. File: elisp,  Node: Function Forms,  Next: Macro Forms,  Prev: Classifying Lists,  Up: Forms
  581. Evaluation of Function Forms
  582. ----------------------------
  583.    If the first element of a list being evaluated is a Lisp function
  584. object or primitive function object, then that list is a "function
  585. call".  For example, here is a call to the function `+':
  586.      (+ 1 x)
  587.    When a function call is evaluated, the first step is to evaluate the
  588. remaining elements of the list in the order they appear.  The results
  589. are the actual argument values, one argument from each element.  Then
  590. the function is called with this list of arguments, effectively using
  591. the function `apply' (*note Calling Functions::.).  If the function is
  592. written in Lisp, the arguments are used to bind the argument variables
  593. of the function (*note Lambda Expressions::.); then the forms in the
  594. function body are evaluated in order, and the result of the last one is
  595. used as the value of the function call.
  596. File: elisp,  Node: Macro Forms,  Next: Special Forms,  Prev: Function Forms,  Up: Forms
  597. Lisp Macro Evaluation
  598. ---------------------
  599.    If the first element of a list being evaluated is a macro object,
  600. then the list is a "macro call".  When a macro call is evaluated, the
  601. elements of the rest of the list are *not* initially evaluated.
  602. Instead, these elements themselves are used as the arguments of the
  603. macro.  The macro definition computes a replacement form, called the
  604. "expansion" of the macro, which is evaluated in place of the original
  605. form.  The expansion may be any sort of form: a self-evaluating
  606. constant, a symbol or a list.  If the expansion is itself a macro call,
  607. this process of expansion repeats until some other sort of form results.
  608.    Normally, the argument expressions are not evaluated as part of
  609. computing the macro expansion, but instead appear as part of the
  610. expansion, so they are evaluated when the expansion is evaluated.
  611.    For example, given a macro defined as follows:
  612.      (defmacro cadr (x)
  613.        (list 'car (list 'cdr x)))
  614. an expression such as `(cadr (assq 'handler list))' is a macro call,
  615. and its expansion is:
  616.      (car (cdr (assq 'handler list)))
  617. Note that the argument `(assq 'handler list)' appears in the expansion.
  618.    *Note Macros::, for a complete description of Emacs Lisp macros.
  619. File: elisp,  Node: Special Forms,  Next: Autoloading,  Prev: Macro Forms,  Up: Forms
  620. Special Forms
  621. -------------
  622.    A "special form" is a primitive function specially marked so that
  623. its arguments are not all evaluated.  Special forms define control
  624. structures or perform variable bindings--things which functions cannot
  625.    Each special form has its own rules for which arguments are evaluated
  626. and which are used without evaluation.  Whether a particular argument is
  627. evaluated may depend on the results of evaluating other arguments.
  628.    Here is a list, in alphabetical order, of all of the special forms in
  629. Emacs Lisp with a reference to where each is described.
  630. `and'
  631.      *note Combining Conditions::.
  632. `catch'
  633.      *note Catch and Throw::.
  634. `cond'
  635.      *note Conditionals::.
  636. `condition-case'
  637.      *note Errors::.
  638. `defconst'
  639.      *note Defining Variables::.
  640. `defmacro'
  641.      *note Defining Macros::.
  642. `defun'
  643.      *note Defining Functions::.
  644. `defvar'
  645.      *note Defining Variables::.
  646. `function'
  647.      *note Anonymous Functions::.
  648.      *note Conditionals::.
  649. `interactive'
  650.      *note Interactive Call::.
  651. `let'
  652.      *note Local Variables::.
  653. `let*'
  654.      *note Local Variables::.
  655.      *note Combining Conditions::.
  656. `prog1'
  657.      *note Sequencing::.
  658. `prog2'
  659.      *note Sequencing::.
  660. `progn'
  661.      *note Sequencing::.
  662. `quote'
  663.      *note Quoting::.
  664. `save-excursion'
  665.      *note Excursions::.
  666. `save-restriction'
  667.      *note Narrowing::.
  668. `save-window-excursion'
  669.      *note Window Configurations::.
  670. `setq'
  671.      *note Setting Variables::.
  672. `setq-default'
  673.      *note Creating Buffer-Local::.
  674. `unwind-protect'
  675.      *note Nonlocal Exits::.
  676. `while'
  677.      *note Iteration::.
  678. `with-output-to-temp-buffer'
  679.      *note Temporary Displays::.
  680.      Common Lisp note: here are some comparisons of special forms in
  681.      GNU Emacs Lisp and Common Lisp.  `setq', `if', and `catch' are
  682.      special forms in both Emacs Lisp and Common Lisp. `defun' is a
  683.      special form in Emacs Lisp, but a macro in Common Lisp. 
  684.      `save-excursion' is a special form in Emacs Lisp, but doesn't
  685.      exist in Common Lisp.  `throw' is a special form in Common Lisp
  686.      (because it must be able to throw multiple values), but it is a
  687.      function in Emacs Lisp (which doesn't have multiple values).
  688. File: elisp,  Node: Autoloading,  Prev: Special Forms,  Up: Forms
  689. Autoloading
  690. -----------
  691.    The "autoload" feature allows you to call a function or macro whose
  692. function definition has not yet been loaded into Emacs.  When an
  693. autoload object appears as a symbol's function definition and that
  694. symbol is used as a function, Emacs will automatically install the real
  695. definition (plus other associated code) and then call that definition.
  696. (*Note Autoload::.)
  697. File: elisp,  Node: Quoting,  Prev: Forms,  Up: Evaluation
  698. Quoting
  699. =======
  700.    The special form `quote' returns its single argument "unchanged".
  701.  -- Special Form: quote OBJECT
  702.      This special form returns OBJECT, without evaluating it.  This
  703.      allows symbols and lists, which would normally be evaluated, to be
  704.      included literally in a program.  (It is not necessary to quote
  705.      numbers, strings, and vectors since they are self-evaluating.)  Use
  706.      `function' instead of `quote' when quoting lambda expressions
  707.      (*note Anonymous Functions::.).
  708.      Because `quote' is used so often in programs, a convenient read
  709.      syntax is defined for it.  An apostrophe character (`'') followed
  710.      by a Lisp object (in read syntax) expands to a list whose first
  711.      element is `quote', and whose second element is the object.  Thus,
  712.      the read syntax `'x' is an abbreviation for `(quote x)'.
  713.      Here are some examples of expressions that use `quote':
  714.           (quote (+ 1 2))
  715.                => (+ 1 2)
  716.           (quote foo)
  717.                => foo
  718.           'foo
  719.                => foo
  720.           ''foo
  721.                => (quote foo)
  722.           '(quote foo)
  723.                => (quote foo)
  724.           ['foo]
  725.                => [(quote foo)]
  726. File: elisp,  Node: Control Structures,  Next: Variables,  Prev: Evaluation,  Up: Top
  727. Control Structures
  728. ******************
  729.    A Lisp program consists of expressions or "forms" (*note Forms::.).
  730. We control the order of execution of the forms by enclosing them in
  731. "control structures".  Control structures are special forms which
  732. control when, whether, or how many times to execute the forms they
  733. contain.
  734.    The simplest control structure is sequential execution: first form
  735. A, then form B, and so on.  This is what happens when you write several
  736. forms in succession in the body of a function, or at top level in a
  737. file of Lisp code--the forms are executed in the order they are
  738. written.  We call this "textual order".  For example, if a function
  739. body consists of two forms A and B, evaluation of the function
  740. evaluates first A and then B, and the function's value is the value of
  741.    Naturally, Emacs Lisp has many kinds of control structures, including
  742. other varieties of sequencing, function calls, conditionals, iteration,
  743. and (controlled) jumps.  The built-in control structures are special
  744. forms since their subforms are not necessarily evaluated.  You can use
  745. macros to define your own control structure constructs (*note
  746. Macros::.).
  747. * Menu:
  748. * Sequencing::             Evaluation in textual order.
  749. * Conditionals::           `if', `cond'.
  750. * Combining Conditions::   `and', `or', `not'.
  751. * Iteration::              `while' loops.
  752. * Nonlocal Exits::         Jumping out of a sequence.
  753. File: elisp,  Node: Sequencing,  Next: Conditionals,  Prev: Control Structures,  Up: Control Structures
  754. Sequencing
  755. ==========
  756.    Evaluating forms in the order they are written is the most common
  757. control structure.  Sometimes this happens automatically, such as in a
  758. function body.  Elsewhere you must use a control structure construct to
  759. do this: `progn', the simplest control construct of Lisp.
  760.    A `progn' special form looks like this:
  761.      (progn A B C ...)
  762. and it says to execute the forms A, B, C and so on, in that order. 
  763. These forms are called the body of the `progn' form. The value of the
  764. last form in the body becomes the value of the entire `progn'.
  765.    When Lisp was young, `progn' was the only way to execute two or more
  766. forms in succession and use the value of the last of them.  But
  767. programmers found they often needed to use a `progn' in the body of a
  768. function, where (at that time) only one form was allowed.  So the body
  769. of a function was made into an "implicit `progn'": several forms are
  770. allowed just as in the body of an actual `progn'.  Many other control
  771. structures likewise contain an implicit `progn'.  As a result, `progn'
  772. is not used as often as it used to be.  It is needed now most often
  773. inside of an `unwind-protect', `and', or `or'.
  774.  -- Special Form: progn FORMS...
  775.      This special form evaluates all of the FORMS, in textual order,
  776.      returning the result of the final form.
  777.           (progn (print "The first form")
  778.                  (print "The second form")
  779.                  (print "The third form"))
  780.                -| "The first form"
  781.                -| "The second form"
  782.                -| "The third form"
  783.           => "The third form"
  784.    Two other control constructs likewise evaluate a series of forms but
  785. return a different value:
  786.  -- Special Form: prog1 FORM1 FORMS...
  787.      This special form evaluates FORM1 and all of the FORMS, in textual
  788.      order, returning the result of FORM1.
  789.           (prog1 (print "The first form")
  790.                  (print "The second form")
  791.                  (print "The third form"))
  792.                -| "The first form"
  793.                -| "The second form"
  794.                -| "The third form"
  795.           => "The first form"
  796.      Here is a way to remove the first element from a list in the
  797.      variable `x', then return the value of that former element:
  798.           (prog1 (car x) (setq x (cdr x)))
  799.  -- Special Form: prog2 FORM1 FORM2 FORMS...
  800.      This special form evaluates FORM1, FORM2, and all of the following
  801.      FORMS, in textual order, returning the result of FORM2.
  802.           (prog2 (print "The first form")
  803.                  (print "The second form")
  804.                  (print "The third form"))
  805.                -| "The first form"
  806.                -| "The second form"
  807.                -| "The third form"
  808.           => "The second form"
  809. File: elisp,  Node: Conditionals,  Next: Combining Conditions,  Prev: Sequencing,  Up: Control Structures
  810. Conditionals
  811. ============
  812.    Conditional control structures choose among alternatives.  Emacs Lisp
  813. has two conditional forms: `if', which is much the same as in other
  814. languages, and `cond', which is a generalized case statement.
  815.  -- Special Form: if CONDITION THEN-FORM ELSE-FORMS...
  816.      `if' chooses between the THEN-FORM and the ELSE-FORMS based on the
  817.      value of CONDITION.  If the evaluated CONDITION is non-`nil',
  818.      THEN-FORM is evaluated and the result returned. Otherwise, the
  819.      ELSE-FORMS are evaluated in textual order, and the value of the
  820.      last one is returned.  (The ELSE part of `if' is an example of an
  821.      implicit `progn'.  *Note Sequencing::.)
  822.      If CONDITION has the value `nil', and no ELSE-FORMS are given,
  823.      `if' returns `nil'.
  824.      `if' is a special form because the branch which is not selected is
  825.      never evaluated--it is ignored.  Thus, in the example below,
  826.      `true' is not printed because `print' is never called.
  827.           (if nil
  828.               (print 'true)
  829.             'very-false)
  830.           => very-false
  831.  -- Special Form: cond CLAUSE...
  832.      `cond' chooses among an arbitrary number of alternatives.  Each
  833.      CLAUSE in the `cond' must be a list.  The CAR of this list is the
  834.      CONDITION; the remaining elements, if any, the BODY-FORMS.  Thus,
  835.      a clause looks like this:
  836.           (CONDITION BODY-FORMS...)
  837.      `cond' tries the clauses in textual order, by evaluating the
  838.      CONDITION of each clause.  If the value of CONDITION is non-`nil',
  839.      the BODY-FORMS are evaluated, and the value of the last of
  840.      BODY-FORMS becomes the value of the `cond'.  The remaining clauses
  841.      are ignored.
  842.      If the value of CONDITION is `nil', the clause "fails", so the
  843.      `cond' moves on to the following clause, trying its CONDITION.
  844.      If every CONDITION evaluates to `nil', so that every clause fails,
  845.      `cond' returns `nil'.
  846.      A clause may also look like this:
  847.           (CONDITION)
  848.      Then, if CONDITION is non-`nil' when tested, the value of
  849.      CONDITION becomes the value of the `cond' form.
  850.      The following example has four clauses, which test for the cases
  851.      where the value of `x' is a number, string, buffer and symbol,
  852.      respectively:
  853.           (cond ((numberp x) x)
  854.                  ((stringp x) x)
  855.                  ((bufferp x)
  856.                   (setq temporary-hack x) ; multiple body-forms
  857.                   (buffer-name x))        ; in one clause
  858.                  ((symbolp x) (symbol-value x)))
  859.      Often we want the last clause to be executed whenever none of the
  860.      previous clauses was successful.  To do this, we use `t' as the
  861.      CONDITION of the last clause, like this: `(t BODY-FORMS)'.  The
  862.      form `t' evaluates to `t', which is never `nil', so this clause
  863.      never fails, provided the `cond' gets to it at all.
  864.      For example,
  865.           (cond ((eq a 1) 'foo)
  866.                 (t "default"))
  867.           => "default"
  868.      This expression is a `cond' which returns `foo' if the value of
  869.      `a' is 1, and returns the string `"default"' otherwise.
  870.    Both `cond' and `if' can usually be written in terms of the other. 
  871. Therefore, the choice between them is a matter of taste and style.  For
  872. example:
  873.      (if A B C)
  874.      ==
  875.      (cond (A B) (t C))
  876. File: elisp,  Node: Combining Conditions,  Next: Iteration,  Prev: Conditionals,  Up: Control Structures
  877. Constructs for Combining Conditions
  878. ===================================
  879.    This section describes three constructs that are often used together
  880. with `if' and `cond' to express complicated conditions.  The constructs
  881. `and' and `or' can also be used individually as kinds of multiple
  882. conditional constructs.
  883.  -- Function: not CONDITION
  884.      This function tests for the falsehood of CONDITION.  It returns
  885.      `t' if CONDITION is `nil', and `nil' otherwise. The function `not'
  886.      is identical to `null', and we recommend using `null' if you are
  887.      testing for an empty list.
  888.  -- Special Form: and CONDITIONS...
  889.      The `and' special form tests whether all the CONDITIONS are true. 
  890.      It works by evaluating the CONDITIONS one by one in the order
  891.      written.
  892.      If any of the CONDITIONS evaluates to `nil', then the result of
  893.      the `and' must be `nil' regardless of the remaining CONDITIONS; so
  894.      the remaining CONDITIONS are ignored and the `and' returns right
  895.      away.
  896.      If all the CONDITIONS turn out non-`nil', then the value of the
  897.      last of them becomes the value of the `and' form.
  898.      Here is an example.  The first condition returns the integer 1,
  899.      which is not `nil'.  Similarly, the second condition returns the
  900.      integer 2, which is not `nil'.  The third condition is `nil', so
  901.      the remaining condition is never evaluated.
  902.           (and (print 1) (print 2) nil (print 3))
  903.                -| 1
  904.                -| 2
  905.           => nil
  906.      Here is a more realistic example of using `and':
  907.           (if (and (consp foo) (eq (car foo) 'x))
  908.               (message "foo is a list starting with x"))
  909.      Note that `(car foo)' is not executed if `(consp foo)' returns
  910.      `nil', thus avoiding an error.
  911.      `and' can be expressed in terms of either `if' or `cond'. For
  912.      example:
  913.           (and ARG1 ARG2 ARG3)
  914.           ==
  915.           (if ARG1 (if ARG2 ARG3))
  916.           ==
  917.           (cond (ARG1 (cond (ARG2 ARG3))))
  918.  -- Special Form: or CONDITIONS...
  919.      The `or' special form tests whether at least one of the CONDITIONS
  920.      is true.  It works by evaluating all the CONDITIONS one by one in
  921.      the order written.
  922.      If any of the CONDITIONS evaluates to a non-`nil' value, then the
  923.      result of the `or' must be non-`nil'; so the remaining CONDITIONS
  924.      are ignored and the `or' returns right away.  The value it returns
  925.      is the non-`nil' value of the condition just evaluated.
  926.      If all the CONDITIONS turn out `nil', then the `or' expression
  927.      returns `nil'.
  928.      For example, this expression tests whether `x' is either 0 or
  929.      `nil':
  930.           (or (eq x nil) (= x 0))
  931.      Like the `and' construct, `or' can be written in terms of `cond'. 
  932.      For example:
  933.           (or ARG1 ARG2 ARG3)
  934.           ==
  935.           (cond (ARG1)
  936.                 (ARG2)
  937.                 (ARG3))
  938.      You could almost write `or' in terms of `if', but not quite:
  939.           (if ARG1 ARG1
  940.             (if ARG2 ARG2
  941.               ARG3))
  942.      This is not completely equivalent because it can evaluate ARG1 or
  943.      ARG2 twice.  By contrast, `(or ARG1 ARG2 ARG3)' never evaluates
  944.      any argument more than once.
  945. File: elisp,  Node: Iteration,  Next: Nonlocal Exits,  Prev: Combining Conditions,  Up: Control Structures
  946. Iteration
  947. =========
  948.    Iteration means executing part of a program repetitively.  For
  949. example, you might want to repeat some expressions once for each
  950. element of a list, or once for each integer from 0 to N.  You can do
  951. this in Emacs Lisp with the special form `while':
  952.  -- Special Form: while CONDITION FORMS...
  953.      `while' first evaluates CONDITION.  If the result is non-`nil', it
  954.      evaluates FORMS in textual order.  Then it reevaluates CONDITION,
  955.      and if the result is non-`nil', it evaluates FORMS again.  This
  956.      process repeats until CONDITION evaluates to `nil'.
  957.      There is no limit on the number of iterations that may occur.  The
  958.      loop will continue until either CONDITION evaluates to `nil' or
  959.      until an error or `throw' jumps out of it (*note Nonlocal
  960.      Exits::.).
  961.      The value of a `while' form is always `nil'.
  962.           (setq num 0)
  963.                => 0
  964.           (while (< num 4)
  965.             (princ (format "Iteration %d." num))
  966.             (setq num (1+ num)))
  967.                -| Iteration 0.
  968.                -| Iteration 1.
  969.                -| Iteration 2.
  970.                -| Iteration 3.
  971.                => nil
  972.      If you would like to execute something on each iteration before the
  973.      end-test, put it together with the end-test in a `progn' as the
  974.      first argument of `while', as shown here:
  975.           (while (progn
  976.                    (forward-line 1)
  977.                    (not (looking-at "^$"))))
  978.      This moves forward one line and continues moving by lines until an
  979.      empty line is reached.
  980.