home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / unix / info / elisp.i07 (.txt) < prev    next >
GNU Info File  |  1993-06-14  |  52KB  |  953 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: Scope,  Next: Extent,  Prev: Variable Scoping,  Up: Variable Scoping
  21. Scope
  22. -----
  23.    Emacs Lisp uses "indefinite scope" for local variable bindings. This
  24. means that any function anywhere in the program text might access a
  25. given binding of a variable.  Consider the following function
  26. definitions:
  27.      (defun binder (x)  ; `x' is bound in `binder'.
  28.         (foo 5))        ; `foo' is some other function.
  29.      
  30.      (defun user ()     ; `x' is used in `user'.
  31.        (list x))
  32.    In a lexically scoped language, the binding of `x' from `binder'
  33. would never be accessible in `user', because `user' is not textually
  34. contained within the function `binder'.  However, in dynamically scoped
  35. Emacs Lisp, `user' may or may not refer to the binding of `x'
  36. established in `binder', depending on circumstances:
  37.    * If we call `user' directly without calling `binder' at all, then
  38.      whatever binding of `x' is found, it cannot come from `binder'.
  39.    * If we define `foo' as follows and call `binder', then the binding
  40.      made in `binder' will be seen in `user':
  41.           (defun foo (lose)
  42.             (user))
  43.    * If we define `foo' as follows and call `binder', then the binding
  44.      made in `binder' *will not* be seen in `user':
  45.           (defun foo (x)
  46.             (user))
  47.      Here, when `foo' is called by `binder', it binds `x'. (The binding
  48.      in `foo' is said to "shadow" the one made in `binder'.) 
  49.      Therefore, `user' will access the `x' bound by `foo' instead of
  50.      the one bound by `binder'.
  51. File: elisp,  Node: Extent,  Next: Impl of Scope,  Prev: Scope,  Up: Variable Scoping
  52. Extent
  53. ------
  54.    "Extent" refers to the time during program execution that a variable
  55. name is valid.  In Emacs Lisp, a variable is valid only while the form
  56. that bound it is executing.  This is called "dynamic extent".  "Local"
  57. or "automatic" variables in most languages, including C and Pascal,
  58. have dynamic extent.
  59.    One alternative to dynamic extent is "indefinite extent".  This
  60. means that a variable binding can live on past the exit from the form
  61. that made the binding.  Common Lisp and Scheme, for example, support
  62. this, but Emacs Lisp does not.
  63.    To illustrate this, the function below, `make-add', returns a
  64. function that purports to add N to its own argument M. This would work
  65. in Common Lisp, but it does not work as intended in Emacs Lisp, because
  66. after the call to `make-add' exits, the variable `n' is no longer bound
  67. to the actual argument 2.
  68.      (defun make-add (n)
  69.          (function (lambda (m) (+ n m))))  ; Return a function.
  70.           => make-add
  71.      (fset 'add2 (make-add 2))  ; Define function `add2' with `(make-add 2)'.
  72.           => (lambda (m) (+ n m))
  73.      (add2 4)                   ; Try to add 2 to 4.
  74.      error--> Symbol's value as variable is void: n
  75. File: elisp,  Node: Impl of Scope,  Next: Using Scoping,  Prev: Extent,  Up: Variable Scoping
  76. Implementation of Dynamic Scoping
  77. ---------------------------------
  78.    A simple sample implementation (which is not how Emacs Lisp actually
  79. works) may help you understand dynamic binding.  This technique is
  80. called "deep binding" and was used in early Lisp systems.
  81.    Suppose there is a stack of bindings: variable-value pairs.  At entry
  82. to a function or to a `let' form, we can push bindings on the stack for
  83. the arguments or local variables created there.  We can pop those
  84. bindings from the stack at exit from the binding construct.
  85.    We can find the value of a variable by searching the stack from top
  86. to bottom for a binding for that variable; the value from that binding
  87. is the value of the variable.  To set the variable, we search for the
  88. current binding, then store the new value into that binding.
  89.    As you can see, a function's bindings remain in effect as long as it
  90. continues execution, even during its calls to other functions.  That is
  91. why we say the extent of the binding is dynamic.  And any other function
  92. can refer to the bindings, if it uses the same variables while the
  93. bindings are in effect.  That is why we say the scope is indefinite.
  94.    The actual implementation of variable scoping in GNU Emacs Lisp uses
  95. a technique called "shallow binding".  Each variable has a standard
  96. place in which its current value is always found--the value cell of the
  97. symbol.
  98.    In shallow binding, setting the variable works by storing a value in
  99. the value cell.  When a new local binding is created, the local value is
  100. stored in the value cell, and the old value (belonging to a previous
  101. binding) is pushed on a stack.  When a binding is eliminated, the old
  102. value is popped off the stack and stored in the value cell.
  103.    We use shallow binding because it has the same results as deep
  104. binding, but runs faster, since there is never a need to search for a
  105. binding.
  106. File: elisp,  Node: Using Scoping,  Prev: Impl of Scope,  Up: Variable Scoping
  107. Proper Use of Dynamic Scoping
  108. -----------------------------
  109.    Binding a variable in one function and using it in another is a
  110. powerful technique, but if used without restraint, it can make programs
  111. hard to understand.  There are two clean ways to use this technique:
  112.    * Use or bind the variable only in a few related functions, written
  113.      close together in one file.  Such a variable is used for
  114.      communication within one program.
  115.      You should write comments to inform other programmers that they
  116.      can see all uses of the variable before them, and to advise them
  117.      not to add uses elsewhere.
  118.    * Give the variable a well-defined, documented meaning, and make all
  119.      appropriate functions refer to it (but not bind it or set it)
  120.      wherever that meaning is relevant.  For example, the variable
  121.      `case-fold-search' is defined as "non-`nil' means ignore case when
  122.      searching"; various search and replace functions refer to it
  123.      directly or through their subroutines, but do not bind or set it.
  124.      Then you can bind the variable in other programs, knowing reliably
  125.      what the effect will be.
  126. File: elisp,  Node: Buffer-Local Variables,  Prev: Variable Scoping,  Up: Variables
  127. Buffer-Local Variables
  128. ======================
  129.    Global and local variable bindings are found in most programming
  130. languages in one form or another.  Emacs also supports another, unusual
  131. kind of variable binding: "buffer-local" bindings, which apply only to
  132. one buffer.  Emacs Lisp is meant for programming editing commands, and
  133. having different values for a variable in different buffers is an
  134. important customization method.
  135. * Menu:
  136. * Intro to Buffer-Local::      Introduction and concepts.
  137. * Creating Buffer-Local::      Creating and destroying buffer-local bindings.
  138. * Default Value::              The default value is seen in buffers
  139.                                  that don't have their own local values.
  140. File: elisp,  Node: Intro to Buffer-Local,  Next: Creating Buffer-Local,  Prev: Buffer-Local Variables,  Up: Buffer-Local Variables
  141. Introduction to Buffer-Local Variables
  142. --------------------------------------
  143.    A buffer-local variable has a buffer-local binding associated with a
  144. particular buffer.  The binding is in effect when that buffer is
  145. current; otherwise, it is not in effect.  If you set the variable while
  146. a buffer-local binding is in effect, the new value goes in that binding,
  147. so the global binding is unchanged; this means that the change is
  148. visible in that buffer alone.
  149.    A variable may have buffer-local bindings in some buffers but not in
  150. others.  The global binding is shared by all the buffers that don't have
  151. their own bindings.  Thus, if you set the variable in a buffer that does
  152. not have a buffer-local binding for it, the new value is visible in all
  153. buffers except those with buffer-local bindings.  (Here we are assuming
  154. that there are no `let'-style local bindings to complicate the issue.)
  155.    The most common use of buffer-local bindings is for major modes to
  156. change variables that control the behavior of commands.  For example, C
  157. mode and Lisp mode both set the variable `paragraph-start' to specify
  158. that only blank lines separate paragraphs.  They do this by making the
  159. variable buffer-local in the buffer that is being put into C mode or
  160. Lisp mode, and then setting it to the new value for that mode.
  161.    The usual way to make a buffer-local binding is with
  162. `make-local-variable', which is what major mode commands use.  This
  163. affects just the current buffer; all other buffers (including those yet
  164. to be created) continue to share the global value.
  165.    A more powerful operation is to mark the variable as "automatically
  166. buffer-local" by calling `make-variable-buffer-local'.  You can think
  167. of this as making the variable local in all buffers, even those yet to
  168. be created.  More precisely, the effect is that setting the variable
  169. automatically makes the variable local to the current buffer if it is
  170. not already so.  All buffers start out by sharing the global value of
  171. the variable as usual, but any `setq' creates a buffer-local binding
  172. for the current buffer.  The new value is stored in the buffer-local
  173. binding, leaving the (default) global binding untouched.  The global
  174. value can no longer be changed with `setq'; you need to use
  175. `setq-default' to do that.
  176.    When a variable has local values in one or more buffers, you can get
  177. Emacs very confused by binding the variable with `let', changing to a
  178. different current buffer in which a different binding is in effect, and
  179. then exiting the `let'.  The best way to preserve your sanity is to
  180. avoid such situations.  If you use `save-excursion' around each piece
  181. of code that changes to a different current buffer, you will not have
  182. this problem.  Here is an example of incorrect code:
  183.      (setq foo 'b)
  184.      (set-buffer "a")
  185.      (make-local-variable 'foo)
  186.      (setq foo 'a)
  187.      (let ((foo 'temp))
  188.        (set-buffer "b")
  189.        ...)
  190.      foo => 'a      ; The old buffer-local value from buffer `a'
  191.                            ; is now the default value.
  192.      (set-buffer "a")
  193.      foo => 'temp   ; The local value that should be gone
  194.                            ; is now the buffer-local value in buffer `a'.
  195. But `save-excursion' as shown here avoids the problem:
  196.      (let ((foo 'temp))
  197.        (save-excursion
  198.          (set-buffer "b")
  199.          ...))
  200.    Local variables in a file you edit are also represented by
  201. buffer-local bindings for the buffer that holds the file within Emacs.
  202. *Note Auto Major Mode::.
  203. File: elisp,  Node: Creating Buffer-Local,  Next: Default Value,  Prev: Intro to Buffer-Local,  Up: Buffer-Local Variables
  204. Creating and Destroying Buffer-local Bindings
  205. ---------------------------------------------
  206.  -- Command: make-local-variable SYMBOL
  207.      This function creates a buffer-local binding for SYMBOL in the
  208.      current buffer.  Other buffers are not affected.  The value
  209.      returned is SYMBOL.
  210.      The buffer-local value of SYMBOL starts out as the same value
  211.      SYMBOL previously had.
  212.           ;; In buffer `b1':
  213.           (setq foo 5)                ; Affects all buffers.
  214.                => 5
  215.           (make-local-variable 'foo)  ; Now it is local in `b1'.
  216.                => foo
  217.           foo                         ; That did not change the value.
  218.                => 5
  219.           (setq foo 6)                ; Change the value in `b1'.
  220.                => 6
  221.           foo
  222.                => 6
  223.           
  224.           ;; In buffer `b2', the value hasn't changed.
  225.           (save-excursion
  226.             (set-buffer "b2")
  227.             foo)
  228.                => 5
  229.  -- Command: make-variable-buffer-local SYMBOL
  230.      This function marks SYMBOL automatically buffer-local, so that any
  231.      attempt to set it will make it local to the current buffer at the
  232.      time.
  233.      The value returned is SYMBOL.
  234.  -- Function: buffer-local-variables &optional BUFFER
  235.      This function tells you what the buffer-local variables are in
  236.      buffer BUFFER.  It returns an association list (*note Association
  237.      Lists::.) in which each association contains one buffer-local
  238.      variable and its value.  If BUFFER is omitted, the current buffer
  239.      is used.
  240.           (setq lcl (buffer-local-variables))
  241.           => ((fill-column . 75)
  242.               (case-fold-search . t)
  243.               ...
  244.               (mark-ring #<marker at 5454 in buffers.texi>)
  245.               (require-final-newline . t))
  246.      Note that storing new values into the CDRs of the elements in this
  247.      list will *not* change the local values of the variables.
  248.  -- Command: kill-local-variable SYMBOL
  249.      This function deletes the buffer-local binding (if any) for SYMBOL
  250.      in the current buffer.  As a result, the global (default) binding
  251.      of SYMBOL becomes visible in this buffer.  Usually this results in
  252.      a change in the value of SYMBOL, since the global value is usually
  253.      different from the buffer-local value just eliminated.
  254.      It is possible to kill the local binding of a variable that
  255.      automatically becomes local when set.  This causes the variable to
  256.      show its global value in the current buffer.  However, if you set
  257.      the variable again, this will once again create a local value.
  258.      `kill-local-variable' returns SYMBOL.
  259.  -- Function: kill-all-local-variables
  260.      This function eliminates all the buffer-local variable bindings of
  261.      the current buffer.  As a result, the buffer will see the default
  262.      values of all variables.  This function also resets certain other
  263.      information pertaining to the buffer: its local keymap is set to
  264.      `nil', its syntax table is set to the value of
  265.      `standard-syntax-table', and its abbrev table is set to the value
  266.      of `fundamental-mode-abbrev-table'.
  267.      Every major mode command begins by calling this function, which
  268.      has the effect of switching to Fundamental mode and erasing most
  269.      of the effects of the previous major mode.
  270.      `kill-all-local-variables' returns `nil'.
  271. File: elisp,  Node: Default Value,  Prev: Creating Buffer-Local,  Up: Buffer-Local Variables
  272. The Default Value of a Buffer-Local Variable
  273. --------------------------------------------
  274.    The global value of a variable with buffer-local bindings is also
  275. called the "default" value, because it is the value that is in effect
  276. except when specifically overridden.
  277.    The functions `default-value' and `setq-default' allow you to access
  278. and change the default value regardless of whether the current buffer
  279. has a buffer-local binding.  For example, you could use `setq-default'
  280. to change the default setting of `paragraph-start' for most buffers;
  281. and this would work even when you are in a C or Lisp mode buffer which
  282. has a buffer-local value for this variable.
  283.  -- Function: default-value SYMBOL
  284.      This function returns SYMBOL's default value.  This is the value
  285.      that is seen in buffers that do not have their own values for this
  286.      variable.  If SYMBOL is not buffer-local, this is equivalent to
  287.      `symbol-value' (*note Accessing Variables::.).
  288.  -- Special Form: setq-default SYMBOL VALUE
  289.      This sets the default value of SYMBOL to VALUE. SYMBOL is not
  290.      evaluated, but VALUE is.  The value of the `setq-default' form is
  291.      VALUE.
  292.      If a SYMBOL is not buffer-local for the current buffer, and is not
  293.      marked automatically buffer-local, this has the same effect as
  294.      `setq'.  If SYMBOL is buffer-local for the current buffer, then
  295.      this changes the value that other buffers will see (as long as they
  296.      don't have a buffer-local value), but not the value that the
  297.      current buffer sees.
  298.           ;; In buffer `foo':
  299.           (make-local-variable 'local)
  300.                => local
  301.           (setq local 'value-in-foo)
  302.                => value-in-foo
  303.           (setq-default local 'new-default)
  304.                => new-default
  305.           local
  306.                => value-in-foo
  307.           (default-value 'local)
  308.                => new-default
  309.           
  310.           ;; In (the new) buffer `bar':
  311.           local
  312.                => new-default
  313.           (default-value 'local)
  314.                => new-default
  315.           (setq local 'another-default)
  316.                => another-default
  317.           (default-value 'local)
  318.                => another-default
  319.           
  320.           ;; Back in buffer `foo':
  321.           local
  322.                => value-in-foo
  323.           (default-value 'local)
  324.                => another-default
  325.  -- Function: set-default SYMBOL VALUE
  326.      This function is like `setq-default', except that SYMBOL is
  327.      evaluated.
  328.           (set-default (car '(a b c)) 23)
  329.                => 23
  330.           (default-value 'a)
  331.                => 23
  332. File: elisp,  Node: Functions,  Next: Macros,  Prev: Variables,  Up: Top
  333. Functions
  334. *********
  335.    A Lisp program is composed mainly of Lisp functions.  This chapter
  336. explains what functions are, how they accept arguments, and how to
  337. define them.
  338. * Menu:
  339. * What Is a Function::    Lisp functions vs primitives; terminology.
  340. * Lambda Expressions::    How functions are expressed as Lisp objects.
  341. * Function Names::        A symbol can serve as the name of a function.
  342. * Defining Functions::    Lisp expressions for defining functions.
  343. * Calling Functions::     How to use an existing function.
  344. * Mapping Functions::     Applying a function to each element of a list, etc.
  345. * Anonymous Functions::   Lambda-expressions are functions with no names.
  346. * Function Cells::        Accessing or setting the function definition
  347.                             of a symbol.
  348. * Related Topics::        Cross-references to specific Lisp primitives
  349.                             that have a special bearing on how functions work.
  350. File: elisp,  Node: What Is a Function,  Next: Lambda Expressions,  Prev: Functions,  Up: Functions
  351. What Is a Function?
  352. ===================
  353.    In a general sense, a function is a rule for carrying on a
  354. computation given several values called "arguments".  The result of the
  355. computation is called the value of the function.  The computation can
  356. also have side effects: lasting changes in the values of variables or
  357. the contents of data structures.
  358.    Here are important terms for functions in Emacs Lisp and for other
  359. function-like objects.
  360. "function"
  361.      In Emacs Lisp, a "function" is anything that can be applied to
  362.      arguments in a Lisp program.  In some cases, we will use it more
  363.      specifically to mean a function written in Lisp.  Special forms and
  364.      macros are not functions.
  365. "primitive"
  366.      A "primitive" is a function callable from Lisp that is written in
  367.      C, such as `car' or `append'.  These functions are also called
  368.      "built-in" functions or "subrs".  (Special forms are also
  369.      considered primitives.)
  370.      Primitives provide the lowest-level interfaces to editing
  371.      functions or operating system services, or in a few cases they
  372.      perform important operations more quickly than a Lisp program
  373.      could.  Primitives can be modified or added only by changing the C
  374.      sources and recompiling the editor.  See *Note Writing Emacs
  375.      Primitives::.
  376. "lambda expression"
  377.      A "lambda expression" is a function written in Lisp. These are
  378.      described in the following section. *Note Lambda Expressions::.
  379. "special form"
  380.      A "special form" is a primitive that is like a function but does
  381.      not evaluate all of its arguments in the usual way.  It may
  382.      evaluate only some of the arguments, or may evaluate them in an
  383.      unusual order, or several times.  Many special forms are described
  384.      in *Note Control Structures::.
  385. "macro"
  386.      A "macro" is a construct defined in Lisp by the programmer.  It
  387.      differs from a function in that it translates a Lisp expression
  388.      that you write into an equivalent expression to be evaluated
  389.      instead of the original expression.  *Note Macros::, for how to
  390.      define and use macros.
  391. "command"
  392.      A "command" is an object that `command-execute' can invoke; it is
  393.      a possible definition for a key sequence.  Some functions are
  394.      commands; a function written in Lisp is a command if it contains an
  395.      interactive declaration (*note Defining Commands::.).  Such a
  396.      function can be called from Lisp expressions like other functions;
  397.      in this case, the fact that the function is a command makes no
  398.      difference.
  399.      Strings are commands also, even though they are not functions.  A
  400.      symbol is a command if its function definition is a command; such
  401.      symbols can be invoked with `M-x'.  The symbol is a function as
  402.      well if the definition is a function.  *Note Command Overview::.
  403. "keystroke command"
  404.      A "keystroke command" is a command that is bound to a key sequence
  405.      (typically one to three keystrokes).  The distinction is made here
  406.      merely to avoid confusion with the meaning of "command" in
  407.      non-Emacs editors; for programmers, the distinction is normally
  408.      unimportant.
  409.  -- Function: subrp OBJECT
  410.      This function returns `t' if OBJECT is a built-in function (i.e. a
  411.      Lisp primitive).
  412.           (subrp 'message)                ; `message' is a symbol,
  413.                => nil                     ; not a subr object.
  414.           (subrp (symbol-function 'message))
  415.                => t
  416. File: elisp,  Node: Lambda Expressions,  Next: Function Names,  Prev: What Is a Function,  Up: Functions
  417. Lambda Expressions
  418. ==================
  419.    A function written in Lisp is a list that looks like this:
  420.      (lambda (ARG-VARIABLES...)
  421.        [DOCUMENTATION-STRING]
  422.        [INTERACTIVE-DECLARATION]
  423.        BODY-FORMS...)
  424. (Such a list is called a "lambda expression", even though it is not an
  425. expression at all, for historical reasons.)
  426. * Menu:
  427. * Lambda Components::       The parts of a lambda expression.
  428. * Simple Lambda::           A simple example.
  429. * Argument List::           Details and special features of argument lists.
  430. * Function Documentation::  How to put documentation in a function.
  431. File: elisp,  Node: Lambda Components,  Next: Simple Lambda,  Prev: Lambda Expressions,  Up: Lambda Expressions
  432. Components of a Lambda Expression
  433. ---------------------------------
  434.    A function written in Lisp (a "lambda expression") is a list that
  435. looks like this:
  436.      (lambda (ARG-VARIABLES...)
  437.        [DOCUMENTATION-STRING]
  438.        [INTERACTIVE-DECLARATION]
  439.        BODY-FORMS...)
  440.    The first element of a lambda expression is always the symbol
  441. `lambda'.  This indicates that the list represents a function.  The
  442. reason functions are defined to start with `lambda' is so that other
  443. lists, intended for other uses, will not accidentally be valid as
  444. functions.
  445.    The second element is a list of argument variable names (symbols).
  446. This is called the "lambda list".  When a Lisp function is called, the
  447. argument values are matched up against the variables in the lambda
  448. list, which are given local bindings with the values provided. *Note
  449. Local Variables::.
  450.    The documentation string is an actual string that serves to describe
  451. the function for the Emacs help facilities.  *Note Function
  452. Documentation::.
  453.    The interactive declaration is a list of the form `(interactive
  454. CODE-STRING)'.  This declares how to provide arguments if the function
  455. is used interactively.  Functions with this declaration are called
  456. "commands"; they can be called using `M-x' or bound to a key. Functions
  457. not intended to be called in this way should not have interactive
  458. declarations.  *Note Defining Commands::, for how to write an
  459. interactive declaration.
  460.    The rest of the elements are the "body" of the function: the Lisp
  461. code to do the work of the function (or, as a Lisp programmer would say,
  462. "a list of Lisp forms to evaluate").  The value returned by the
  463. function is the value returned by the last element of the body.
  464. File: elisp,  Node: Simple Lambda,  Next: Argument List,  Prev: Lambda Components,  Up: Lambda Expressions
  465. A Simple Lambda-Expression Example
  466. ----------------------------------
  467.    Consider for example the following function:
  468.      (lambda (a b c) (+ a b c))
  469. We can call this function by writing it as the CAR of an expression,
  470. like this:
  471.      ((lambda (a b c) (+ a b c))
  472.       1 2 3)
  473. The body of this lambda expression is evaluated with the variable `a'
  474. bound to 1, `b' bound to 2, and `c' bound to 3. Evaluation of the body
  475. adds these three numbers, producing the result 6; therefore, this call
  476. to the function returns the value 6.
  477.    Note that the arguments can be the results of other function calls,
  478. as in this example:
  479.      ((lambda (a b c) (+ a b c))
  480.       1 (* 2 3) (- 5 4))
  481. Here all the arguments `1', `(* 2 3)', and `(- 5 4)' are evaluated,
  482. left to right.  Then the lambda expression is applied to the argument
  483. values 1, 6 and 1 to produce the value 8.
  484.    It is not often useful to write a lambda expression as the CAR of a
  485. form in this way.  You can get the same result, of making local
  486. variables and giving them values, using the special form `let' (*note
  487. Local Variables::.).  And `let' is clearer and easier to use. In
  488. practice, lambda expressions are either stored as the function
  489. definitions of symbols, to produce named functions, or passed as
  490. arguments to other functions (*note Anonymous Functions::.).
  491.    However, calls to explicit lambda expressions were very useful in the
  492. old days of Lisp, before the special form `let' was invented.  At that
  493. time, they were the only way to bind and initialize local variables.
  494. File: elisp,  Node: Argument List,  Next: Function Documentation,  Prev: Simple Lambda,  Up: Lambda Expressions
  495. Advanced Features of Argument Lists
  496. -----------------------------------
  497.    Our simple sample function, `(lambda (a b c) (+ a b c))', specifies
  498. three argument variables, so it must be called with three arguments: if
  499. you try to call it with only two arguments or four arguments, you will
  500. get a `wrong-number-of-arguments' error.
  501.    It is often convenient to write a function that allows certain
  502. arguments to be omitted.  For example, the function `substring' accepts
  503. three arguments--a string, the start index and the end index--but the
  504. third argument defaults to the end of the string if you omit it.  It is
  505. also convenient for certain functions to accept an indefinite number of
  506. arguments, as the functions `and' and `+' do.
  507.    To specify optional arguments that may be omitted when a function is
  508. called, simply include the keyword `&optional' before the optional
  509. arguments.  To specify a list of zero or more extra arguments, include
  510. the keyword `&rest' before one final argument.
  511.    Thus, the complete syntax for an argument list is as follows:
  512.      (REQUIRED-VARS...
  513.       [&optional OPTIONAL-VARS...]
  514.       [&rest REST-VAR])
  515. The square brackets indicate that the `&optional' and `&rest' clauses,
  516. and the variables that follow them, are optional.
  517.    A call to the function requires one actual argument for each of the
  518. REQUIRED-VARS.  There may be actual arguments for zero or more of the
  519. OPTIONAL-VARS, and there cannot be any more actual arguments than these
  520. unless `&rest' exists.  In that case, there may be any number of extra
  521. actual arguments.
  522.    If actual arguments for the optional and rest variables are omitted,
  523. then they always default to `nil'.  However, the body of the function
  524. is free to consider `nil' an abbreviation for some other meaningful
  525. value.  This is what `substring' does; `nil' as the third argument
  526. means to use the length of the string supplied.  There is no way for the
  527. function to distinguish between an explicit argument of `nil' and an
  528. omitted argument.
  529.      Common Lisp note: Common Lisp allows the function to specify what
  530.      default values will be used when an optional argument is omitted;
  531.      GNU Emacs Lisp always uses `nil'.
  532.    For example, an argument list that looks like this:
  533.      (a b &optional c d &rest e)
  534. binds `a' and `b' to the first two actual arguments, which are
  535. required.  If one or two more arguments are provided, `c' and `d' are
  536. bound to them respectively; any arguments after the first four are
  537. collected into a list and `e' is bound to that list.  If there are only
  538. two arguments, `c' is `nil'; if two or three arguments, `d' is `nil';
  539. if four arguments or fewer, `e' is `nil'.
  540.    There is no way to have required arguments following optional
  541. ones--it would not make sense.  To see why this must be so, suppose
  542. that `c' in the example were optional and `d' were required. If three
  543. actual arguments are given; then which variable would the third
  544. argument be for?  Similarly, it makes no sense to have any more
  545. arguments (either required or optional) after a `&rest' argument.
  546.    Here are some examples of argument lists and proper calls:
  547.      ((lambda (n) (1+ n))                ; One required:
  548.       1)                                 ; requires exactly one argument.
  549.           => 2
  550.      ((lambda (n &optional n1)           ; One required and one optional:
  551.               (if n1 (+ n n1) (1+ n)))   ; 1 or 2 arguments.
  552.       1 2)
  553.           => 3
  554.      ((lambda (n &rest ns)               ; One required and one rest:
  555.               (+ n (apply '+ ns)))       ; 1 or more arguments.
  556.       1 2 3 4 5)
  557.           => 15
  558. File: elisp,  Node: Function Documentation,  Prev: Argument List,  Up: Lambda Expressions
  559. Documentation Strings of Functions
  560. ----------------------------------
  561.    A lambda expression may optionally have a "documentation string" just
  562. after the lambda list.  This string does not affect execution of the
  563. function; it is a kind of comment, but a systematized comment which
  564. actually appears inside the Lisp world and can be used by the Emacs help
  565. facilities.  *Note Documentation::, for how the DOCUMENTATION-STRING is
  566. accessed.
  567.    It is a good idea to provide documentation strings for all commands,
  568. and for all other functions in your program that users of your program
  569. should know about; internal functions might as well have only comments,
  570. since comments don't take up any room when your program is loaded.
  571.    The first line of the documentation string should stand on its own,
  572. because `apropos' displays just this first line.  It should consist of
  573. one or two complete sentences that summarize the function's purpose.
  574.    The start of the documentation string is usually indented, but since
  575. these spaces come before the starting double-quote, they are not part of
  576. the string.  Some people make a practice of indenting any additional
  577. lines of the string so that the text lines up.  *This is a mistake.* 
  578. The indentation of the following lines is inside the string; what looks
  579. nice in the source code will look ugly when displayed by the help
  580. commands.
  581.    You may wonder how the documentation string could be optional, since
  582. there are required components of the function that follow it (the body).
  583. Since evaluation of a string returns that string, without any side
  584. effects, it has no effect if it is not the last form in the body. 
  585. Thus, in practice, there is no confusion between the first form of the
  586. body and the documentation string; if the only body form is a string
  587. then it serves both as the return value and as the documentation.
  588. File: elisp,  Node: Function Names,  Next: Defining Functions,  Prev: Lambda Expressions,  Up: Functions
  589. Naming a Function
  590. =================
  591.    In most computer languages, every function has a name; the idea of a
  592. function without a name is nonsensical.  In Lisp, a function in the
  593. strictest sense has no name.  It is simply a list whose first element is
  594. `lambda', or a primitive subr-object.
  595.    However, a symbol can serve as the name of a function.  This happens
  596. when you put the function in the symbol's "function cell" (*note Symbol
  597. Components::.).  Then the symbol itself becomes a valid, callable
  598. function, equivalent to the list or subr-object that its function cell
  599. refers to.  The contents of the function cell are also called the
  600. symbol's "function definition".
  601.    In practice, nearly all functions are given names in this way and
  602. referred to through their names.  For example, the symbol `car' works
  603. as a function and does what it does because the primitive subr-object
  604. `#<subr car>' is stored in its function cell.
  605.    We give functions names because it is more convenient to refer to
  606. them by their names in other functions.  For primitive subr-objects
  607. such as `#<subr car>', names are the only way you can refer to them:
  608. there is no read syntax for such objects.  For functions written in
  609. Lisp, the name is more convenient to use in a call than an explicit
  610. lambda expression.  Also, a function with a name can refer to
  611. itself--it can be recursive.  Writing the function's name in its own
  612. definition is much more convenient than making the function definition
  613. point to itself (something that is not impossible but that has various
  614. disadvantages in practice).
  615.    Functions are often identified with the symbols used to name them. 
  616. For example, we often speak of "the function `car'", not distinguishing
  617. between the symbol `car' and the primitive subr-object that is its
  618. function definition.  For most purposes, there is no need to
  619. distinguish.
  620.    Even so, keep in mind that a function need not have a unique name. 
  621. While a given function object *usually* appears in the function cell of
  622. only one symbol, this is just a matter of convenience.  It is very easy
  623. to store it in several symbols using `fset'; then each of the symbols is
  624. equally well a name for the same function.
  625.    A symbol used as a function name may also be used as a variable;
  626. these two uses of a symbol are independent and do not conflict.
  627. File: elisp,  Node: Defining Functions,  Next: Calling Functions,  Prev: Function Names,  Up: Functions
  628. Defining Named Functions
  629. ========================
  630.    We usually give a name to a function when it is first created.  This
  631. is called "defining a function", and it is done with the `defun'
  632. special form.
  633.  -- Special Form: defun NAME ARGUMENT-LIST BODY-FORMS
  634.      `defun' is the usual way to define new Lisp functions.  It defines
  635.      the symbol NAME as a function that looks like this:
  636.           (lambda ARGUMENT-LIST . BODY-FORMS)
  637.      This lambda expression is stored in the function cell of NAME. The
  638.      value returned by evaluating the `defun' form is NAME, but usually
  639.      we ignore this value.
  640.      As described previously (*note Lambda Expressions::.),
  641.      ARGUMENT-LIST is a list of argument names and may include the
  642.      keywords `&optional' and `&rest'.  Also, the first two forms in
  643.      BODY-FORMS may be a documentation string and an interactive
  644.      declaration.
  645.      Note that the same symbol NAME may also be used as a global
  646.      variable, since the value cell is independent of the function cell.
  647.      Here are some examples:
  648.           (defun foo () 5)
  649.                => foo
  650.           (foo)
  651.                => 5
  652.           
  653.           (defun bar (a &optional b &rest c)
  654.               (list a b c))
  655.                => bar
  656.           (bar 1 2 3 4 5)
  657.                => (1 2 (3 4 5))
  658.           (bar 1)
  659.                => (1 nil nil)
  660.           (bar)
  661.           error--> Wrong number of arguments.
  662.           
  663.           (defun capitalize-backwards ()
  664.             "This function makes the last letter of a word upper case."
  665.             (interactive)
  666.             (backward-word 1)
  667.             (forward-word 1)
  668.             (backward-char 1)
  669.             (capitalize-word 1))
  670.                => capitalize-backwards
  671.      Be careful not to redefine existing functions unintentionally.
  672.      `defun' will redefine even primitive functions such as `car'
  673.      without any hesitation or notification.  Redefining a function
  674.      already defined is often done deliberately, and there is no way to
  675.      distinguish deliberate redefinition from unintentional
  676.      redefinition.
  677. File: elisp,  Node: Calling Functions,  Next: Mapping Functions,  Prev: Defining Functions,  Up: Functions
  678. Calling Functions
  679. =================
  680.    Defining functions is only half the battle.  Functions don't do
  681. anything until you "call" them, i.e., tell them to run.  This process
  682. is also known as "invocation".
  683.    The most common way of invoking a function is by evaluating a list. 
  684. For example, evaluating the list `(concat "a" "b")' calls the function
  685. `concat'.  *Note Evaluation::, for a description of evaluation.
  686.    When you write a list as an expression in your program, the function
  687. name is part of the program.  This means that the choice of which
  688. function to call is made when you write the program.  Usually that's
  689. just what you want.  Occasionally you need to decide at run time which
  690. function to call.  Then you can use the functions `funcall' and `apply'.
  691.  -- Function: funcall FUNCTION &rest ARGUMENTS
  692.      `funcall' calls FUNCTION with ARGUMENTS, and returns whatever
  693.      FUNCTION returns.
  694.      Since `funcall' is a function, all of its arguments, including
  695.      FUNCTION, are evaluated before `funcall' is called.  This means
  696.      that you can use any expression to obtain the function to be
  697.      called.  It also means that `funcall' does not see the expressions
  698.      you write for the ARGUMENTS, only their values.  These values are
  699.      *not* evaluated a second time in the act of calling FUNCTION;
  700.      `funcall' enters the normal procedure for calling a function at the
  701.      place where the arguments have already been evaluated.
  702.      The argument FUNCTION must be either a Lisp function or a
  703.      primitive function.  Special forms and macros are not allowed,
  704.      because they make sense only when given the "unevaluated" argument
  705.      expressions.  `funcall' cannot provide these because, as we saw
  706.      above, it never knows them in the first place.
  707.           (setq f 'list)
  708.                => list
  709.           (funcall f 'x 'y 'z)
  710.                => (x y z)
  711.           (funcall f 'x 'y '(z))
  712.                => (x y (z))
  713.           (funcall 'and t nil)
  714.           error--> Invalid function: #<subr and>
  715.      Compare this example with that of `apply'.
  716.  -- Function: apply FUNCTION &rest ARGUMENTS
  717.      `apply' calls FUNCTION with ARGUMENTS, just like `funcall' but
  718.      with one difference: the last of ARGUMENTS is a list of arguments
  719.      to give to FUNCTION, rather than a single argument.  We also say
  720.      that this list is "appended" to the other arguments.
  721.      `apply' returns the result of calling FUNCTION.  As with
  722.      `funcall', FUNCTION must either be a Lisp function or a primitive
  723.      function; special forms and macros do not make sense in `apply'.
  724.           (setq f 'list)
  725.                => list
  726.           (apply f 'x 'y 'z)
  727.           error--> Wrong type argument: listp, z
  728.           (apply '+ 1 2 '(3 4))
  729.                => 10
  730.           (apply '+ '(1 2 3 4))
  731.                => 10
  732.           
  733.           (apply 'append '((a b c) nil (x y z) nil))
  734.                => (a b c x y z)
  735.      An interesting example of using `apply' is found in the description
  736.      of `mapcar'; see the following section.
  737.    It is common for Lisp functions to accept functions as arguments or
  738. find them in data structures (especially in hook variables and property
  739. lists) and call them using `funcall' or `apply'.  Functions that accept
  740. function arguments are often called "functionals".
  741.    Sometimes, when you call such a function, it is useful to supply a
  742. no-op function as the argument.  Here are two different kinds of no-op
  743. function:
  744.  -- Function: identity ARG
  745.      This function returns ARG and has no side effects.
  746.  -- Function: ignore &rest ARGS
  747.      This function ignores any arguments and returns `nil'.
  748. File: elisp,  Node: Mapping Functions,  Next: Anonymous Functions,  Prev: Calling Functions,  Up: Functions
  749. Mapping Functions
  750. =================
  751.    A "mapping function" applies a given function to each element of a
  752. list or other collection.  Emacs Lisp has three such functions;
  753. `mapcar' and `mapconcat', which scan a list, are described here.  For
  754. the third mapping function, `mapatoms', see *Note Creating Symbols::.
  755.  -- Function: mapcar FUNCTION SEQUENCE
  756.      `mapcar' applies FUNCTION to each element of SEQUENCE in turn. 
  757.      The results are made into a `nil'-terminated list.
  758.      The argument SEQUENCE may be a list, a vector or a string.  The
  759.      result is always a list.  The length of the result is the same as
  760.      the length of SEQUENCE.
  761.      For example:
  762.           (mapcar 'car '((a b) (c d) (e f)))
  763.                => (a c e)
  764.           (mapcar '1+ [1 2 3])
  765.                => (2 3 4)
  766.           (mapcar 'char-to-string "abc")
  767.                => ("a" "b" "c")
  768.           
  769.           ;; Call each function in `my-hooks'.
  770.           (mapcar 'funcall my-hooks)
  771.           
  772.           (defun mapcar* (f &rest args)
  773.             "Apply FUNCTION to successive cars of all ARGS, until one ends.
  774.           Return the list of results."
  775.             (if (not (memq 'nil args))              ; If no list is exhausted,
  776.                 (cons (apply f (mapcar 'car args))  ; Apply function to CARs.
  777.                       (apply 'mapcar* f             ; Recurse for rest of elements.
  778.                              (mapcar 'cdr args)))))
  779.           
  780.           (mapcar* 'cons '(a b c) '(1 2 3 4))
  781.                => ((a . 1) (b . 2) (c . 3))
  782.  -- Function: mapconcat FUNCTION SEQUENCE SEPARATOR
  783.      `mapconcat' applies FUNCTION to each element of SEQUENCE: the
  784.      results, which must be strings, are concatenated. Between each
  785.      pair of result strings, `mapconcat' inserts the string SEPARATOR. 
  786.      Usually SEPARATOR contains a space or comma or other suitable
  787.      punctuation.
  788.      The argument FUNCTION must be a function that can take one
  789.      argument and returns a string.
  790.           (mapconcat 'symbol-name
  791.                      '(The cat in the hat)
  792.                      " ")
  793.                => "The cat in the hat"
  794.           
  795.           (mapconcat (function (lambda (x) (format "%c" (1+ x))))
  796.                      "HAL-8000"
  797.                      "")
  798.                => "IBM.9111"
  799. File: elisp,  Node: Anonymous Functions,  Next: Function Cells,  Prev: Mapping Functions,  Up: Functions
  800. Anonymous Functions
  801. ===================
  802.    In Lisp, a function is a list that starts with `lambda' (or
  803. alternatively a primitive subr-object); names are "extra".  Although
  804. usually functions are defined with `defun' and given names at the same
  805. time, it is occasionally more concise to use an explicit lambda
  806. expression--an anonymous function.  Such a list is valid wherever a
  807. function name is.
  808.    Any method of creating such a list makes a valid function.  Even
  809. this:
  810.      (setq silly (append '(lambda (x)) (list (list '+ (* 3 4) 'x))))
  811.           => (lambda (x) (+ 12 x))
  812. This computes a list that looks like `(lambda (x) (+ 12 x))' and makes
  813. it the value (*not* the function definition!) of `silly'.
  814.    Here is how we might call this function:
  815.      (funcall silly 1)
  816.           => 13
  817. (It does *not* work to write `(silly 1)', because this function is not
  818. the *function definition* of `silly'.  We have not given `silly' any
  819. function definition, just a value as a variable.)
  820.    Most of the time, anonymous functions are constants that appear in
  821. your program.  For example, you might want to pass one as an argument
  822. to the function `mapcar', which applies any given function to each
  823. element of a list.  Here we pass an anonymous function that multiplies
  824. a number by two:
  825.      (defun double-each (list)
  826.        (mapcar '(lambda (x) (* 2 x)) list))
  827.           => double-each
  828.      (double-each '(2 11))
  829.           => (4 22)
  830. In such cases, we usually use the special form `function' instead of
  831. simple quotation to quote the anonymous function.
  832.  -- Special Form: function FUNCTION-OBJECT
  833.      This special form returns FUNCTION-OBJECT without evaluating it.
  834.      In this, it is equivalent to `quote'.  However, it serves as a
  835.      note to the Emacs Lisp compiler that FUNCTION-OBJECT is intended
  836.      to be used only as a function, and therefore can safely be
  837.      compiled. *Note Quoting::, for comparison.
  838.    Using `function' instead of `quote' makes a difference inside a
  839. function or macro that you are going to compile.  For example:
  840.      (defun double-each (list)
  841.        (mapcar (function (lambda (x) (* 2 x))) list))
  842.           => double-each
  843.      (double-each '(2 11))
  844.           => (4 22)
  845. If this definition of `double-each' is compiled, the anonymous function
  846. is compiled as well.  By contrast, in the previous definition where
  847. ordinary `quote' is used, the argument passed to `mapcar' is the
  848. precise list shown:
  849.      (lambda (arg) (+ arg 5))
  850. The Lisp compiler cannot assume this list is a function, even though it
  851. looks like one, since it does not know what `mapcar' does with the
  852. list.  Perhaps `mapcar' will check that the CAR of the third element is
  853. the symbol `+'!  The advantage of `function' is that it tells the
  854. compiler to go ahead and compile the constant function.
  855.    We sometimes write `function' instead of `quote' when quoting the
  856. name of a function, but this usage is just a sort of comment.
  857.      (function SYMBOL) == (quote SYMBOL) == 'SYMBOL
  858.    See `documentation' in *Note Accessing Documentation::, for a
  859. realistic example using `function' and an anonymous function.
  860. File: elisp,  Node: Function Cells,  Next: Related Topics,  Prev: Anonymous Functions,  Up: Functions
  861. Accessing Function Cell Contents
  862. ================================
  863.    The "function definition" of a symbol is the object stored in the
  864. function cell of the symbol.  The functions described here access, test,
  865. and set the function cell of symbols.
  866.  -- Function: symbol-function SYMBOL
  867.      This returns the object in the function cell of SYMBOL.  If the
  868.      symbol's function cell is void, a `void-function' error is
  869.      signaled.
  870.      This function does not check that the returned object is a
  871.      legitimate function.
  872.           (defun bar (n) (+ n 2))
  873.                => bar
  874.           (symbol-function 'bar)
  875.                => (lambda (n) (+ n 2))
  876.           (fset 'baz 'bar)
  877.                => bar
  878.           (symbol-function 'baz)
  879.                => bar
  880.    If you have never given a symbol any function definition, we say that
  881. that symbol's function cell is "void".  In other words, the function
  882. cell does not have any Lisp object in it.  If you try to call such a
  883. symbol as a function, it signals a `void-function' error.
  884.    Note that void is not the same as `nil' or the symbol `void'.  The
  885. symbols `nil' and `void' are Lisp objects, and can be stored into a
  886. function cell just as any other object can be (and they can be valid
  887. functions if you define them in turn with `defun'); but `nil' or `void'
  888. is *an object*.  A void function cell contains no object whatsoever.
  889.    You can test the voidness of a symbol's function definition with
  890. `fboundp'.  After you have given a symbol a function definition, you
  891. can make it void once more using `fmakunbound'.
  892.  -- Function: fboundp SYMBOL
  893.      Returns `t' if the symbol has an object in its function cell,
  894.      `nil' otherwise.  It does not check that the object is a legitimate
  895.      function.
  896.  -- Function: fmakunbound SYMBOL
  897.      This function makes SYMBOL's function cell void, so that a
  898.      subsequent attempt to access this cell will cause a `void-function'
  899.      error.  (See also `makunbound', in *Note Local Variables::.)
  900.           (defun foo (x) x)
  901.                => x
  902.           (fmakunbound 'foo)
  903.                => x
  904.           (foo 1)
  905.           error--> Symbol's function definition is void: foo
  906.  -- Function: fset SYMBOL OBJECT
  907.      This function stores OBJECT in the function cell of SYMBOL. The
  908.      result is OBJECT.  Normally OBJECT should be a function or the
  909.      name of a function, but this is not checked.
  910.      There are three normal uses of this function:
  911.         * Copying one symbol's function definition to another.  (In
  912.           other words, making an alternate name for a function.)
  913.         * Giving a symbol a function definition that is not a list and
  914.           therefore cannot be made with `defun'.  *Note Classifying
  915.           Lists::, for an example of this usage.
  916.         * In constructs for defining or altering functions.  If `defun'
  917.           were not a primitive, it could be written in Lisp (as a
  918.           macro) using `fset'.
  919.      Here are examples of the first two uses:
  920.           ;; Give `first' the same definition `car' has.
  921.           (fset 'first (symbol-function 'car))
  922.                => #<subr car>
  923.           (first '(1 2 3))
  924.                => 1
  925.           
  926.           ;; Make the symbol `car' the function definition of `xfirst'.
  927.           (fset 'xfirst 'car)
  928.                => car
  929.           (xfirst '(1 2 3))
  930.                => 1
  931.           (symbol-function 'xfirst)
  932.                => car
  933.           (symbol-function (symbol-function 'xfirst))
  934.                => #<subr car>
  935.           
  936.           ;; Define a named keyboard macro.
  937.           (fset 'kill-two-lines "\^u2\^k")
  938.                => "\^u2\^k"
  939.    When writing a function that extends a previously defined function,
  940. the following idiom is often used:
  941.      (fset 'old-foo (symbol-function 'foo))
  942.      
  943.      (defun foo ()
  944.        "Just like old-foo, except more so."
  945.        (old-foo)
  946.        (more-so))
  947. This does not work properly if `foo' has been defined to autoload. In
  948. such a case, when `foo' calls `old-foo', Lisp will attempt to define
  949. `old-foo' by loading a file.  Since this presumably defines `foo'
  950. rather than `old-foo', it will not produce the proper results.  The
  951. only way to avoid this problem is to make sure the file is loaded
  952. before moving aside the old definition of `foo'.
  953.