DataMuseum.dk

Presents historical artifacts from the history of:

DKUUG/EUUG Conference tapes

This is an automatic "excavation" of a thematic subset of
artifacts from Datamuseum.dk's BitArchive.

See our Wiki for more about DKUUG/EUUG Conference tapes

Excavated with: AutoArchaeologist - Free & Open Source Software.


top - metrics - download
Index: T l

⟦6d72850b8⟧ TextFile

    Length: 55391 (0xd85f)
    Types: TextFile
    Names: »lispref-5«

Derivation

└─⟦a05ed705a⟧ Bits:30007078 DKUUG GNU 2/12/89
    └─⟦c06c473ab⟧ »./UNRELEASED/lispref.tar.Z« 
        └─⟦1b57a2ffe⟧ 
            └─⟦this⟧ »lispref-5« 

TextFile

Info file: lispref,    -*-Text-*-
produced by texinfo-format-buffer
from file: lispref.texinfo









This file documents GNU Emacs Lisp.

This is Edition 0.1 Beta of the GNU Emacs Lisp Reference Manual, for
Emacs Version 18, with some references to Emacs Version 19.

Please read this document for review purposes.

Published by the Free Software Foundation, 675 Massachusetts Avenue,
Cambridge, MA 02139 USA

Copyright (C) 1989 Free Software Foundation, Inc.

Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the
entire resulting derived work is distributed under the terms of a
permission notice identical to this one.

Permission is granted to copy and distribute translations of this manual
into another language, under the above conditions for modified versions,
except that this permission notice may be stated in a translation
approved by the Foundation.



▶1f◀
File: lispref  Node: Scope, Prev: Impl of Scope Rules, Up: Variable Resolution, Next: Extent

Scope
-----

  Emacs Lisp uses "indefinite scope" for local variable bindings.  This
means that it finds values of free variables by looking backward on the
(dynamic) call chain.  It follows that any function anywhere in the
program text might access a given binding of a variable.  Consider the
following function definitions:

     (defun binder (x)  ; `x' is bound in `binder'.
        (foo 5))        ; `foo' is some other function.

     (defun user ()     ; `x' is used in `user'.
       (list x))

  In a lexically scoped language, the binding of `x' from `binder' would
never be accessible in `user', because `user' is not textually contained
within the function `binder'.

  However, in dynamically scoped Emacs Lisp, `user' may or may not refer
