X-Git-Url: https://git.hcoop.net/bpt/emacs.git/blobdiff_plain/c7844a276494777c90c57cfbb38d90f64ad2d866..a8e7d6d783219972c08fd49a3a2afaf26eb139c2:/doc/lispref/functions.texi diff --git a/doc/lispref/functions.texi b/doc/lispref/functions.texi index 519957f892..b5cf38ed6f 100644 --- a/doc/lispref/functions.texi +++ b/doc/lispref/functions.texi @@ -1,9 +1,8 @@ @c -*-texinfo-*- @c This is part of the GNU Emacs Lisp Reference Manual. -@c Copyright (C) 1990-1995, 1998-1999, 2001-2011 +@c Copyright (C) 1990-1995, 1998-1999, 2001-2012 @c Free Software Foundation, Inc. @c See the file elisp.texi for copying conditions. -@setfilename ../../info/functions @node Functions, Macros, Variables, Top @chapter Functions @@ -21,8 +20,9 @@ define them. * Anonymous Functions:: Lambda expressions are functions with no names. * Function Cells:: Accessing or setting the function definition of a symbol. +* Closures:: Functions that enclose a lexical environment. * Obsolete Functions:: Declaring functions obsolete. -* Inline Functions:: Defining functions that the compiler will open code. +* Inline Functions:: Functions that the compiler will expand inline. * Declaring Functions:: Telling the compiler that a function is defined. * Function Safety:: Determining whether a function is safe to call. * Related Topics:: Cross-references to specific Lisp primitives @@ -32,104 +32,117 @@ define them. @node What Is a Function @section What Is a Function? - In a general sense, a function is a rule for carrying on a computation -given several values called @dfn{arguments}. The result of the -computation is called the value of the function. The computation can -also have side effects: lasting changes in the values of variables or -the contents of data structures. - - Here are important terms for functions in Emacs Lisp and for other -function-like objects. +@cindex return value +@cindex value of function +@cindex argument + In a general sense, a function is a rule for carrying out a +computation given input values called @dfn{arguments}. The result of +the computation is called the @dfn{value} or @dfn{return value} of the +function. The computation can also have side effects, such as lasting +changes in the values of variables or the contents of data structures. + + In most computer languages, every function has a name. But in Lisp, +a function in the strictest sense has no name: it is an object which +can @emph{optionally} be associated with a symbol (e.g.@: @code{car}) +that serves as the function name. @xref{Function Names}. When a +function has been given a name, we usually also refer to that symbol +as a ``function'' (e.g.@: we refer to ``the function @code{car}''). +In this manual, the distinction between a function name and the +function object itself is usually unimportant, but we will take note +wherever it is relevant. + + Certain function-like objects, called @dfn{special forms} and +@dfn{macros}, also accept arguments to carry out computations. +However, as explained below, these are not considered functions in +Emacs Lisp. + + Here are important terms for functions and function-like objects: @table @dfn -@item function -@cindex function -In Emacs Lisp, a @dfn{function} is anything that can be applied to -arguments in a Lisp program. In some cases, we use it more -specifically to mean a function written in Lisp. Special forms and -macros are not functions. +@item lambda expression +A function (in the strict sense, i.e.@: a function object) which is +written in Lisp. These are described in the following section. +@ifnottex +@xref{Lambda Expressions}. +@end ifnottex @item primitive @cindex primitive @cindex subr @cindex built-in function -A @dfn{primitive} is a function callable from Lisp that is written in C, -such as @code{car} or @code{append}. These functions are also called -@dfn{built-in functions}, or @dfn{subrs}. (Special forms are also -considered primitives.) - -Usually the reason we implement a function as a primitive is either -because it is fundamental, because it provides a low-level interface -to operating system services, or because it needs to run fast. -Primitives can be modified or added only by changing the C sources and -recompiling the editor. See @ref{Writing Emacs Primitives}. - -@item lambda expression -A @dfn{lambda expression} is a function written in Lisp. -These are described in the following section. -@ifnottex -@xref{Lambda Expressions}. -@end ifnottex +A function which is callable from Lisp but is actually written in C. +Primitives are also called @dfn{built-in functions}, or @dfn{subrs}. +Examples include functions like @code{car} and @code{append}. In +addition, all special forms (see below) are also considered +primitives. + +Usually, a function is implemented as a primitive because it is a +fundamental part of Lisp (e.g.@: @code{car}), or because it provides a +low-level interface to operating system services, or because it needs +to run fast. Unlike functions defined in Lisp, primitives can be +modified or added only by changing the C sources and recompiling +Emacs. See @ref{Writing Emacs Primitives}. @item special form -A @dfn{special form} is a primitive that is like a function but does not -evaluate all of its arguments in the usual way. It may evaluate only -some of the arguments, or may evaluate them in an unusual order, or -several times. Many special forms are described in @ref{Control -Structures}. +A primitive that is like a function but does not evaluate all of its +arguments in the usual way. It may evaluate only some of the +arguments, or may evaluate them in an unusual order, or several times. +Examples include @code{if}, @code{and}, and @code{while}. +@xref{Special Forms}. @item macro @cindex macro -A @dfn{macro} is a construct defined in Lisp by the programmer. It -differs from a function in that it translates a Lisp expression that you -write into an equivalent expression to be evaluated instead of the -original expression. Macros enable Lisp programmers to do the sorts of -things that special forms can do. @xref{Macros}, for how to define and -use macros. +A construct defined in Lisp, which differs from a function in that it +translates a Lisp expression into another expression which is to be +evaluated instead of the original expression. Macros enable Lisp +programmers to do the sorts of things that special forms can do. +@xref{Macros}. @item command @cindex command -A @dfn{command} is an object that @code{command-execute} can invoke; it -is a possible definition for a key sequence. Some functions are -commands; a function written in Lisp is a command if it contains an -interactive declaration (@pxref{Defining Commands}). Such a function -can be called from Lisp expressions like other functions; in this case, -the fact that the function is a command makes no difference. +An object which can be invoked via the @code{command-execute} +primitive, usually due to the user typing in a key sequence +@dfn{bound} to that command. @xref{Interactive Call}. A command is +usually a function; if the function is written in Lisp, it is made +into a command by an @code{interactive} form in the function +definition (@pxref{Defining Commands}). Commands that are functions +can also be called from Lisp expressions, just like other functions. Keyboard macros (strings and vectors) are commands also, even though -they are not functions. A symbol is a command if its function -definition is a command; such symbols can be invoked with @kbd{M-x}. -The symbol is a function as well if the definition is a function. -@xref{Interactive Call}. - -@item keystroke command -@cindex keystroke command -A @dfn{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 Lisp programs, the distinction is normally unimportant. +they are not functions. @xref{Keyboard Macros}. We say that a symbol +is a command if its function cell contains a command (@pxref{Symbol +Components}); such a @dfn{named command} can be invoked with +@kbd{M-x}. + +@item closure +A function object that is much like a lambda expression, except that +it also encloses an ``environment'' of lexical variable bindings. +@xref{Closures}. @item byte-code function -A @dfn{byte-code function} is a function that has been compiled by the -byte compiler. @xref{Byte-Code Type}. +A function that has been compiled by the byte compiler. +@xref{Byte-Code Type}. @item autoload object @cindex autoload object -An @dfn{autoload object} is a place-holder for a real function. If -the autoload object is called, it will make Emacs load the file -containing the definition of the real function, and then call the real -function instead. +A place-holder for a real function. If the autoload object is called, +Emacs loads the file containing the definition of the real function, +and then calls the real function. @xref{Autoload}. @end table + You can use the function @code{functionp} to test if an object is a +function: + @defun functionp object This function returns @code{t} if @var{object} is any kind of function, i.e.@: can be passed to @code{funcall}. Note that -@code{functionp} returns @code{nil} for special forms (@pxref{Special -Forms}). +@code{functionp} returns @code{t} for symbols that are function names, +and returns @code{nil} for special forms. @end defun -Unlike @code{functionp}, the next three functions do @emph{not} -treat a symbol as its function definition. +@noindent +Unlike @code{functionp}, the next three functions do @emph{not} treat +a symbol as its function definition. @defun subrp object This function returns @code{t} if @var{object} is a built-in function @@ -172,21 +185,26 @@ function with @code{&rest} arguments, or the symbol @code{unevalled} if @section Lambda Expressions @cindex lambda expression - A function written in Lisp is a list that looks like this: + A lambda expression is a function object written in Lisp. Here is +an example: @example -(lambda (@var{arg-variables}@dots{}) - @r{[}@var{documentation-string}@r{]} - @r{[}@var{interactive-declaration}@r{]} - @var{body-forms}@dots{}) +(lambda (x) + "Return the hyperbolic cosine of X." + (* 0.5 (+ (exp x) (exp (- x))))) @end example @noindent -Such a list is called a @dfn{lambda expression}. In Emacs Lisp, it -actually is valid as an expression---it evaluates to itself. In some -other Lisp dialects, a lambda expression is not a valid expression at -all. In either case, its main use is not to be evaluated as an -expression, but to be called as a function. +In Emacs Lisp, such a list is valid as an expression---it evaluates to +itself. But its main use is not to be evaluated as an expression, but +to be called as a function. + + A lambda expression, by itself, has no name; it is an @dfn{anonymous +function}. Although lambda expressions can be used this way +(@pxref{Anonymous Functions}), they are more commonly associated with +symbols to make @dfn{named functions} (@pxref{Function Names}). +Before going into these details, the following subsections describe +the components of a lambda expression and what they do. @menu * Lambda Components:: The parts of a lambda expression. @@ -198,10 +216,7 @@ expression, but to be called as a function. @node Lambda Components @subsection Components of a Lambda Expression -@ifnottex - - A function written in Lisp (a ``lambda expression'') is a list that -looks like this: + A lambda expression is a list that looks like this: @example (lambda (@var{arg-variables}@dots{}) @@ -209,7 +224,6 @@ looks like this: [@var{interactive-declaration}] @var{body-forms}@dots{}) @end example -@end ifnottex @cindex lambda list The first element of a lambda expression is always the symbol @@ -243,22 +257,21 @@ code to do the work of the function (or, as a Lisp programmer would say, function is the value returned by the last element of the body. @node Simple Lambda -@subsection A Simple Lambda-Expression Example +@subsection A Simple Lambda Expression Example - Consider for example the following function: + Consider the following example: @example (lambda (a b c) (+ a b c)) @end example @noindent -We can call this function by writing it as the @sc{car} of an -expression, like this: +We can call this function by passing it to @code{funcall}, like this: @example @group -((lambda (a b c) (+ a b c)) - 1 2 3) +(funcall (lambda (a b c) (+ a b c)) + 1 2 3) @end group @end example @@ -273,8 +286,8 @@ this example: @example @group -((lambda (a b c) (+ a b c)) - 1 (* 2 3) (- 5 4)) +(funcall (lambda (a b c) (+ a b c)) + 1 (* 2 3) (- 5 4)) @end group @end example @@ -283,18 +296,15 @@ This evaluates the arguments @code{1}, @code{(* 2 3)}, and @code{(- 5 4)} from left to right. Then it applies the lambda expression to the argument values 1, 6 and 1 to produce the value 8. - It is not often useful to write a lambda expression as the @sc{car} of -a form in this way. You can get the same result, of making local -variables and giving them values, using the special form @code{let} -(@pxref{Local Variables}). And @code{let} is clearer and easier to use. -In practice, lambda expressions are either stored as the function -definitions of symbols, to produce named functions, or passed as -arguments to other functions (@pxref{Anonymous Functions}). - - However, calls to explicit lambda expressions were very useful in the -old days of Lisp, before the special form @code{let} was invented. At -that time, they were the only way to bind and initialize local -variables. + As these examples show, you can use a form with a lambda expression +as its @sc{car} to make local variables and give them values. In the +old days of Lisp, this technique was the only way to bind and +initialize local variables. But nowadays, it is clearer to use the +special form @code{let} for this purpose (@pxref{Local Variables}). +Lambda expressions are mainly used as anonymous functions for passing +as arguments to other functions (@pxref{Anonymous Functions}), or +stored as symbol function definitions to produce named functions +(@pxref{Function Names}). @node Argument List @subsection Other Features of Argument Lists @@ -388,16 +398,16 @@ after a @code{&rest} argument. Here are some examples of argument lists and proper calls: @smallexample -((lambda (n) (1+ n)) ; @r{One required:} - 1) ; @r{requires exactly one argument.} +(funcall (lambda (n) (1+ n)) ; @r{One required:} + 1) ; @r{requires exactly one argument.} @result{} 2 -((lambda (n &optional n1) ; @r{One required and one optional:} - (if n1 (+ n n1) (1+ n))) ; @r{1 or 2 arguments.} - 1 2) +(funcall (lambda (n &optional n1) ; @r{One required and one optional:} + (if n1 (+ n n1) (1+ n))) ; @r{1 or 2 arguments.} + 1 2) @result{} 3 -((lambda (n &rest ns) ; @r{One required and one rest:} - (+ n (apply '+ ns))) ; @r{1 or more arguments.} - 1 2 3 4 5) +(funcall (lambda (n &rest ns) ; @r{One required and one rest:} + (+ n (apply '+ ns))) ; @r{1 or more arguments.} + 1 2 3 4 5) @result{} 15 @end smallexample @@ -405,12 +415,12 @@ after a @code{&rest} argument. @subsection Documentation Strings of Functions @cindex documentation of function - A lambda expression may optionally have a @dfn{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 -facilities. @xref{Documentation}, for how the @var{documentation-string} is -accessed. + A lambda expression may optionally have a @dfn{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 facilities. @xref{Documentation}, for how the +documentation string is accessed. It is a good idea to provide documentation strings for all the functions in your program, even those that are called only from within @@ -463,55 +473,45 @@ way users think of the parts of the macro call. @cindex named function @cindex function 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 -@code{lambda}, a byte-code function object, 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 @dfn{function cell} -(@pxref{Symbol Components}). 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 are also -called the symbol's @dfn{function definition}. The procedure of using a -symbol's function definition in place of the symbol is called -@dfn{symbol function indirection}; see @ref{Function Indirection}. - - In practice, nearly all functions are given names in this way and -referred to through their names. For example, the symbol @code{car} works -as a function and does what it does because the primitive subr-object -@code{#} is stored in its function cell. + A symbol can serve as the name of a function. This happens when the +symbol's @dfn{function cell} (@pxref{Symbol Components}) contains a +function object (e.g.@: a lambda expression). Then the symbol itself +becomes a valid, callable function, equivalent to the function object +in its function cell. + + The contents of the function cell are also called the symbol's +@dfn{function definition}. The procedure of using a symbol's function +definition in place of the symbol is called @dfn{symbol function +indirection}; see @ref{Function Indirection}. If you have not given a +symbol a function definition, its function cell is said to be +@dfn{void}, and it cannot be used as a function. + + In practice, nearly all functions have names, and are referred to by +their names. You can create a named Lisp function by defining a +lambda expression and putting it in a function cell (@pxref{Function +Cells}). However, it is more common to use the @code{defun} special +form, described in the next section. +@ifnottex +@xref{Defining Functions}. +@end ifnottex We give functions names because it is convenient to refer to them by -their names in Lisp expressions. For primitive subr-objects such as -@code{#}, names are the only way you can refer to them: there -is no read syntax for such objects. For functions written in Lisp, the -name is more convenient to use in a call than an explicit lambda -expression. Also, a function with a name can refer to itself---it can -be recursive. Writing the function's name in its own definition is much -more convenient than making the function definition point to itself -(something that is not impossible but that has various disadvantages in -practice). - - We often identify functions with the symbols used to name them. For -example, we often speak of ``the function @code{car},'' not -distinguishing between the symbol @code{car} and the primitive -subr-object that is its function definition. For most purposes, the -distinction is not important. - - Even so, keep in mind that a function need not have a unique name. While -a given function object @emph{usually} appears in the function cell of only -one symbol, this is just a matter of convenience. It is easy to store -it in several symbols using @code{fset}; then each of the symbols is -equally well a name for the same function. - - A symbol used as a function name may also be used as a variable; these -two uses of a symbol are independent and do not conflict. (Some Lisp -dialects, such as Scheme, do not distinguish between a symbol's value -and its function definition; a symbol's value as a variable is also its -function definition.) If you have not given a symbol a function -definition, you cannot use it as a function; whether the symbol has a -value as a variable makes no difference to this. +their names in Lisp expressions. Also, a named Lisp function can +easily refer to itself---it can be recursive. Furthermore, primitives +can only be referred to textually by their names, since primitive +function objects (@pxref{Primitive Function Type}) have no read +syntax. + + A function need not have a unique name. A given function object +@emph{usually} appears in the function cell of only one symbol, but +this is just a convention. It is easy to store it in several symbols +using @code{fset}; then each of the symbols is a valid name for the +same function. + + Note that a symbol used as a function name may also be used as a +variable; these two uses of a symbol are independent and do not +conflict. (This is not the case in some dialects of Lisp, like +Scheme.) @node Defining Functions @section Defining Functions @@ -521,7 +521,7 @@ value as a variable makes no difference to this. is called @dfn{defining a function}, and it is done with the @code{defun} special form. -@defspec defun name argument-list body-forms +@defspec defun name argument-list body-forms... @code{defun} is the usual way to define new Lisp functions. It defines the symbol @var{name} as a function that looks like this: @@ -534,14 +534,9 @@ defines the symbol @var{name} as a function that looks like this: value. As described previously, @var{argument-list} is a list of argument -names and may include the keywords @code{&optional} and @code{&rest} -(@pxref{Lambda Expressions}). Also, the first two of the -@var{body-forms} may be a documentation string and an interactive -declaration. - -There is no conflict if the same symbol @var{name} is also used as a -variable, since the symbol's value cell is independent of the function -cell. @xref{Symbol Components}. +names and may include the keywords @code{&optional} and @code{&rest}. +Also, the first two of the @var{body-forms} may be a documentation +string and an interactive declaration. @xref{Lambda Components}. Here are some examples: @@ -575,7 +570,7 @@ Here are some examples: @group (defun capitalize-backwards () - "Upcase the last letter of a word." + "Upcase the last letter of the word at point." (interactive) (backward-word 1) (forward-word 1) @@ -587,9 +582,10 @@ Here are some examples: Be careful not to redefine existing functions unintentionally. @code{defun} redefines even primitive functions such as @code{car} -without any hesitation or notification. Redefining a function already -defined is often done deliberately, and there is no way to distinguish -deliberate redefinition from unintentional redefinition. +without any hesitation or notification. Emacs does not prevent you +from doing this, because redefining a function is sometimes done +deliberately, and there is no way to distinguish deliberate +redefinition from unintentional redefinition. @end defspec @cindex function aliases @@ -626,7 +622,8 @@ call the primitive's C definition directly, so changing the symbol's definition will have no effect on them. See also @code{defsubst}, which defines a function like @code{defun} -and tells the Lisp compiler to open-code it. @xref{Inline Functions}. +and tells the Lisp compiler to perform inline expansion on it. +@xref{Inline Functions}. @node Calling Functions @section Calling Functions @@ -790,18 +787,23 @@ This function returns @var{arg} and has no side effects. This function ignores any arguments and returns @code{nil}. @end defun + Some functions are user-visible @dfn{commands}, which can be called +interactively (usually by a key sequence). It is possible to invoke +such a command exactly as though it was called interactively, by using +the @code{call-interactively} function. @xref{Interactive Call}. + @node Mapping Functions @section Mapping Functions @cindex mapping functions A @dfn{mapping function} applies a given function (@emph{not} a special form or macro) to each element of a list or other collection. -Emacs Lisp has several such functions; @code{mapcar} and -@code{mapconcat}, which scan a list, are described here. -@xref{Definition of mapatoms}, for the function @code{mapatoms} which -maps over the symbols in an obarray. @xref{Definition of maphash}, -for the function @code{maphash} which maps over key/value associations -in a hash table. +Emacs Lisp has several such functions; this section describes +@code{mapcar}, @code{mapc}, and @code{mapconcat}, which map over a +list. @xref{Definition of mapatoms}, for the function @code{mapatoms} +which maps over the symbols in an obarray. @xref{Definition of +maphash}, for the function @code{maphash} which maps over key/value +associations in a hash table. These mapping functions do not allow char-tables because a char-table is a sparse array whose nominal range of indices is very large. To map @@ -892,47 +894,66 @@ bool-vector, or a string. @section Anonymous Functions @cindex anonymous function - In Lisp, a function is a list that starts with @code{lambda}, a -byte-code function compiled from such a list, or alternatively a -primitive subr-object; names are ``extra.'' Although functions are -usually defined with @code{defun} and given names at the same time, it -is occasionally more concise to use an explicit lambda expression---an -anonymous function. Such a list is valid wherever a function name is. + Although functions are usually defined with @code{defun} and given +names at the same time, it is sometimes convenient to use an explicit +lambda expression---an @dfn{anonymous function}. Anonymous functions +are valid wherever function names are. They are often assigned as +variable values, or as arguments to functions; for instance, you might +pass one as the @var{function} argument to @code{mapcar}, which +applies that function to each element of a list (@pxref{Mapping +Functions}). @xref{describe-symbols example}, for a realistic example +of this. + + When defining a lambda expression that is to be used as an anonymous +function, you can in principle use any method to construct the list. +But typically you should use the @code{lambda} macro, or the +@code{function} special form, or the @code{#'} read syntax: + +@defmac lambda args body... +This macro returns an anonymous function with argument list @var{args} +and body forms given by @var{body}. In effect, this macro makes +@code{lambda} forms ``self-quoting'': evaluating a form whose @sc{car} +is @code{lambda} yields the form itself: - Any method of creating such a list makes a valid function. Even this: +@example +(lambda (x) (* x x)) + @result{} (lambda (x) (* x x)) +@end example -@smallexample -@group -(setq silly (append '(lambda (x)) (list (list '+ (* 3 4) 'x)))) -@result{} (lambda (x) (+ 12 x)) -@end group -@end smallexample +The @code{lambda} form has one other effect: it tells the Emacs +evaluator and byte-compiler that its argument is a function, by using +@code{function} as a subroutine (see below). +@end defmac -@noindent -This computes a list that looks like @code{(lambda (x) (+ 12 x))} and -makes it the value (@emph{not} the function definition!) of -@code{silly}. +@defspec function function-object +@cindex function quoting +This special form returns @var{function-object} without evaluating it. +In this, it is similar to @code{quote} (@pxref{Quoting}). But unlike +@code{quote}, it also serves as a note to the Emacs evaluator and +byte-compiler that @var{function-object} is intended to be used as a +function. Assuming @var{function-object} is a valid lambda +expression, this has two effects: - Here is how we might call this function: +@itemize +@item +When the code is byte-compiled, @var{function-object} is compiled into +a byte-code function object (@pxref{Byte Compilation}). -@example -@group -(funcall silly 1) -@result{} 13 -@end group -@end example +@item +When lexical binding is enabled, @var{function-object} is converted +into a closure. @xref{Closures}. +@end itemize +@end defspec -@noindent -It does @emph{not} work to write @code{(silly 1)}, because this -function is not the @emph{function definition} of @code{silly}. We -have not given @code{silly} any function definition, just a value as a -variable. +@cindex @samp{#'} syntax +The read syntax @code{#'} is a short-hand for using @code{function}. +The following forms are all equivalent: - Most of the time, anonymous functions are constants that appear in -your program. For instance, you might want to pass one as an argument -to the function @code{mapcar}, which applies any given function to -each element of a list (@pxref{Mapping Functions}). -@xref{describe-symbols example}, for a realistic example of this. +@example +(lambda (x) (* x x)) +(function (lambda (x) (* x x))) +#'(lambda (x) (* x x)) +@end example In the following example, we define a @code{change-property} function that takes a function as its third argument, followed by a @@ -953,15 +974,11 @@ function that takes a function as its third argument, followed by a @end example @noindent -In the @code{double-property} function, we did not quote the -@code{lambda} form. This is permissible, because a @code{lambda} form -is @dfn{self-quoting}: evaluating the form yields the form itself. +Note that we do not quote the @code{lambda} form. -Whether or not you quote a @code{lambda} form makes a difference if -you compile the code (@pxref{Byte Compilation}). If the @code{lambda} -form is unquoted, as in the above example, the anonymous function is -also compiled. Suppose, however, that we quoted the @code{lambda} -form: + If you compile the above code, the anonymous function is also +compiled. This would not happen if, say, you had constructed the +anonymous function by quoting it as a list: @example @group @@ -971,52 +988,10 @@ form: @end example @noindent -If you compile this, the argument passed to @code{change-property} is -the precise list shown: - -@example -(lambda (x) (* x 2)) -@end example - -@noindent -The Lisp compiler cannot assume this list is a function, even though -it looks like one, since it does not know what @code{change-property} -will do with the list. Perhaps it will check whether the @sc{car} of -the third element is the symbol @code{*}! - -@findex function -The @code{function} special form explicitly tells the byte-compiler -that its argument is a function: - -@defspec function function-object -@cindex function quoting -This special form returns @var{function-object} without evaluating it. -In this, it is equivalent to @code{quote}. However, it serves as a -note to the Emacs Lisp compiler that @var{function-object} is intended -to be used only as a function, and therefore can safely be compiled. -Contrast this with @code{quote}, in @ref{Quoting}. -@end defspec - -@cindex @samp{#'} syntax -The read syntax @code{#'} is a short-hand for using @code{function}. -Generally, it is not necessary to use either @code{#'} or -@code{function}; just use an unquoted @code{lambda} form instead. -(Actually, @code{lambda} is a macro defined using @code{function}.) -The following forms are all equivalent: - -@example -#'(lambda (x) (* x x)) -(function (lambda (x) (* x x))) -(lambda (x) (* x x)) -@end example - - We sometimes write @code{function} instead of @code{quote} when -quoting the name of a function, but this usage is just a sort of -comment: - -@example -(function @var{symbol}) @equiv{} (quote @var{symbol}) @equiv{} '@var{symbol} -@end example +In that case, the anonymous function is kept as a lambda expression in +the compiled code. The byte-compiler cannot assume this list is a +function, even though it looks like one, since it does not know that +@code{change-property} intends to use it as a function. @node Function Cells @section Accessing Function Cell Contents @@ -1112,77 +1087,60 @@ This function stores @var{definition} in the function cell of this is not checked. The argument @var{symbol} is an ordinary evaluated argument. -There are three normal uses of this function: +The primary use of this function is as a subroutine by constructs that +define or alter functions, like @code{defadvice} (@pxref{Advising +Functions}). (If @code{defun} were not a primitive, it could be +written as a Lisp macro using @code{fset}.) You can also use it to +give a symbol a function definition that is not a list, e.g.@: a +keyboard macro (@pxref{Keyboard Macros}): -@itemize @bullet -@item -Copying one symbol's function definition to another---in other words, -making an alternate name for a function. (If you think of this as the -definition of the new name, you should use @code{defalias} instead of -@code{fset}; see @ref{Definition of defalias}.) +@example +;; @r{Define a named keyboard macro.} +(fset 'kill-two-lines "\^u2\^k") + @result{} "\^u2\^k" +@end example -@item -Giving a symbol a function definition that is not a list and therefore -cannot be made with @code{defun}. For example, you can use @code{fset} -to give a symbol @code{s1} a function definition which is another symbol -@code{s2}; then @code{s1} serves as an alias for whatever definition -@code{s2} presently has. (Once again use @code{defalias} instead of -@code{fset} if you think of this as the definition of @code{s1}.) +It you wish to use @code{fset} to make an alternate name for a +function, consider using @code{defalias} instead. @xref{Definition of +defalias}. +@end defun -@item -In constructs for defining or altering functions. If @code{defun} -were not a primitive, it could be written in Lisp (as a macro) using -@code{fset}. -@end itemize +@node Closures +@section Closures -Here are examples of these uses: + As explained in @ref{Variable Scoping}, Emacs can optionally enable +lexical binding of variables. When lexical binding is enabled, any +named function that you create (e.g.@: with @code{defun}), as well as +any anonymous function that you create using the @code{lambda} macro +or the @code{function} special form or the @code{#'} syntax +(@pxref{Anonymous Functions}), is automatically converted into a +closure. -@example -@group -;; @r{Save @code{foo}'s definition in @code{old-foo}.} -(fset 'old-foo (symbol-function 'foo)) -@end group + A closure is a function that also carries a record of the lexical +environment that existed when the function was defined. When it is +invoked, any lexical variable references within its definition use the +retained lexical environment. In all other respects, closures behave +much like ordinary functions; in particular, they can be called in the +same way as ordinary functions. -@group -;; @r{Make the symbol @code{car} the function definition of @code{xfirst}.} -;; @r{(Most likely, @code{defalias} would be better than @code{fset} here.)} -(fset 'xfirst 'car) - @result{} car -@end group -@group -(xfirst '(1 2 3)) - @result{} 1 -@end group -@group -(symbol-function 'xfirst) - @result{} car -@end group -@group -(symbol-function (symbol-function 'xfirst)) - @result{} # -@end group + @xref{Lexical Binding}, for an example of using a closure. -@group -;; @r{Define a named keyboard macro.} -(fset 'kill-two-lines "\^u2\^k") - @result{} "\^u2\^k" -@end group + Currently, an Emacs Lisp closure object is represented by a list +with the symbol @code{closure} as the first element, a list +representing the lexical environment as the second element, and the +argument list and body forms as the remaining elements: -@group -;; @r{Here is a function that alters other functions.} -(defun copy-function-definition (new old) - "Define NEW with the same function definition as OLD." - (fset new (symbol-function old))) -@end group +@example +;; @r{lexical binding is enabled.} +(lambda (x) (* x x)) + @result{} (closure (t) (x) (* x x)) @end example -@end defun - @code{fset} is sometimes used to save the old definition of a -function before redefining it. That permits the new definition to -invoke the old definition. But it is unmodular and unclean for a Lisp -file to redefine a function defined elsewhere. If you want to modify -a function defined by another package, it is cleaner to use -@code{defadvice} (@pxref{Advising Functions}). +@noindent +However, the fact that the internal structure of a closure is +``exposed'' to the rest of the Lisp world is considered an internal +implementation detail. For this reason, we recommend against directly +examining or altering the structure of closure objects. @node Obsolete Functions @section Declaring Functions Obsolete @@ -1248,41 +1206,46 @@ this: @section Inline Functions @cindex inline functions -@findex defsubst -You can define an @dfn{inline function} by using @code{defsubst} instead -of @code{defun}. An inline function works just like an ordinary -function except for one thing: when you compile a call to the function, -the function's definition is open-coded into the caller. +@defmac defsubst name argument-list body-forms... +Define an inline function. The syntax is exactly the same as +@code{defun} (@pxref{Defining Functions}). +@end defmac + + You can define an @dfn{inline function} by using @code{defsubst} +instead of @code{defun}. An inline function works just like an +ordinary function except for one thing: when you byte-compile a call +to the function (@pxref{Byte Compilation}), the function's definition +is expanded into the caller. -Making a function inline makes explicit calls run faster. But it also -has disadvantages. For one thing, it reduces flexibility; if you -change the definition of the function, calls already inlined still use -the old definition until you recompile them. + Making a function inline often makes its function calls run faster. +But it also has disadvantages. For one thing, it reduces flexibility; +if you change the definition of the function, calls already inlined +still use the old definition until you recompile them. -Another disadvantage is that making a large function inline can increase -the size of compiled code both in files and in memory. Since the speed -advantage of inline functions is greatest for small functions, you -generally should not make large functions inline. + Another disadvantage is that making a large function inline can +increase the size of compiled code both in files and in memory. Since +the speed advantage of inline functions is greatest for small +functions, you generally should not make large functions inline. -Also, inline functions do not behave well with respect to debugging, + Also, inline functions do not behave well with respect to debugging, tracing, and advising (@pxref{Advising Functions}). Since ease of debugging and the flexibility of redefining functions are important features of Emacs, you should not make a function inline, even if it's small, unless its speed is really crucial, and you've timed the code to verify that using @code{defun} actually has performance problems. -It's possible to define a macro to expand into the same code that an -inline function would execute. (@xref{Macros}.) But the macro would be -limited to direct use in expressions---a macro cannot be called with -@code{apply}, @code{mapcar} and so on. Also, it takes some work to -convert an ordinary function into a macro. To convert it into an inline -function is very easy; simply replace @code{defun} with @code{defsubst}. -Since each argument of an inline function is evaluated exactly once, you -needn't worry about how many times the body uses the arguments, as you -do for macros. (@xref{Argument Evaluation}.) + It's possible to define a macro to expand into the same code that an +inline function would execute (@pxref{Macros}). But the macro would +be limited to direct use in expressions---a macro cannot be called +with @code{apply}, @code{mapcar} and so on. Also, it takes some work +to convert an ordinary function into a macro. To convert it into an +inline function is easy; just replace @code{defun} with +@code{defsubst}. Since each argument of an inline function is +evaluated exactly once, you needn't worry about how many times the +body uses the arguments, as you do for macros. -Inline functions can be used and open-coded later on in the same file, -following the definition, just like macros. + After an inline function is defined, its inline expansion can be +performed later on in the same file, just like macros. @node Declaring Functions @section Telling the Compiler that a Function is Defined @@ -1346,12 +1309,10 @@ definition using @code{locate-library}; if that finds no file, they expand the definition file name relative to the directory of the file that contains the @code{declare-function} call. - You can also say that a function is defined by C code by specifying a -file name ending in @samp{.c} or @samp{.m}. @code{check-declare-file} -looks for these files in the C source code directory. This is useful -only when you call a function that is defined only on certain systems. -Most of the primitive functions of Emacs are always defined so they will -never give you a warning. + You can also say that a function is a primitive by specifying a file +name ending in @samp{.c} or @samp{.m}. This is useful only when you +call a primitive that is defined only on certain systems. Most +primitives are always defined, so they will never give you a warning. Sometimes a file will optionally use functions from an external package. If you prefix the filename in the @code{declare-function} statement with