to the binding of `x' established in `binder', depending on
circumstances:

   * If we call `user' directly without calling `binder' at all, then
     whatever binding of `x' is found, it won't be from `binder'.

   * If we define `foo' as follows and call `binder', then the binding
     made in `binder' will be seen in `user':

          (defun foo (lose)
            (user))

   * If we define `foo' as follows and call `binder', then the binding
     made in `binder' *will not* be seen in `user':

          (defun foo (x)
            (user))

     Here, when `foo' is called by `binder', it binds `x'.  (The binding
     in `foo' is said to "shadow" the one made in `binder'.)  Therefore,
     `user' will access the `x' bound by `foo' instead of the one bound
     by `binder'.

▶1f◀
File: lispref  Node: Extent, Prev: Scope, Up: Variable Resolution

Extent
------

  "Extent" refers to the time during program execution that a variable
name is valid.  In Emacs Lisp, a variable is valid only while the form
that bound it is executing.  This is called "dynamic extent".  Most
languages, including C and Pascal, have dynamic extent.

  One alternative to dynamic extent is "indefinite extent".  This means
that a variable binding can live on past the exit from the form that
made the binding.  Common Lisp and Scheme, for example, support this,
but Emacs Lisp does not.

  To illustrate this, the function below, `make-add', returns a function
that purports to add N to its own argument M.  This would work in Common
Lisp, but it does not work as intended in Emacs Lisp, because after the
call to `make-add' exits, the variable `n' is no longer bound to the
actual argument 2.

     (defun make-add (n)
         (function (lambda (m) (+ n m))))  ; Return a function.
          => make-add
     (fset 'add2 (make-add 2))  ; Define function add2 with (make-add 2).
          => (lambda (m) (+ n m))
     (add2 4)                   ; Try to add 2 to 4.
     error--> Symbol's value as variable is void: n

▶1f◀
File: lispref  Node: Buffer Local Variables, Prev: Variable Resolution, Up: Variables, Next: Default Value

Buffer Local Variables
======================

  Global and local variables are common features of almost all
programming languages, if not necessarily in the same form that they
take in Emacs Lisp.  Emacs Lisp is meant for programming editing
commands, though, and the central object of editing is the buffer (*Note
Buffers::.)  Therefore, Emacs Lisp also supports "buffer-local
variables", which may have differing values in various buffers.

  A buffer-local variable has a buffer-local binding associated with a
particular buffer.  The binding is in effect when that buffer is
current; otherwise, it is shunted aside.  If you set the variable while
a buffer-local binding is in effect, the new value goes in that binding,
so the global binding is unchanged; this means that the change is
visible in that buffer alone.

  A variable may have buffer-local bindings in some buffers but not in
others.  The global binding is shared by all the buffers that don't have
their own bindings.  Thus, if you set the variable in a buffer that does
not have a buffer-local binding for it, the new value is visible in all
buffers except those with buffer-local bindings.  (Here we are assuming
that there are no `let'-style local bindings to complicate the issue.)

  The most common use of buffer-local bindings is for major modes to
change variables that control the behavior of commands.  For example, C
mode and Lisp mode both set the variable `paragraph-start' to specify
that only blank lines separate paragraphs.  They do this by making the
variable buffer-local in the buffer that is being put into C mode or
Lisp mode, and then setting it to the new value for that mode.

  The usual way to make a buffer-local binding is with
`make-local-variable', which is what major mode commands use.  This
affects just the current buffer; all other buffers (including those yet
to be created) continue to share the global value.

  A more powerful effect is to mark the variable as "automatically
buffer local", with `make-variable-buffer-local'.  You can think of this
as making the variable local in all buffers, even those yet to be
created.  More precisely, the effect is that setting the variable
automatically makes the variable local to the current buffer if it is
not already so.  All buffers start out by sharing the global value of
the variable as usual, but any `setq' while in a buffer creates a
buffer-local binding for that buffer.  The new value is stored in the
buffer-local binding, leaving the (default) global binding untouched.
The global value can no longer be changed with `setq'; you need
`setq-default' to do that.

  Local variables in a file you edit are also represented by
buffer-local bindings for the buffer that holds the file within Emacs.
*Note Setting the Major Mode::.

* Command: make-local-variable SYMBOL

     This function creates a buffer-local binding for SYMBOL in the
     current buffer.  Other buffers are not affected.  The value
     returned is SYMBOL.

     The buffer-local value of SYMBOL starts out as the same value
     SYMBOL previously had.

          ;; In buffer A:
          (setq foo 5)                ; Affects all buffers.
               => 5
          (make-local-variable 'foo)  ; Now it is local in A.
               => foo
          foo                         ; That did not change the value.
               => 5
          (setq foo 6)                ; Change the value in A.
               => 6
          foo
               => 6

          ;; In buffer B, the value hasn't changed.
          (save-excursion
            (set-buffer "B")
            foo)
               => 5

* Command: make-variable-buffer-local SYMBOL

     This function marks SYMBOL automatically buffer local, so that any
     attempt to set it will make it local to the current buffer at the
     time.

     The value returned is SYMBOL.

* Function: buffer-local-variables &optional BUFFER

     This function tells you what the buffer local variables are in
     buffer BUFFER.  It returns an association list (*Note Association
     Lists::) in which each pair is a buffer-local variable and its
     value.  If BUFFER is omitted, the current buffer is used.

          (setq lcl (buffer-local-variables))
               => ((fill-column . 75)
              (case-fold-search . t)
              ...
              (mark-ring #<marker at 5454 in buffers.texinfo>)
              (require-final-newline . t))

     Note that changing the values in this list will *not* change the
     local value of the variable.

* Command: kill-local-variable SYMBOL

     This function deletes the buffer-local binding (if any) for SYMBOL
     in the current buffer.  As a result, the global (default) binding
     of SYMBOL are now visible in this buffer.  Usually this causes the
     value of SYMBOL to change, since the global value is not the same
     as the buffer-local value that was just eliminated.

     `kill-local-variable' returns SYMBOL.

* Function: kill-all-local-variables

     This function eliminates all the buffer-local variable bindings of
     the current buffer.  As a result, the buffer will see the default
     values of all variables.  Every major mode command begins by
     calling this function, which erases most of the effects of the
     previous major mode.

     `kill-all-local-variables' returns `nil'.

▶1f◀
File: lispref  Node: Default Value, Prev: Buffer Local Variables, Up: Variables

The Default Value of a Buffer-Local Variable
============================================

  The functions `default-value' and `setq-default' allow you to access
and change the global value regardless of whether the current buffer has
a buffer-local binding.  You could use `setq-default' to change the
default setting of `paragraph-start' for most buffers; and this would
work even when you are in a C or Lisp mode buffer which has a
buffer-local value for this variable.

* Function: default-value SYMBOL

     Return SYMBOL's default value.  This is the value that is seen in
     buffers that do not have their own values for this variable.  If
     SYMBOL is not buffer-local, than this is the same as `symbol-value'
     (*Note Accessing Variables::).

* Special form: setq-default SYMBOL VALUE

     This function sets the default (global) value of SYMBOL to VALUE.
     SYMBOL is not evaluated, but VALUE is.  The value of the
     `setq-default' form is VALUE.

     The default value is seen in buffers that do not have their own
     buffer-local values for this variable.

     If a SYMBOL is not buffer-local for the current buffer, this is
     equivalent to `setq' in the current buffer for that symbol.  If
     SYMBOL is buffer-local for the current buffer, then this changes
     the value that most other buffers will see (as long as they don't
     have a buffer-local value), but not the value that the current
     buffer sees.

          (make-variable-buffer-local 'local)
               => local

          ;; In buffer foo:
          (setq local 'value-in-foo)
               => value-in-foo
          (setq-default local 'new-default)
               => new-default
          local
               => value-in-foo
          (default-value 'local)
               => new-default

          ;; In (the new) buffer bar:
          local
               => new-default
          (default-value 'local)
               => new-default
          (setq local 'another-default)
               => another-default
          (default-value 'local)
               => another-default

          ;; Back in buffer foo:
          local
               => value-in-foo
          (default-value 'local)
               => another-default

* Function: set-default SYMBOL VALUE

     This function is like `setq-default' except that SYMBOL is
     evaluated.

          (set-default (car '(a b c)) 23)
               => 23
          (default-value 'a)
               => 23


▶1f◀
File: lispref  Node: Functions, Prev: Variables, Up: Top, Next: Macros

Functions
*********

  A Lisp program is composed mainly of Lisp functions.  This chapter
explains what functions are, how they accept arguments, and how to
define them.

* Menu:

* What Is a Function::  
* Lambda Expressions::  
* Function Names::
* Defining Functions::       
* Calling Functions::
* Mapping Functions::
* Anonymous Functions::       
* Function Cells::
* Related Topics::    

▶1f◀
File: lispref  Node: What Is a Function, Prev: Functions, Up: Functions, Next: Lambda Expressions

What Is a Function
==================

  There are two kinds of functions in GNU Emacs Lisp: they may be
primitives written in C, or they may be defined in Lisp.  In Emacs
version 18.52, there are approximately 580 functions in 64 C source
files, and over 2600 functions in about 145 Lisp files.

  The C-coded functions are the built-in functions of Lisp; they appear
in Lisp as primitive subr-objects.  These primitives provide the
lowest-level interfaces to editing functions or operating system
services, or in a very few cases, they exist to perform certain
important operations more quickly than a Lisp program could do them.
Primitives can be modified or added only by changing the C sources and
recompiling the editor.  This is harder than writing Lisp code, but not
impossibly hard; see *Note Writing Emacs Primitives::.

  Most extensions to the Emacs editor are written in Lisp.  If you have
ever programmed other versions of Emacs you will find writing code for
GNU Emacs very pleasant; the Lisp provided is a true version of Lisp,
and functions that are used as editing commands do not require any
special calling sequence.

  Macros are an alternative to functions.  Macros differ from functions
in that they define new forms of Lisp syntax; they translate a Lisp
expression that you write it into an equivalent form to be evaluated
instead.  *Note Macros::, for how to define and use macros.

  We start by defining some terminology:

"function"
     A "function" in general is anything that can be applied to
     arguments in a Lisp program.  In some cases, we will uses it more
     specifically to mean a function written in Lisp.  Special forms and
     macros are not functions.

"primitive"
     A "primitive" is a function callable from Lisp that is written in
     C, such as `car' and `cdr'.  These are sometimes called "built-in"
     functions or "subrs".

"lambda expression"
     A "lambda expression" is a function written in Lisp.  These are
     described in the following section.

     *Note Lambda Expressions::.

"command"
     A "command" is advertised to the user and can be invoked by the
     user with `M-x', or bound to a key in some keymap.  Commands
     written in Lisp are functions with interactive specifications
     (*Note Defining Commands::).

"keystroke command"
     A "keystroke command" is a command that is bound to a key sequence
     (typically one to three keystrokes).  The distinction is made here
     merely to avoid confusion with the meaning of ``command'' in
     non-Emacs editors; for programmers, the distinction is normally
     unimportant.

▶1f◀
File: lispref  Node: Lambda Expressions, Prev: What Is a Function, Up: Functions, Next: Function Names

Lambda Expressions
==================

  A function written in Lisp is a list that looks like this:

     (lambda (ARG-VARIABLES...)
       [DOCUMENTATION-STRING]
       [INTERACTIVE-DECLARATION]
       BODY-FORMS...)

(Such a list is called a "lambda expression" for historical reasons.)

* Menu:

* Lambda Components::	
* Simple Lambda::	
* Argument List::	
* Function Documentation::	

▶1f◀
File: lispref  Node: Lambda Components, Prev: Lambda Expressions, Up: Lambda Expressions, Next: Simple Lambda

Components of a Lambda Expression
---------------------------------

  The first element of this list is always the symbol `lambda'.  This
indicates that the list is supposed to be a function.

  The second element is a list of argument variable names (symbols).
This is called the "lambda list".  When a Lisp function is called, the
argument values are matched up against the names in the lambda list,
which are given local bindings with the values provided.  *Note Local
Variables::.

  The documentation string is an actual string, which serves to describe
the function for the Emacs help system.  *Note Function Documentation::.

  The interactive declaration is a list of the form `(interactive
CODE-STRING)'.  This declares how to provide arguments if the function
is used interactively.  Functions with this declaration are called
"commands"; they can be called using `M-x' or bound to a key.  Functions
not intended to be called in this way should not have interactive
declarations, so as to keep them from interfering with command
completion in `M-x'.  *Note Defining Commands::, for how to write an
interactive declaration.

  The rest of the elements are the "body" of the function: Lisp code to
execute, or, as a Lisp programmer would say, ``a list of Lisp forms to
evaluate''.  The value returned by the function is the value returned by
the last element of the body.

▶1f◀
File: lispref  Node: Simple Lambda, Prev: Lambda Components, Up: Lambda Expressions, Next: Argument List

A Simple Lambda-Expression Example
----------------------------------

  Consider for example the following function:

     (lambda (a b c) (+ a b c))

We can call it as follows:

     ((lambda (a b c) (+ a b c))
      1 2 3)

The body of this lambda expression is evaluated with the variable `a'
bound to 1, `b' bound to 2, and `c' bound to 3.  Evaluation of the body
adds these three numbers, producing the result 6; therefore, this call
to the function returns the value 6.

  Note that the arguments can be the results of other function calls, as
in this example:

     ((lambda (a b c) (+ a b c))
      1 (* 2 3) (- 5 4))

Here all the arguments `1', `(* 2 3)', and `(- 5 4)' are evaluated, left
to right.  Then the function shown is applied to the argument values 1,
6 and 1 to produce the value 8.

▶1f◀
File: lispref  Node: Argument List, Prev: Simple Lambda, Up: Lambda Expressions, Next: Function Documentation

Advanced Features of Argument Lists
-----------------------------------

Our simple sample function

     (lambda (a b c) (+ a b c))

specifies three arguments, so it must be called with three arguments: if
you try to call it with only two arguments or four arguments, you will
get a `wrong-number-of-arguments' error.

  It is often convenient to write a function that allows certain
arguments to be omitted.  For example, the function `substring' accepts
three arguments---a string, the start index and the end index---but the
third argument defaults to the end of the string if you omit it.  It is
also convenient for certain functions to accept an indefinite number of
arguments, as the functions `and' and `+' do.

  To specify optional arguments that may be omitted when a function is
called, simply include the keyword `&optional' before the optional
arguments.  To specify a list of zero or more extra arguments, include
the keyword `&rest' before one final argument.

  The complete syntax for an argument list is as follows:

     (REQUIRED-VARS...
      [&optional OPTIONAL-VARS...]
      [&rest REST-VAR])

The square brackets indicate that the `&optional' and `&rest' clauses,
and the variables that follow them, are optional.  The
DOCUMENTATION-STRING and INTERACTIVE-DECLARATION are described later.

  A call to the function requires one actual argument for each of the
REQUIRED-VARS.  There may be actual arguments for zero or more of the
OPTIONAL-VARS, and there cannot be any more actual arguments than these
unless `&rest' exists.  In that case, there may be any number of extra
actual arguments.

  If actual arguments for the optional and rest variables are omitted,
then they always default to `nil'.  However, the body of the function is
free to consider `nil' an abbreviation for some other meaningful value.
This is what `substring' does; `nil' as the third argument means to use
the length of the string supplied.  There is no way for the function to
distinguish between an explicit argument of `nil' and an omitted
argument.

     Common Lisp Note: Common Lisp allows the function to specify what
     default values will be used when an optional argument is omitted;
     GNU Emacs Lisp always uses `nil'.

  For example, an argument list that looks like this:

     (a b &optional c d &rest e)

binds A and B to the first two actual arguments, which are required.  If
one or two more arguments are included, C and D are bound to them
respectively; any arguments after the first four are collected into a
list and E is bound to that list.  If there are only two arguments, C is
`nil'; if two or three arguments, D is `nil'; if less than four
arguments, E is `nil'.

  There is no way to have required arguments following optional
ones---it would not make sense.  To see why this must be so, suppose
that C in the example were optional and D were required.  If three
actual arguments are given; then what should be bound to the third
argument?  Similarly, it makes no sense to have any arguments after a
`&rest' argument.

  Here are some examples of argument lists:

     ((lambda (n) (1+ n))                ;One parameter:
      1)                                 ;requires exactly one argument
          => 2
     ((lambda (n &optional n1)           ;One parameter and one optional:
              (if n1 (+ n n1) (1+ n)))   ;1 or 2 arguments.
      1 2)
          => 3
     ((lambda (n &rest ns)                ;One parameter and &rest:
              (+ n (apply '+ ns)))        ;1 or more arguments.
      1 2 3 4 5)
          => 15

▶1f◀
File: lispref  Node: Function Documentation, Prev: Argument List, Up: Lambda Expressions

Documentation Strings of Functions
----------------------------------

  A lambda expression may optionally have a "documentation string" just
after the lambda list.  This string does not affect execution of the
function; it is a kind of comment, but a systematized comment which
actually appears inside the Lisp world and can be used by the Emacs help
system.  *Note Documentation::, for how the DOCUMENTATION-STRING is
displayed for the user.

  It is a good idea to provide documentation strings for all commands,
and for all other functions in your program that users of your program
should know about; internal functions might as well have only comments,
since they don't take up any room when your program is loaded.

  The first line of the documentation string should be complete in
itself, because `apropos' displays just this first line.  It should
consist of one or two complete sentences that summarize the function's
purpose.

  The start of the documentation string is usually indented; since these
spaces come before the starting double-quote, they are not part of the
string.  Some people make a practice of indenting any additional lines
of the string so that the text lines up.  *This is a mistake.* The
indentation of the following lines is inside the string; what looks nice
in the source code will look ugly in the help system.

  You may wonder how the documentation string could be optional, since
there are required components of the function that follow it (the body).
Since evaluation of a string returns that string, without any side
effects, it has no effect if it is not the last form in the body.  Thus,
in practice, there is no confusion between the first form of the body
and the documentation string; if the only body form is a string then it
serves both as the return value and as the documentation.

▶1f◀
File: lispref  Node: Function Names, Prev: Lambda Expressions, Up: Functions, Next: Defining Functions

How a Function Can Have a Name
==============================

  In most computer languages, every function has a name; the idea of a
function without a name is nonsensical.  In Lisp, a function in the
strictest sense has no name.  It is simply a list whose first element is
`lambda', or a primitive subr-object.

  However, a symbol can serve as the name of a function.  This happens
when you put the function in the symbol's "function cell".  Then the
symbol itself becomes a valid, callable function, equivalent to the list
or subr-object that its function cell refers to.  The contents of the
function cell is also spoken of as the symbol's "function definition".

  In practice, nearly all functions are given names in this way and
referred to through their names.  For example, the symbol `car' works as
a function and does what it does because the primitive subr-object
`#<subr car>' is stored in its function cell.

  We give functions names because it is more convenient to refer to them
by their names in other functions.  For a primitive subr-object such as
`#<subr car>', that is the only way you can refer to them: there is no
read syntax for such objects.  For functions written in Lisp, the name
makes it possible to refer to the function without including a copy of
it.  Also, a function with a name can refer to itself---it can be
recursive.  Writing the function's own name is much more convenient than
making the function point to itself (something which is not impossible
but which has various disadvantages in practice).

  Functions are often identified with the symbols used to name them.
For example, we often speak of ``the function `car''', not
distinguishing between the symbol `car' and the primitive subr-object
that is its function definition.  For most purposes, there is no need to
distinguish.

  Even so, keep in mind that a function need not have a unique name.
While a given function object *usually* appears in the function cell of
only one symbol, this is just a matter of convenience.  It is very easy
to store it in several symbols using `fset'; then each of the symbols is
equally well a name for the same function.

▶1f◀
File: lispref  Node: Defining Functions, Prev: Function Names, Up: Functions, Next: Calling Functions

Defining Named Functions
========================

  The usual way to create a function written in Lisp is to give it a
name at the same time.  This is called "defining a function", and it is
done with the `defun' special form.

* Special form: defun NAME PARAMETER-LIST BODY-FORMS

     `defun' is the usual way to define new Lisp functions.  It defines
     the symbol NAME as a function which looks like this:

          (lambda PARAMETER-LIST . BODY-FORMS)

     This lambda expression is stored in the function cell of NAME.  The
     value returned by evaluating the `defun' form is NAME, but usually
     we ignore this value.

     As described previously (*Note Lambda Expressions::),
     PARAMETER-LIST is a list of parameter names and may include the
     keywords `&optional' and `&rest'.  Also, the first two forms in
     BODY-FORMS may be a documentation string and an interactive
     declaration.

     Note that the same NAME may also be used as a global variable since
     the value cell is independent of the function cell.  But take
     precautions against unintentionally redefining functions since
     `defun' will even redefine primitive functions such as `car'
     without any hesitation or notification.

          (defun foo () 5)
               => foo
          (foo)
               => 5

          (defun bar (a &optional b &rest c)
              (list a b c))
               => bar
          (bar 1 2 3 4 5)
               => (1 2 (3 4 5))
          (bar 1)
               => (1 nil nil)
          (bar)
          error--> Wrong number of arguments.

          (defun capitalize-backwards ()
            "This function makes the last letter of a word upper-case."
            (interactive)
            (backward-word 1)
            (forward-word 1)
            (backward-char 1)
            (capitalize-word 1))
               => capitalize-backwards

▶1f◀
File: lispref  Node: Calling Functions, Prev: Defining Functions, Up: Control Structures, Next: Mapping Functions

Function Invocation
===================

  Defining functions is only half the battle.  Functions don't do
anything until you "call" them, which means, tell them to run.  This
process is also known as "invocation".

  The most common way of invoking a function is simply to evaluate a
list.  For example, evaluating the list `(concat "a" "b")' calls the
function `concat'.  *Note Evaluation::, for a description of evaluation
in general.

  When you evaluate a list, you have to specify the function name in
your program.  This means that the choice of which function to call is
made when you write the program.  Usually that's just what you want.
Occasionally you need to decide at run time which function to call.
Then you can use the functions `apply' and `funcall'.

* Function: funcall FUNCTION &rest ARGUMENTS

     `funcall' calls FUNCTION with ARGUMENTS, and returns whatever
     FUNCTION returns.

     Since `funcall' is a function, all of its arguments, including
     FUNCTION, are evaluated before `funcall' is called.  This means
     that you can use any expression to come up with the function to be
     called.  It also means that `funcall' does not see the expressions
     you write for the ARGUMENTS, only their values.

     The ARGUMENTS are *not* evaluated a second time in the act of
     calling FUNCTION.  `funcall' enters the normal procedure for
     calling a function at the place where the arguments have already
     been evaluated.
  
     FUNCTION must be either a Lisp function or a primitive function.
     Special forms and macros are not allowed, because they make sense
     only when given the ``unevaluated'' argument expressions.
     `funcall' cannot give these because, as we saw above, it never sees
     them in the first place.

          (setq f 'list)
               => list
          (funcall f 'x 'y 'z)
               => (x y z)
          (funcall f 'x 'y '(z))
               => (x y (z))
          (funcall 'and t nil)
          error--> Invalid function: #<subr and>

     Compare this example with that of `apply'.

* Function: apply FUNCTION &rest ARGUMENTS

     `apply' calls FUNCTION with ARGUMENTS, just like `funcall' but with
     one difference: the last of ARGUMENTS is a list of arguments to
     give to FUNCTION, rather than a single argument.  We also say that
     this list is "appended" to the other arguments.

     `apply' returns the result of that call to FUNCTION.  As with
     `funcall', FUNCTION must either be a Lisp function or a primitive
     function; special forms and macros do not make sense to apply.

          (setq f 'list)
               => list
          (apply f 'x 'y 'z)
          error--> Wrong type argument: listp, z
          (apply f 'x 'y '(z))
               => (x y z)
          (apply f '(x y z))
               => (x y z)

          ;; Remove empty lists from a list of possibly empty lists.
          (apply 'append '((a b c) nil (x y z) nil))
               => (a b c x y z)

▶1f◀
File: lispref  Node: Mapping Functions, Prev: Calling Functions, Up: Control Structures, Next: Anonymous Functions

Mapping Functions
=================

  A "mapping function" applies a given function to each element of a
list or other collection.  Emacs Lisp has three such functions: two,
`mapcar' and `mapconcat', which scan a list, are described here.  (The
third function is `mapatoms'; *Note Creating and Interning Symbols::.)

* Function: mapcar FUNCTION SEQUENCE

     `mapcar' applies FUNCTION to each element of SEQUENCE in turn.  The
     results are made into a `nil'-terminated list.

     The argument SEQUENCE may be a list, a vector or a string.  The
     result is always a list.  The length of the result is the same as
     the length of SEQUENCE.

     For example:

          (mapcar 'car '((a b) (c d) (e f)))
               => (a c e)
          (mapcar '1+ [1 2 3])
               => (2 3 4)
          (mapcar char-to-string "abc")
               => ("a" "b" "c")

          ;; Call each function in `my-hooks'.
          (mapcar 'funcall my-hooks)

          (defun mapcar* (f &rest args)
            "Apply FUNCTION to successive cars of all ARGS, until one ends.
          Return the list of results."
            (cons (apply f (mapcar 'car args))       ; Apply function to CARs.
                  (let ((rest (mapcar 'cdr args)))
                    (if (not (memq 'nil rest))
                        (apply 'mapcar* f rest)))))  ; Do the same for CDRs.

          (mapcar* 'cons '(a b c) '(1 2 3 4))
               => ((a . 1) (b . 2) (c . 3))

* Function: mapconcat FUNCTION SEQUENCE SEPARATOR

     `mapconcat' applies FUNCTION to each element of SEQUENCE: the
     results, which must be strings, are concatenated.  Between each
     pair of result strings, `mapconcat' inserts the string SEPARATOR.
     Usually SEPARATOR contains a space or comma or other suitable
     punctuation.

     FUNCTION must be a function that can take one argument and returns
     a string.
  
          (mapconcat 'symbol-name
                     '(The cat in the hat)
                     " ")
               => "The cat in the hat"

          (mapconcat (function (lambda (x) (format "%c" (1+ x))))
                     "HAL-8000"
                     "")
               => "IBM.9111"

▶1f◀
File: lispref  Node: Anonymous Functions, Prev: Mapping Functions, Up: Functions, Next: Function Cells

Some Functions Don't Have Names
===============================

  In Lisp, a function is a list with a certain format (or a subroutine);
names are ``extra''.  Although usually functions are defined with
`defun' and given names at the same time, it is occasionally more
concise to use an anonymous function---a list that starts with `lambda'.

  Any method of creating such a list makes a valid function.  Even this:

     (setq silly (append '(lambda (x)) (list (list '+ (* 3 4) 'x))))
          => (lambda (x) (+ 12 x))

Now the value of the variable `silly' is an anonymous function which
adds 12 to its argument.  Here is how we might call this function:

     (funcall silly 1)
          => 13

(It does *not* work to write `(silly 1)', because this function is not
the *function definition* of `silly'.  We have not given `silly' any
function definition, just a value as a variable.)

But most of the time, anonymous functions are constants which appear in
your program.  For example, you might want to pass one as an argument to
the function `mapcar', which applies any given function to each element
of a list.  Here we pass an anonymous function that multiplies a number
by two:

     (defun double-each (list)
       (mapcar '(lambda (x) (* 2 x)) list))
          => double-each
     (double-each '(2 11))
          => (4 22)

In such cases, we usually use `function' instead of simple quotation.

* Special form: function FUNCTION-OBJECT

     This special form returns FUNCTION-OBJECT without evaluating it.
     In this, it is equivalent to `quote'.  However, it serves as a note
     to the Emacs Lisp compiler that FUNCTION-OBJECT is intended to be
     used only as a function, and therefore can safely be compiled.
     *Note Quoting::, for comparison.

Using `function' instead of `quote' makes a difference inside a function
or macro that you are going to compile.  For example:

     (defun double-each (list)
       (mapcar (function (lambda (x) (* 2 x))) list))
          => double-each
     (double-each '(2 11))
          => (4 22)

If this definition of `double-each' is compiled, the anonymous function
is compiled as well.  In the previous definition, above, the argument
passed to `mapcar' is the precise list shown:

     (lambda (arg) (+ arg 5))

This is because the Lisp compiler cannot assume this list is a function,
even though it looks like one, and it does not know what `mapcar' does
with the list.  Perhaps `mapcar' will check that the CAR of the third
element is the symbol `+'!  We use `function' to tell the compiler to go
ahead and compile.

We also often write `function' instead of `quote' when quoting the name
of a function, but then it is just a sort of comment.

     (function car) == (quote car) == 'car

▶1f◀
File: lispref  Node: Function Cells, Prev: Anonymous Functions, Up: Functions, Next: Related Topics

Accessing Function Cell Contents
================================

  The "function definition" of a symbol is the object stored in the
function cell of the symbol.  The functions described here access, test,
and set the function cell of symbols.

* Function: symbol-function SYMBOL

     Returns the object in the function cell of SYMBOL.  If the symbol's
     function cell is void, a `void-function' error is signaled.

     This function does not check that the object is a legitimate
     function.

          (defun bar (n) (+ n 2))
               => bar
          (symbol-function 'bar)
               => (lambda (n) (+ n 2))
          (fset 'baz 'bar)
               => bar
          (symbol-function 'baz)
               => bar

* Function: subrp OBJECT

     This function returns `t' if OBJECT is a built-in function (i.e. a
     Lisp primitive).

          (subrp 'message)                ; `message' is a symbol,
               => nil                   ; not a subr object.
          (subrp (symbol-function 'message))
               => t

  If you have never given a symbol any function definition, we say that
that symbol's function cell is "void".  In other words, the function
cell does not have any Lisp object in it.  If you try to call this
symbol as a function, the result is a `void-function' error.

  Note that void is not the same as `nil' or the symbol `void'.  The
symbols `nil' and `void' are Lisp objects, and can be stored into a
function cell just as any other object can be (and they can be valid
functions if you define them in turn with `defun'); but they are
*something*.  A void function cell contains no object whatever.

  You can test the voidness of a symbol's function definition with
`fboundp'.  After you have given a symbol a function definition, you can
make it void once more using `fmakunbound'.

* Function: fboundp SYMBOL

     Returns `t' if the symbol has some value (any non-void object) in
     its function cell, `nil' otherwise.  It does not check that the
     value is a legitimate function.

* Function: fmakunbound SYMBOL

     This function sets the symbol's function pointer to be ``void''
     (not the *symbol* `void'), so that any attempt to access this cell
     will cause a `void-function' error.  (See also `makunbound', in
     *Note Local Variables::.)

          (defun foo (x) x)
               => x
          (fmakunbound 'foo)
               => x
          (foo 1)
          error--> Symbol's function definition is void: foo

* Function: fset SYMBOL OBJECT

     This function sets the function cell of SYMBOL to be OBJECT.  The
     result is OBJECT.  Normally OBJECT should be a function or the name
     of one, but this is not checked.

     There are three normal uses of this function:

        * Copying one symbol's function definition to another.  (In
          other words, making an alias.)

        * Giving a symbol a function definition that is not a list and
          therefore cannot be made with `defun'.

        * In constructs for defining or altering functions.  If `defun'
          were not a primitive, it could be written in Lisp (as a macro)
          using `fset'.

     Here are examples of the first two uses:

          ;; Give `first' the same definition `car' has.
          (fset 'first (symbol-function 'car))
               => #<subr car>
          (first '(1 2 3))
               => 1

          ;; Make the symbol `car' the function definition of `xfirst'.
          (fset 'xfirst 'car)
               => car
          (xfirst '(1 2 3))
               => 1
          (symbol-function 'xfirst)
               => car
          (symbol-function (symbol-function 'xfirst))
               => #<subr car>

▶1f◀
File: lispref  Node: Related Topics, Prev: Function Cells, Up: Functions

Other Topics Related to Functions
=================================

  Here is a table of several functions that do things related to
function calling and function definitions.

`apply'
     *Note Calling Functions::.

`funcall'
     *Note Calling Functions::.

`eval'
     *Note Eval::.

`mapatoms'
     *Note Creating and Interning Symbols::.

`mapcar'
     *Note Mapping Functions::.

`mapconcat'
     *Note Mapping Functions::.

`documentation'
     *Note Documentation::.

`interactive'
     *Note Interactive Call::.

`call-interactively'
     *Note Interactive Call::.

`interactive-p'
     *Note Interactive Call::.

`commandp'
     *Note Command Overview::.

`autoload'
     *Note Autoload::.

`ignore'
     *Note Key Lookup::.

`undefined'
     *Note Key Lookup::.
▶1f◀
File: lispref  Node: Macros, Prev: Functions, Up: Top, Next: Control Structures

Macros
******

"Macros" enable you to define new control constructs and other language
features.  A macro is defined much like a function; but instead of
saying how to compute a value, it says how to compute another Lisp
expression which will compute the value.  We call this expression the
"expansion" of the macro.

Macros can do this because they operate on the unevaluated expressions
for the arguments, not on the argument values as functions do.
Therefore they can construct an expansion containing these argument
expressions, or parts of them.

* Menu:

* Simple Macro::
* Expansion::
* Compiling Macros::
* Defining Macros::     
* Backquote::   
* Problems with Macros::

▶1f◀
File: lispref  Node: Simple Macro, Prev: Macros, Up: Macros, Next: Expansion

A Simple Example of a Macro
===========================

Suppose we sould like to define a Lisp construct to increment a variable
value, much like the `++' operator in C.  We would like to write `(inc
x)' and have the effect of `(setq x (1+ x))'.  Here is how to do it:

     (defmacro inc (var)
        (list 'setq var (list '1+ var)))

When called as `(inc x)', the argument `var' has the value `x'---*not*
the *value* of `x'.  The body of the macro uses this to construct the
expansion, which is `(setq x (1+ x))'.  Once the macro definition
returns this expansion, Lisp proceeds to evaluate it, thus incrementing
`x'.

▶1f◀
File: lispref  Node: Expansion, Prev: Simple Macro, Up: Macros, Next: Compiling Macros

Expansion of a Macro Call
=========================

This section describes in detail the process of expanding a macro call.

A macro call looks just like a function call: it is a list which starts
with the name of the macro.  The rest of the elements of the list are
the arguments of the macro.

Evaluation of the macro call begins like evaluation of a function call
except for one crucial difference: the arguments of a function are the
values of the elements of the list.  The macro arguments are the actual
expressions appearing in the macro call.

Having obtained the arguments, Lisp invokes the macro just as a function
is invoked.  The argument variables of the macro are bound to the
argument values from the macro call, or to a list of them in the case of
a `&rest' argument.  And the macro body executes and returns its value
just as a function body does.

Now comes the second crucial difference between macros and functions:
the value returned by the macro body is not the value of the macro call.
Instead, it is an alternate expression for computing that value, also
known as the "expansion" of the macro.  The Lisp interpreter therefore
proceeds to evaluate the expansion as soon as it comes back from the
macro.

Since the expression is evaluated normally, it may contain calls to
other macros.  It may even be a call to the same macro, though this is
unusual.

You can see what a macro call would expand into by means of
`macroexpand':

* Function: macroexpand FORM &optional ENVIRONMENT

     This function expands FORM, if it is a macro call.  If the result
     is another macro call, it is expanded in turn, until something
     which is not a macro call results.  That is the value returned by
     `macroexpand'.  If FORM is not a macro call to begin with, it is
     returned as given.

     Note that `macroexpand' does not look at the subexpressions of FORM
     (although some macro definitions may do so).  If they are macro
     calls themselves, `macroexpand' will not expand them.

     If ENVIRONMENT is provided, it specifies an alist of macro
     definitions that shadow the currently defined macros.  This is used
     by byte-compilation.

          (defmacro inc (var)
              (list 'setq var (list '1+ var)))
               => inc

          (macroexpand '(inc r))
               => (setq r (1+ r))

          (defmacro inc2 (var1 var2)
              (list 'progn (list 'inc var1) (list 'inc var2)))
               => inc2

          (macroexpand '(inc2 r s))
               => (progn (inc r) (inc s))        ; `inc' not expanded here.

▶1f◀
File: lispref  Node: Compiling Macros, Prev: Expansion, Up: Macros, Next: Defining Macros

Macros and Byte-Compilation
===========================

You might ask why the trouble of computing an expansion for a macro and
then evaluating it.  Why not have the macro body produce the desired
results directly?  The reason has to do with the Lisp compiler.

When a macro call appears in a Lisp program being compiled, the Lisp
compiler calls the macro definition just as the interpreter would, and
receives an expansion.  But instead of evaluating this expansion, it
compiles it.  As a result, the compiled code produces the value and side
effects that we want, and it executes just as fast as if we had written
the expansion ourselves.  This would be impossible if the macro body
computed the value and side effects itself---they would be computed at
compile time, which is not useful.

In order for compilation of macro calls to work, the macros must be
defined in Lisp when the calls to them are compiled.  The compiler has a
special feature to help you do this: if a file being compiled contains a
`defmacro' form, the macro is defined temporarily for the rest of the
compilation of that file.  To use this, you must define the macro in the
same file where it is used, and before its first use.  Alternatively,
you can put your macro definitions in a separate file and load that file
before doing any compilation.

▶1f◀
File: lispref  Node: Defining Macros, Prev: Compiling Macros, Up: Macros, Next: Backquote

Defining Macros
===============

  A Lisp macro is a list whose CAR is `macro'.  Its CDR should be a
function; expansion of the macro works by applying the function (with
`apply') to the list of unevaluated argument-expressions from the macro
call.

  You can use an anonymous Lisp macro just like an anonymous function,
but this is never done, because it does not make sense to pass an
anonymous macro to mapping functions such as `mapcar'.  In practice, all
Lisp macros have names, and they are usually defined with the special
form `defmacro'.

* Special form: defmacro NAME PARAMETER-LIST BODY-FORMS...

     `defmacro' defines the symbol NAME as a macro which looks like
     this:

          (macro lambda PARAMETER-LIST . BODY-FORMS)

     This macro-object is stored in the function cell of NAME.  The
     value returned by evaluating the `defmacro' form is NAME, but
     usually we ignore this value.

     The shape and meaning of PARAMETER-LIST is the same as in a
     function, and the keyword `&rest' and `&optional' may be used
     (*Note Argument List::).  Macros may have a documentation string,
     but any `interactive' declaration is ignored since macros cannot be
     called interactively.

▶1f◀
File: lispref  Node: Backquote, Prev: Defining Macros, Up: Macros, Next: Problems with Macros

Backquote
=========

It could prove rather awkward to write macros of significant size,
simply due the number of times the function `list' needs to be called.
To make writing these forms easier, a macro ``' (pronounced "backquote")
exists.

  Backquote allows you to quote a list, but selectively evaluate
elements of that list.  In its simplest form, it is identical to the
special form `quote'.  In the example below, the two forms yield
identical results.

     (` (a list of (+ 2 3) elements))
          => (a list of (+ 2 3) elements)
     (quote (a list of (+ 2 3) elements))
          => (a list of (+ 2 3) elements)

By inserting a special marker,`,', inside of the argument to backquote,
it is possible to evaluate desired portions of the argument:

     (list 'a 'list 'of (+ 2 3) 'elements)
          => (a list of 5 elements)
     (` (a list of (, (+ 2 3)) elements))
          => (a list of 5 elements)

It is also possible to have an evaluated list "spliced" into the
resulting list by using the special marker `,@'.  The elements of the
spliced list become elements at the same level as the other elements of
the resulting list.  The equivalent code without using ``' is often
unreadable.

     (setq some-list '(2 3))
          => (2 3)
     (cons 1 (append some-list (list 4)))
          => (1 2 3 4)
     (` (1 (,@ some-list) 4))
          => (1 2 3 (4))

     ;; A more complex example:
     (cons 'a
       (cons 'list
         (cons 'of (append (list (+ 2 3)) '(elements)))))
          => (a list of 5 elements)
     (` (a list of (,@ (list (+ 2 3))) elements))
          => (a list of 5 (elements))
          => (a list of 5 elements)

* Macro: ` LIST

     This macro returns LIST as quote would, except any sublist
     beginning with the special marker `,' will have its second element
     evaluated, and any sublist beginning with the special marker `,@'
     will have its second element evaluated, and the result spliced into
     the list being created.

     If any of these specially marked sublists contain more than two
     elements, those elements will be ignored.

     There are several subtle bugs that should simply be avoided.  The
     following forms do not work as one would expect:

          (` (a . (, 1)))					; Not `(a . 1)'
               => (a \, 1)                                
          (` [a (, 1) c])					; Not `[a 1 c]'
               error--> Wrong type argument                      
          (` (, 2))					; Not 2
               => (\, 2)                                  

          (` (a list of (, (list (+ 2 3))) elements xx))
           => (a list of (5) elements xx)


▶1f◀
File: lispref  Node: Problems with Macros, Prev: Backquote, Up: Macros

Common Problems Using Macros
============================

When defining a macro you must always pay attention to how many times
the arguments will be evaluated when the expansion is executed.  To
illustrate this problem, here is a macro to facilitate iteration.  This
macro allows us to write a simple ``for'' loop such as one might find in
Pascal.

     (defmacro for (var from init to final do &rest body)
       "Execute a simple \"for\" loop, e.g.,
         (for i from 1 to 10 do (print i))."

       (list 'let (list (list var init))
             (cons 'while (cons (list '<= var final)
                                (append body (list (list 'inc var)))
                                ))))
          => for

     (for i from 1 to 3 do
        (setq square (* i i))
        (princ (format "\n%d %d" i square)))
     ==>
     (let ((i 1))
       (while (<= i 3)
         (setq square (* i i))
         (princ (format "%d      %d" i square))
         (inc i)))

          -|1       1
          -|2       4
          -|3       9
          => nil

The arguments `from', `to', and `do' in this macro are ``syntactic
sugar''; they are entirely ignored.  The idea is that you will write
noise words (such as `from', `to', and `do') in those positions in the
macro call.

This macro suffers from the defect that FINAL is evaluated on every
iteration.  If FINAL is a constant, there's no problem.  If it had been
a more complex form, say `(long-complex-calculation x)', it would slow
down the execution significantly.  If FINAL has side effects, executing
it more than once could be disastrous.

A well-designed macro takes steps to avoid this problem by producing an
expansion that evaluates the argument expressions exactly once unless
they are supposed to be repeated.  Here is a suitable expansion for the
`for' macro:

     (let ((i 1)
           (max 3))
       (while (<= i max)
         (setq square (* i i))
         (princ (format "%d      %d" i square))
         (inc i)))

Here is a macro definition that creates this expansion:

     (defmacro for (var from init to final do &rest body)
       "Execute a simple for loop: (for i from 1 to 10 do (print i))."
       (` (let (( (, var) (, init) )
                ( max (, final) ))
            (while (<= (, var) max)
                   (,@ body)
                   (inc (, var))
                   ))))

However, this definition has a different problem: it introduces a local
variable named `max' which the user does not expect.  This will cause
trouble in examples such as the following:

     (let ((max 0))
       (for x from 0 to 10 do
         (let ((this (frob x)))
           (if (< max this)
               (setq max this)))))

where the references to `max' inside the body of the `for', which are
supposed to refer to the user's binding of `max', will get instead the
binding made by `for'.

The way to correct this is to use an uninterned symbol instead of `max'
(*Note Creating and Interning Symbols::).  The uninterned symbol can be
bound and referred to just like any other symbol; but if it is created
by `for', we know that it cannot appear in the user's program.  And
since it is not interned, there is no way the user can put it into the
program later.  It will not appear anywhere except where put by `for'.
Here is a definition of `for' which works this way:

     (defmacro for (var from init to final do &rest body)
       "Execute a simple for loop: (for i from 1 to 10 do (print i))."
       (let ((tempvar (make-symbol "max")))
         (` (let (((, var) (, init))
                  ((, tempvar) (, final)))
              (while (<= (, var) (, tempvar))
                     (,@ body)
                     (inc (, var)))))))

This creates an uninterned symbol named `max' and puts it in the
expansion where the canonical, interned symbol `max' was used
previously.

Another problem can happen if you evaluate any of the macro argument
expressions during the computation of the expansion: if it is supposed
to refer to the user's variables, you may have trouble if the user
happens to use a variable with the same name as one of the macro
arguments.  The problem is that inside the macro body, the macro
argument binding is the most local binding of this variable, so any
references inside the form being evaluated will refer to it.  Here is an
example:

     (defmacro foo (a)
       (list 'setq (eval a) t))
          => foo
     (setq x 'b)
     (foo x) ==> (setq b t)
          => t                  ; and `b' has been set.
     but
     (setq a 'b)
     (foo a) ==> (setq 'b t)   ; invalid!
     error--> Symbol's value is void: b

Here it makes a difference whether the user types `a' or `x', because
`a' conflicts with the macro argument variable `a'.

In general it is better to avoid calling `eval' in a macro definition at
all.
▶1f◀