Merge from emacs-24; up to 2012-05-08T14:11:47Z!monnier@iro.umontreal.ca
[emacs.git] / doc / lispref / functions.texi
blob845561f91ec674e4de71be270c9beb116b07a94b
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998-1999, 2001-2012
4 @c   Free Software Foundation, Inc.
5 @c See the file elisp.texi for copying conditions.
6 @node Functions
7 @chapter Functions
9   A Lisp program is composed mainly of Lisp functions.  This chapter
10 explains what functions are, how they accept arguments, and how to
11 define them.
13 @menu
14 * What Is a Function::    Lisp functions vs. primitives; terminology.
15 * Lambda Expressions::    How functions are expressed as Lisp objects.
16 * Function Names::        A symbol can serve as the name of a function.
17 * Defining Functions::    Lisp expressions for defining functions.
18 * Calling Functions::     How to use an existing function.
19 * Mapping Functions::     Applying a function to each element of a list, etc.
20 * Anonymous Functions::   Lambda expressions are functions with no names.
21 * Function Cells::        Accessing or setting the function definition
22                             of a symbol.
23 * Closures::              Functions that enclose a lexical environment.
24 * Obsolete Functions::    Declaring functions obsolete.
25 * Inline Functions::      Functions that the compiler will expand inline.
26 * Declare Form::          Adding additional information about a function.
27 * Declaring Functions::   Telling the compiler that a function is defined.
28 * Function Safety::       Determining whether a function is safe to call.
29 * Related Topics::        Cross-references to specific Lisp primitives
30                             that have a special bearing on how functions work.
31 @end menu
33 @node What Is a Function
34 @section What Is a Function?
36 @cindex return value
37 @cindex value of function
38 @cindex argument
39   In a general sense, a function is a rule for carrying out a
40 computation given input values called @dfn{arguments}.  The result of
41 the computation is called the @dfn{value} or @dfn{return value} of the
42 function.  The computation can also have side effects, such as lasting
43 changes in the values of variables or the contents of data structures.
45   In most computer languages, every function has a name.  But in Lisp,
46 a function in the strictest sense has no name: it is an object which
47 can @emph{optionally} be associated with a symbol (e.g.@: @code{car})
48 that serves as the function name.  @xref{Function Names}.  When a
49 function has been given a name, we usually also refer to that symbol
50 as a ``function'' (e.g.@: we refer to ``the function @code{car}'').
51 In this manual, the distinction between a function name and the
52 function object itself is usually unimportant, but we will take note
53 wherever it is relevant.
55   Certain function-like objects, called @dfn{special forms} and
56 @dfn{macros}, also accept arguments to carry out computations.
57 However, as explained below, these are not considered functions in
58 Emacs Lisp.
60   Here are important terms for functions and function-like objects:
62 @table @dfn
63 @item lambda expression
64 A function (in the strict sense, i.e.@: a function object) which is
65 written in Lisp.  These are described in the following section.
66 @ifnottex
67 @xref{Lambda Expressions}.
68 @end ifnottex
70 @item primitive
71 @cindex primitive
72 @cindex subr
73 @cindex built-in function
74 A function which is callable from Lisp but is actually written in C.
75 Primitives are also called @dfn{built-in functions}, or @dfn{subrs}.
76 Examples include functions like @code{car} and @code{append}.  In
77 addition, all special forms (see below) are also considered
78 primitives.
80 Usually, a function is implemented as a primitive because it is a
81 fundamental part of Lisp (e.g.@: @code{car}), or because it provides a
82 low-level interface to operating system services, or because it needs
83 to run fast.  Unlike functions defined in Lisp, primitives can be
84 modified or added only by changing the C sources and recompiling
85 Emacs.  See @ref{Writing Emacs Primitives}.
87 @item special form
88 A primitive that is like a function but does not evaluate all of its
89 arguments in the usual way.  It may evaluate only some of the
90 arguments, or may evaluate them in an unusual order, or several times.
91 Examples include @code{if}, @code{and}, and @code{while}.
92 @xref{Special Forms}.
94 @item macro
95 @cindex macro
96 A construct defined in Lisp, which differs from a function in that it
97 translates a Lisp expression into another expression which is to be
98 evaluated instead of the original expression.  Macros enable Lisp
99 programmers to do the sorts of things that special forms can do.
100 @xref{Macros}.
102 @item command
103 @cindex command
104 An object which can be invoked via the @code{command-execute}
105 primitive, usually due to the user typing in a key sequence
106 @dfn{bound} to that command.  @xref{Interactive Call}.  A command is
107 usually a function; if the function is written in Lisp, it is made
108 into a command by an @code{interactive} form in the function
109 definition (@pxref{Defining Commands}).  Commands that are functions
110 can also be called from Lisp expressions, just like other functions.
112 Keyboard macros (strings and vectors) are commands also, even though
113 they are not functions.  @xref{Keyboard Macros}.  We say that a symbol
114 is a command if its function cell contains a command (@pxref{Symbol
115 Components}); such a @dfn{named command} can be invoked with
116 @kbd{M-x}.
118 @item closure
119 A function object that is much like a lambda expression, except that
120 it also encloses an ``environment'' of lexical variable bindings.
121 @xref{Closures}.
123 @item byte-code function
124 A function that has been compiled by the byte compiler.
125 @xref{Byte-Code Type}.
127 @item autoload object
128 @cindex autoload object
129 A place-holder for a real function.  If the autoload object is called,
130 Emacs loads the file containing the definition of the real function,
131 and then calls the real function.  @xref{Autoload}.
132 @end table
134   You can use the function @code{functionp} to test if an object is a
135 function:
137 @defun functionp object
138 This function returns @code{t} if @var{object} is any kind of
139 function, i.e.@: can be passed to @code{funcall}.  Note that
140 @code{functionp} returns @code{t} for symbols that are function names,
141 and returns @code{nil} for special forms.
142 @end defun
144 @noindent
145 Unlike @code{functionp}, the next three functions do @emph{not} treat
146 a symbol as its function definition.
148 @defun subrp object
149 This function returns @code{t} if @var{object} is a built-in function
150 (i.e., a Lisp primitive).
152 @example
153 @group
154 (subrp 'message)            ; @r{@code{message} is a symbol,}
155      @result{} nil                 ;   @r{not a subr object.}
156 @end group
157 @group
158 (subrp (symbol-function 'message))
159      @result{} t
160 @end group
161 @end example
162 @end defun
164 @defun byte-code-function-p object
165 This function returns @code{t} if @var{object} is a byte-code
166 function.  For example:
168 @example
169 @group
170 (byte-code-function-p (symbol-function 'next-line))
171      @result{} t
172 @end group
173 @end example
174 @end defun
176 @defun subr-arity subr
177 This function provides information about the argument list of a
178 primitive, @var{subr}.  The returned value is a pair
179 @code{(@var{min} . @var{max})}.  @var{min} is the minimum number of
180 args.  @var{max} is the maximum number or the symbol @code{many}, for a
181 function with @code{&rest} arguments, or the symbol @code{unevalled} if
182 @var{subr} is a special form.
183 @end defun
185 @node Lambda Expressions
186 @section Lambda Expressions
187 @cindex lambda expression
189   A lambda expression is a function object written in Lisp.  Here is
190 an example:
192 @example
193 (lambda (x)
194   "Return the hyperbolic cosine of X."
195   (* 0.5 (+ (exp x) (exp (- x)))))
196 @end example
198 @noindent
199 In Emacs Lisp, such a list is valid as an expression---it evaluates to
200 itself.  But its main use is not to be evaluated as an expression, but
201 to be called as a function.
203   A lambda expression, by itself, has no name; it is an @dfn{anonymous
204 function}.  Although lambda expressions can be used this way
205 (@pxref{Anonymous Functions}), they are more commonly associated with
206 symbols to make @dfn{named functions} (@pxref{Function Names}).
207 Before going into these details, the following subsections describe
208 the components of a lambda expression and what they do.
210 @menu
211 * Lambda Components::       The parts of a lambda expression.
212 * Simple Lambda::           A simple example.
213 * Argument List::           Details and special features of argument lists.
214 * Function Documentation::  How to put documentation in a function.
215 @end menu
217 @node Lambda Components
218 @subsection Components of a Lambda Expression
220   A lambda expression is a list that looks like this:
222 @example
223 (lambda (@var{arg-variables}@dots{})
224   [@var{documentation-string}]
225   [@var{interactive-declaration}]
226   @var{body-forms}@dots{})
227 @end example
229 @cindex lambda list
230   The first element of a lambda expression is always the symbol
231 @code{lambda}.  This indicates that the list represents a function.  The
232 reason functions are defined to start with @code{lambda} is so that
233 other lists, intended for other uses, will not accidentally be valid as
234 functions.
236   The second element is a list of symbols---the argument variable names.
237 This is called the @dfn{lambda list}.  When a Lisp function is called,
238 the argument values are matched up against the variables in the lambda
239 list, which are given local bindings with the values provided.
240 @xref{Local Variables}.
242   The documentation string is a Lisp string object placed within the
243 function definition to describe the function for the Emacs help
244 facilities.  @xref{Function Documentation}.
246   The interactive declaration is a list of the form @code{(interactive
247 @var{code-string})}.  This declares how to provide arguments if the
248 function is used interactively.  Functions with this declaration are called
249 @dfn{commands}; they can be called using @kbd{M-x} or bound to a key.
250 Functions not intended to be called in this way should not have interactive
251 declarations.  @xref{Defining Commands}, for how to write an interactive
252 declaration.
254 @cindex body of function
255   The rest of the elements are the @dfn{body} of the function: the Lisp
256 code to do the work of the function (or, as a Lisp programmer would say,
257 ``a list of Lisp forms to evaluate'').  The value returned by the
258 function is the value returned by the last element of the body.
260 @node Simple Lambda
261 @subsection A Simple Lambda Expression Example
263   Consider the following example:
265 @example
266 (lambda (a b c) (+ a b c))
267 @end example
269 @noindent
270 We can call this function by passing it to @code{funcall}, like this:
272 @example
273 @group
274 (funcall (lambda (a b c) (+ a b c))
275          1 2 3)
276 @end group
277 @end example
279 @noindent
280 This call evaluates the body of the lambda expression  with the variable
281 @code{a} bound to 1, @code{b} bound to 2, and @code{c} bound to 3.
282 Evaluation of the body adds these three numbers, producing the result 6;
283 therefore, this call to the function returns the value 6.
285   Note that the arguments can be the results of other function calls, as in
286 this example:
288 @example
289 @group
290 (funcall (lambda (a b c) (+ a b c))
291          1 (* 2 3) (- 5 4))
292 @end group
293 @end example
295 @noindent
296 This evaluates the arguments @code{1}, @code{(* 2 3)}, and @code{(- 5
297 4)} from left to right.  Then it applies the lambda expression to the
298 argument values 1, 6 and 1 to produce the value 8.
300   As these examples show, you can use a form with a lambda expression
301 as its @sc{car} to make local variables and give them values.  In the
302 old days of Lisp, this technique was the only way to bind and
303 initialize local variables.  But nowadays, it is clearer to use the
304 special form @code{let} for this purpose (@pxref{Local Variables}).
305 Lambda expressions are mainly used as anonymous functions for passing
306 as arguments to other functions (@pxref{Anonymous Functions}), or
307 stored as symbol function definitions to produce named functions
308 (@pxref{Function Names}).
310 @node Argument List
311 @subsection Other Features of Argument Lists
312 @kindex wrong-number-of-arguments
313 @cindex argument binding
314 @cindex binding arguments
315 @cindex argument lists, features
317   Our simple sample function, @code{(lambda (a b c) (+ a b c))},
318 specifies three argument variables, so it must be called with three
319 arguments: if you try to call it with only two arguments or four
320 arguments, you get a @code{wrong-number-of-arguments} error.
322   It is often convenient to write a function that allows certain
323 arguments to be omitted.  For example, the function @code{substring}
324 accepts three arguments---a string, the start index and the end
325 index---but the third argument defaults to the @var{length} of the
326 string if you omit it.  It is also convenient for certain functions to
327 accept an indefinite number of arguments, as the functions @code{list}
328 and @code{+} do.
330 @cindex optional arguments
331 @cindex rest arguments
332 @kindex &optional
333 @kindex &rest
334   To specify optional arguments that may be omitted when a function
335 is called, simply include the keyword @code{&optional} before the optional
336 arguments.  To specify a list of zero or more extra arguments, include the
337 keyword @code{&rest} before one final argument.
339   Thus, the complete syntax for an argument list is as follows:
341 @example
342 @group
343 (@var{required-vars}@dots{}
344  @r{[}&optional @var{optional-vars}@dots{}@r{]}
345  @r{[}&rest @var{rest-var}@r{]})
346 @end group
347 @end example
349 @noindent
350 The square brackets indicate that the @code{&optional} and @code{&rest}
351 clauses, and the variables that follow them, are optional.
353   A call to the function requires one actual argument for each of the
354 @var{required-vars}.  There may be actual arguments for zero or more of
355 the @var{optional-vars}, and there cannot be any actual arguments beyond
356 that unless the lambda list uses @code{&rest}.  In that case, there may
357 be any number of extra actual arguments.
359   If actual arguments for the optional and rest variables are omitted,
360 then they always default to @code{nil}.  There is no way for the
361 function to distinguish between an explicit argument of @code{nil} and
362 an omitted argument.  However, the body of the function is free to
363 consider @code{nil} an abbreviation for some other meaningful value.
364 This is what @code{substring} does; @code{nil} as the third argument to
365 @code{substring} means to use the length of the string supplied.
367 @cindex CL note---default optional arg
368 @quotation
369 @b{Common Lisp note:} Common Lisp allows the function to specify what
370 default value to use when an optional argument is omitted; Emacs Lisp
371 always uses @code{nil}.  Emacs Lisp does not support ``supplied-p''
372 variables that tell you whether an argument was explicitly passed.
373 @end quotation
375   For example, an argument list that looks like this:
377 @example
378 (a b &optional c d &rest e)
379 @end example
381 @noindent
382 binds @code{a} and @code{b} to the first two actual arguments, which are
383 required.  If one or two more arguments are provided, @code{c} and
384 @code{d} are bound to them respectively; any arguments after the first
385 four are collected into a list and @code{e} is bound to that list.  If
386 there are only two arguments, @code{c} is @code{nil}; if two or three
387 arguments, @code{d} is @code{nil}; if four arguments or fewer, @code{e}
388 is @code{nil}.
390   There is no way to have required arguments following optional
391 ones---it would not make sense.  To see why this must be so, suppose
392 that @code{c} in the example were optional and @code{d} were required.
393 Suppose three actual arguments are given; which variable would the
394 third argument be for?  Would it be used for the @var{c}, or for
395 @var{d}?  One can argue for both possibilities.  Similarly, it makes
396 no sense to have any more arguments (either required or optional)
397 after a @code{&rest} argument.
399   Here are some examples of argument lists and proper calls:
401 @example
402 (funcall (lambda (n) (1+ n))        ; @r{One required:}
403          1)                         ; @r{requires exactly one argument.}
404      @result{} 2
405 (funcall (lambda (n &optional n1)   ; @r{One required and one optional:}
406            (if n1 (+ n n1) (1+ n))) ; @r{1 or 2 arguments.}
407          1 2)
408      @result{} 3
409 (funcall (lambda (n &rest ns)       ; @r{One required and one rest:}
410            (+ n (apply '+ ns)))     ; @r{1 or more arguments.}
411          1 2 3 4 5)
412      @result{} 15
413 @end example
415 @node Function Documentation
416 @subsection Documentation Strings of Functions
417 @cindex documentation of function
419   A lambda expression may optionally have a @dfn{documentation string}
420 just after the lambda list.  This string does not affect execution of
421 the function; it is a kind of comment, but a systematized comment
422 which actually appears inside the Lisp world and can be used by the
423 Emacs help facilities.  @xref{Documentation}, for how the
424 documentation string is accessed.
426   It is a good idea to provide documentation strings for all the
427 functions in your program, even those that are called only from within
428 your program.  Documentation strings are like comments, except that they
429 are easier to access.
431   The first line of the documentation string should stand on its own,
432 because @code{apropos} displays just this first line.  It should consist
433 of one or two complete sentences that summarize the function's purpose.
435   The start of the documentation string is usually indented in the
436 source file, but since these spaces come before the starting
437 double-quote, they are not part of the string.  Some people make a
438 practice of indenting any additional lines of the string so that the
439 text lines up in the program source.  @emph{That is a mistake.}  The
440 indentation of the following lines is inside the string; what looks
441 nice in the source code will look ugly when displayed by the help
442 commands.
444   You may wonder how the documentation string could be optional, since
445 there are required components of the function that follow it (the body).
446 Since evaluation of a string returns that string, without any side effects,
447 it has no effect if it is not the last form in the body.  Thus, in
448 practice, there is no confusion between the first form of the body and the
449 documentation string; if the only body form is a string then it serves both
450 as the return value and as the documentation.
452   The last line of the documentation string can specify calling
453 conventions different from the actual function arguments.  Write
454 text like this:
456 @example
457 \(fn @var{arglist})
458 @end example
460 @noindent
461 following a blank line, at the beginning of the line, with no newline
462 following it inside the documentation string.  (The @samp{\} is used
463 to avoid confusing the Emacs motion commands.)  The calling convention
464 specified in this way appears in help messages in place of the one
465 derived from the actual arguments of the function.
467   This feature is particularly useful for macro definitions, since the
468 arguments written in a macro definition often do not correspond to the
469 way users think of the parts of the macro call.
471 @node Function Names
472 @section Naming a Function
473 @cindex function definition
474 @cindex named function
475 @cindex function name
477   A symbol can serve as the name of a function.  This happens when the
478 symbol's @dfn{function cell} (@pxref{Symbol Components}) contains a
479 function object (e.g.@: a lambda expression).  Then the symbol itself
480 becomes a valid, callable function, equivalent to the function object
481 in its function cell.
483   The contents of the function cell are also called the symbol's
484 @dfn{function definition}.  The procedure of using a symbol's function
485 definition in place of the symbol is called @dfn{symbol function
486 indirection}; see @ref{Function Indirection}.  If you have not given a
487 symbol a function definition, its function cell is said to be
488 @dfn{void}, and it cannot be used as a function.
490   In practice, nearly all functions have names, and are referred to by
491 their names.  You can create a named Lisp function by defining a
492 lambda expression and putting it in a function cell (@pxref{Function
493 Cells}).  However, it is more common to use the @code{defun} special
494 form, described in the next section.
495 @ifnottex
496 @xref{Defining Functions}.
497 @end ifnottex
499   We give functions names because it is convenient to refer to them by
500 their names in Lisp expressions.  Also, a named Lisp function can
501 easily refer to itself---it can be recursive.  Furthermore, primitives
502 can only be referred to textually by their names, since primitive
503 function objects (@pxref{Primitive Function Type}) have no read
504 syntax.
506   A function need not have a unique name.  A given function object
507 @emph{usually} appears in the function cell of only one symbol, but
508 this is just a convention.  It is easy to store it in several symbols
509 using @code{fset}; then each of the symbols is a valid name for the
510 same function.
512   Note that a symbol used as a function name may also be used as a
513 variable; these two uses of a symbol are independent and do not
514 conflict.  (This is not the case in some dialects of Lisp, like
515 Scheme.)
517 @node Defining Functions
518 @section Defining Functions
519 @cindex defining a function
521   We usually give a name to a function when it is first created.  This
522 is called @dfn{defining a function}, and it is done with the
523 @code{defun} special form.
525 @defmac defun name argument-list body-forms...
526 @code{defun} is the usual way to define new Lisp functions.  It
527 defines the symbol @var{name} as a function that looks like this:
529 @example
530 (lambda @var{argument-list} . @var{body-forms})
531 @end example
533 @code{defun} stores this lambda expression in the function cell of
534 @var{name}.  Its return value is @emph{undefined}.
536 As described previously, @var{argument-list} is a list of argument
537 names and may include the keywords @code{&optional} and @code{&rest}.
538 Also, the first two of the @var{body-forms} may be a documentation
539 string and an interactive declaration.  @xref{Lambda Components}.
541 Here are some examples:
543 @example
544 @group
545 (defun foo () 5)
546 (foo)
547      @result{} 5
548 @end group
550 @group
551 (defun bar (a &optional b &rest c)
552     (list a b c))
553 (bar 1 2 3 4 5)
554      @result{} (1 2 (3 4 5))
555 @end group
556 @group
557 (bar 1)
558      @result{} (1 nil nil)
559 @end group
560 @group
561 (bar)
562 @error{} Wrong number of arguments.
563 @end group
565 @group
566 (defun capitalize-backwards ()
567   "Upcase the last letter of the word at point."
568   (interactive)
569   (backward-word 1)
570   (forward-word 1)
571   (backward-char 1)
572   (capitalize-word 1))
573 @end group
574 @end example
576 Be careful not to redefine existing functions unintentionally.
577 @code{defun} redefines even primitive functions such as @code{car}
578 without any hesitation or notification.  Emacs does not prevent you
579 from doing this, because redefining a function is sometimes done
580 deliberately, and there is no way to distinguish deliberate
581 redefinition from unintentional redefinition.
582 @end defmac
584 @cindex function aliases
585 @defun defalias name definition &optional docstring
586 @anchor{Definition of defalias}
587 This special form defines the symbol @var{name} as a function, with
588 definition @var{definition} (which can be any valid Lisp function).
589 Its return value is @emph{undefined}.
591 If @var{docstring} is non-@code{nil}, it becomes the function
592 documentation of @var{name}.  Otherwise, any documentation provided by
593 @var{definition} is used.
595 The proper place to use @code{defalias} is where a specific function
596 name is being defined---especially where that name appears explicitly in
597 the source file being loaded.  This is because @code{defalias} records
598 which file defined the function, just like @code{defun}
599 (@pxref{Unloading}).
601 By contrast, in programs that manipulate function definitions for other
602 purposes, it is better to use @code{fset}, which does not keep such
603 records.  @xref{Function Cells}.
604 @end defun
606   You cannot create a new primitive function with @code{defun} or
607 @code{defalias}, but you can use them to change the function definition of
608 any symbol, even one such as @code{car} or @code{x-popup-menu} whose
609 normal definition is a primitive.  However, this is risky: for
610 instance, it is next to impossible to redefine @code{car} without
611 breaking Lisp completely.  Redefining an obscure function such as
612 @code{x-popup-menu} is less dangerous, but it still may not work as
613 you expect.  If there are calls to the primitive from C code, they
614 call the primitive's C definition directly, so changing the symbol's
615 definition will have no effect on them.
617   See also @code{defsubst}, which defines a function like @code{defun}
618 and tells the Lisp compiler to perform inline expansion on it.
619 @xref{Inline Functions}.
621 @node Calling Functions
622 @section Calling Functions
623 @cindex function invocation
624 @cindex calling a function
626   Defining functions is only half the battle.  Functions don't do
627 anything until you @dfn{call} them, i.e., tell them to run.  Calling a
628 function is also known as @dfn{invocation}.
630   The most common way of invoking a function is by evaluating a list.
631 For example, evaluating the list @code{(concat "a" "b")} calls the
632 function @code{concat} with arguments @code{"a"} and @code{"b"}.
633 @xref{Evaluation}, for a description of evaluation.
635   When you write a list as an expression in your program, you specify
636 which function to call, and how many arguments to give it, in the text
637 of the program.  Usually that's just what you want.  Occasionally you
638 need to compute at run time which function to call.  To do that, use
639 the function @code{funcall}.  When you also need to determine at run
640 time how many arguments to pass, use @code{apply}.
642 @defun funcall function &rest arguments
643 @code{funcall} calls @var{function} with @var{arguments}, and returns
644 whatever @var{function} returns.
646 Since @code{funcall} is a function, all of its arguments, including
647 @var{function}, are evaluated before @code{funcall} is called.  This
648 means that you can use any expression to obtain the function to be
649 called.  It also means that @code{funcall} does not see the
650 expressions you write for the @var{arguments}, only their values.
651 These values are @emph{not} evaluated a second time in the act of
652 calling @var{function}; the operation of @code{funcall} is like the
653 normal procedure for calling a function, once its arguments have
654 already been evaluated.
656 The argument @var{function} must be either a Lisp function or a
657 primitive function.  Special forms and macros are not allowed, because
658 they make sense only when given the ``unevaluated'' argument
659 expressions.  @code{funcall} cannot provide these because, as we saw
660 above, it never knows them in the first place.
662 @example
663 @group
664 (setq f 'list)
665      @result{} list
666 @end group
667 @group
668 (funcall f 'x 'y 'z)
669      @result{} (x y z)
670 @end group
671 @group
672 (funcall f 'x 'y '(z))
673      @result{} (x y (z))
674 @end group
675 @group
676 (funcall 'and t nil)
677 @error{} Invalid function: #<subr and>
678 @end group
679 @end example
681 Compare these examples with the examples of @code{apply}.
682 @end defun
684 @defun apply function &rest arguments
685 @code{apply} calls @var{function} with @var{arguments}, just like
686 @code{funcall} but with one difference: the last of @var{arguments} is a
687 list of objects, which are passed to @var{function} as separate
688 arguments, rather than a single list.  We say that @code{apply}
689 @dfn{spreads} this list so that each individual element becomes an
690 argument.
692 @code{apply} returns the result of calling @var{function}.  As with
693 @code{funcall}, @var{function} must either be a Lisp function or a
694 primitive function; special forms and macros do not make sense in
695 @code{apply}.
697 @example
698 @group
699 (setq f 'list)
700      @result{} list
701 @end group
702 @group
703 (apply f 'x 'y 'z)
704 @error{} Wrong type argument: listp, z
705 @end group
706 @group
707 (apply '+ 1 2 '(3 4))
708      @result{} 10
709 @end group
710 @group
711 (apply '+ '(1 2 3 4))
712      @result{} 10
713 @end group
715 @group
716 (apply 'append '((a b c) nil (x y z) nil))
717      @result{} (a b c x y z)
718 @end group
719 @end example
721 For an interesting example of using @code{apply}, see @ref{Definition
722 of mapcar}.
723 @end defun
725 @cindex partial application of functions
726 @cindex currying
727   Sometimes it is useful to fix some of the function's arguments at
728 certain values, and leave the rest of arguments for when the function
729 is actually called.  The act of fixing some of the function's
730 arguments is called @dfn{partial application} of the function@footnote{
731 This is related to, but different from @dfn{currying}, which
732 transforms a function that takes multiple arguments in such a way that
733 it can be called as a chain of functions, each one with a single
734 argument.}.
735 The result is a new function that accepts the rest of
736 arguments and calls the original function with all the arguments
737 combined.
739   Here's how to do partial application in Emacs Lisp:
741 @defun apply-partially func &rest args
742 This function returns a new function which, when called, will call
743 @var{func} with the list of arguments composed from @var{args} and
744 additional arguments specified at the time of the call.  If @var{func}
745 accepts @var{n} arguments, then a call to @code{apply-partially} with
746 @w{@code{@var{m} < @var{n}}} arguments will produce a new function of
747 @w{@code{@var{n} - @var{m}}} arguments.
749 Here's how we could define the built-in function @code{1+}, if it
750 didn't exist, using @code{apply-partially} and @code{+}, another
751 built-in function:
753 @example
754 @group
755 (defalias '1+ (apply-partially '+ 1)
756   "Increment argument by one.")
757 @end group
758 @group
759 (1+ 10)
760      @result{} 11
761 @end group
762 @end example
763 @end defun
765 @cindex functionals
766   It is common for Lisp functions to accept functions as arguments or
767 find them in data structures (especially in hook variables and property
768 lists) and call them using @code{funcall} or @code{apply}.  Functions
769 that accept function arguments are often called @dfn{functionals}.
771   Sometimes, when you call a functional, it is useful to supply a no-op
772 function as the argument.  Here are two different kinds of no-op
773 function:
775 @defun identity arg
776 This function returns @var{arg} and has no side effects.
777 @end defun
779 @defun ignore &rest args
780 This function ignores any arguments and returns @code{nil}.
781 @end defun
783   Some functions are user-visible @dfn{commands}, which can be called
784 interactively (usually by a key sequence).  It is possible to invoke
785 such a command exactly as though it was called interactively, by using
786 the @code{call-interactively} function.  @xref{Interactive Call}.
788 @node Mapping Functions
789 @section Mapping Functions
790 @cindex mapping functions
792   A @dfn{mapping function} applies a given function (@emph{not} a
793 special form or macro) to each element of a list or other collection.
794 Emacs Lisp has several such functions; this section describes
795 @code{mapcar}, @code{mapc}, and @code{mapconcat}, which map over a
796 list.  @xref{Definition of mapatoms}, for the function @code{mapatoms}
797 which maps over the symbols in an obarray.  @xref{Definition of
798 maphash}, for the function @code{maphash} which maps over key/value
799 associations in a hash table.
801   These mapping functions do not allow char-tables because a char-table
802 is a sparse array whose nominal range of indices is very large.  To map
803 over a char-table in a way that deals properly with its sparse nature,
804 use the function @code{map-char-table} (@pxref{Char-Tables}).
806 @defun mapcar function sequence
807 @anchor{Definition of mapcar}
808 @code{mapcar} applies @var{function} to each element of @var{sequence}
809 in turn, and returns a list of the results.
811 The argument @var{sequence} can be any kind of sequence except a
812 char-table; that is, a list, a vector, a bool-vector, or a string.  The
813 result is always a list.  The length of the result is the same as the
814 length of @var{sequence}.  For example:
816 @example
817 @group
818 (mapcar 'car '((a b) (c d) (e f)))
819      @result{} (a c e)
820 (mapcar '1+ [1 2 3])
821      @result{} (2 3 4)
822 (mapcar 'string "abc")
823      @result{} ("a" "b" "c")
824 @end group
826 @group
827 ;; @r{Call each function in @code{my-hooks}.}
828 (mapcar 'funcall my-hooks)
829 @end group
831 @group
832 (defun mapcar* (function &rest args)
833   "Apply FUNCTION to successive cars of all ARGS.
834 Return the list of results."
835   ;; @r{If no list is exhausted,}
836   (if (not (memq nil args))
837       ;; @r{apply function to @sc{car}s.}
838       (cons (apply function (mapcar 'car args))
839             (apply 'mapcar* function
840                    ;; @r{Recurse for rest of elements.}
841                    (mapcar 'cdr args)))))
842 @end group
844 @group
845 (mapcar* 'cons '(a b c) '(1 2 3 4))
846      @result{} ((a . 1) (b . 2) (c . 3))
847 @end group
848 @end example
849 @end defun
851 @defun mapc function sequence
852 @code{mapc} is like @code{mapcar} except that @var{function} is used for
853 side-effects only---the values it returns are ignored, not collected
854 into a list.  @code{mapc} always returns @var{sequence}.
855 @end defun
857 @defun mapconcat function sequence separator
858 @code{mapconcat} applies @var{function} to each element of
859 @var{sequence}: the results, which must be strings, are concatenated.
860 Between each pair of result strings, @code{mapconcat} inserts the string
861 @var{separator}.  Usually @var{separator} contains a space or comma or
862 other suitable punctuation.
864 The argument @var{function} must be a function that can take one
865 argument and return a string.  The argument @var{sequence} can be any
866 kind of sequence except a char-table; that is, a list, a vector, a
867 bool-vector, or a string.
869 @example
870 @group
871 (mapconcat 'symbol-name
872            '(The cat in the hat)
873            " ")
874      @result{} "The cat in the hat"
875 @end group
877 @group
878 (mapconcat (function (lambda (x) (format "%c" (1+ x))))
879            "HAL-8000"
880            "")
881      @result{} "IBM.9111"
882 @end group
883 @end example
884 @end defun
886 @node Anonymous Functions
887 @section Anonymous Functions
888 @cindex anonymous function
890   Although functions are usually defined with @code{defun} and given
891 names at the same time, it is sometimes convenient to use an explicit
892 lambda expression---an @dfn{anonymous function}.  Anonymous functions
893 are valid wherever function names are.  They are often assigned as
894 variable values, or as arguments to functions; for instance, you might
895 pass one as the @var{function} argument to @code{mapcar}, which
896 applies that function to each element of a list (@pxref{Mapping
897 Functions}).  @xref{describe-symbols example}, for a realistic example
898 of this.
900   When defining a lambda expression that is to be used as an anonymous
901 function, you can in principle use any method to construct the list.
902 But typically you should use the @code{lambda} macro, or the
903 @code{function} special form, or the @code{#'} read syntax:
905 @defmac lambda args body...
906 This macro returns an anonymous function with argument list @var{args}
907 and body forms given by @var{body}.  In effect, this macro makes
908 @code{lambda} forms ``self-quoting'': evaluating a form whose @sc{car}
909 is @code{lambda} yields the form itself:
911 @example
912 (lambda (x) (* x x))
913      @result{} (lambda (x) (* x x))
914 @end example
916 The @code{lambda} form has one other effect: it tells the Emacs
917 evaluator and byte-compiler that its argument is a function, by using
918 @code{function} as a subroutine (see below).
919 @end defmac
921 @defspec function function-object
922 @cindex function quoting
923 This special form returns @var{function-object} without evaluating it.
924 In this, it is similar to @code{quote} (@pxref{Quoting}).  But unlike
925 @code{quote}, it also serves as a note to the Emacs evaluator and
926 byte-compiler that @var{function-object} is intended to be used as a
927 function.  Assuming @var{function-object} is a valid lambda
928 expression, this has two effects:
930 @itemize
931 @item
932 When the code is byte-compiled, @var{function-object} is compiled into
933 a byte-code function object (@pxref{Byte Compilation}).
935 @item
936 When lexical binding is enabled, @var{function-object} is converted
937 into a closure.  @xref{Closures}.
938 @end itemize
939 @end defspec
941 @cindex @samp{#'} syntax
942 The read syntax @code{#'} is a short-hand for using @code{function}.
943 The following forms are all equivalent:
945 @example
946 (lambda (x) (* x x))
947 (function (lambda (x) (* x x)))
948 #'(lambda (x) (* x x))
949 @end example
951   In the following example, we define a @code{change-property}
952 function that takes a function as its third argument, followed by a
953 @code{double-property} function that makes use of
954 @code{change-property} by passing it an anonymous function:
956 @example
957 @group
958 (defun change-property (symbol prop function)
959   (let ((value (get symbol prop)))
960     (put symbol prop (funcall function value))))
961 @end group
963 @group
964 (defun double-property (symbol prop)
965   (change-property symbol prop (lambda (x) (* 2 x))))
966 @end group
967 @end example
969 @noindent
970 Note that we do not quote the @code{lambda} form.
972   If you compile the above code, the anonymous function is also
973 compiled.  This would not happen if, say, you had constructed the
974 anonymous function by quoting it as a list:
976 @example
977 @group
978 (defun double-property (symbol prop)
979   (change-property symbol prop '(lambda (x) (* 2 x))))
980 @end group
981 @end example
983 @noindent
984 In that case, the anonymous function is kept as a lambda expression in
985 the compiled code.  The byte-compiler cannot assume this list is a
986 function, even though it looks like one, since it does not know that
987 @code{change-property} intends to use it as a function.
989 @node Function Cells
990 @section Accessing Function Cell Contents
992   The @dfn{function definition} of a symbol is the object stored in the
993 function cell of the symbol.  The functions described here access, test,
994 and set the function cell of symbols.
996   See also the function @code{indirect-function}.  @xref{Definition of
997 indirect-function}.
999 @defun symbol-function symbol
1000 @kindex void-function
1001 This returns the object in the function cell of @var{symbol}.  If the
1002 symbol's function cell is void, a @code{void-function} error is
1003 signaled.
1005 This function does not check that the returned object is a legitimate
1006 function.
1008 @example
1009 @group
1010 (defun bar (n) (+ n 2))
1011 (symbol-function 'bar)
1012      @result{} (lambda (n) (+ n 2))
1013 @end group
1014 @group
1015 (fset 'baz 'bar)
1016      @result{} bar
1017 @end group
1018 @group
1019 (symbol-function 'baz)
1020      @result{} bar
1021 @end group
1022 @end example
1023 @end defun
1025 @cindex void function cell
1026   If you have never given a symbol any function definition, we say that
1027 that symbol's function cell is @dfn{void}.  In other words, the function
1028 cell does not have any Lisp object in it.  If you try to call such a symbol
1029 as a function, it signals a @code{void-function} error.
1031   Note that void is not the same as @code{nil} or the symbol
1032 @code{void}.  The symbols @code{nil} and @code{void} are Lisp objects,
1033 and can be stored into a function cell just as any other object can be
1034 (and they can be valid functions if you define them in turn with
1035 @code{defun}).  A void function cell contains no object whatsoever.
1037   You can test the voidness of a symbol's function definition with
1038 @code{fboundp}.  After you have given a symbol a function definition, you
1039 can make it void once more using @code{fmakunbound}.
1041 @defun fboundp symbol
1042 This function returns @code{t} if the symbol has an object in its
1043 function cell, @code{nil} otherwise.  It does not check that the object
1044 is a legitimate function.
1045 @end defun
1047 @defun fmakunbound symbol
1048 This function makes @var{symbol}'s function cell void, so that a
1049 subsequent attempt to access this cell will cause a
1050 @code{void-function} error.  It returns @var{symbol}.  (See also
1051 @code{makunbound}, in @ref{Void Variables}.)
1053 @example
1054 @group
1055 (defun foo (x) x)
1056 (foo 1)
1057      @result{}1
1058 @end group
1059 @group
1060 (fmakunbound 'foo)
1061      @result{} foo
1062 @end group
1063 @group
1064 (foo 1)
1065 @error{} Symbol's function definition is void: foo
1066 @end group
1067 @end example
1068 @end defun
1070 @defun fset symbol definition
1071 This function stores @var{definition} in the function cell of
1072 @var{symbol}.  The result is @var{definition}.  Normally
1073 @var{definition} should be a function or the name of a function, but
1074 this is not checked.  The argument @var{symbol} is an ordinary evaluated
1075 argument.
1077 The primary use of this function is as a subroutine by constructs that
1078 define or alter functions, like @code{defadvice} (@pxref{Advising
1079 Functions}).  (If @code{defun} were not a primitive, it could be
1080 written as a Lisp macro using @code{fset}.)  You can also use it to
1081 give a symbol a function definition that is not a list, e.g.@: a
1082 keyboard macro (@pxref{Keyboard Macros}):
1084 @example
1085 ;; @r{Define a named keyboard macro.}
1086 (fset 'kill-two-lines "\^u2\^k")
1087      @result{} "\^u2\^k"
1088 @end example
1090 It you wish to use @code{fset} to make an alternate name for a
1091 function, consider using @code{defalias} instead.  @xref{Definition of
1092 defalias}.
1093 @end defun
1095 @node Closures
1096 @section Closures
1098   As explained in @ref{Variable Scoping}, Emacs can optionally enable
1099 lexical binding of variables.  When lexical binding is enabled, any
1100 named function that you create (e.g.@: with @code{defun}), as well as
1101 any anonymous function that you create using the @code{lambda} macro
1102 or the @code{function} special form or the @code{#'} syntax
1103 (@pxref{Anonymous Functions}), is automatically converted into a
1104 @dfn{closure}.
1106 @cindex closure
1107   A closure is a function that also carries a record of the lexical
1108 environment that existed when the function was defined.  When it is
1109 invoked, any lexical variable references within its definition use the
1110 retained lexical environment.  In all other respects, closures behave
1111 much like ordinary functions; in particular, they can be called in the
1112 same way as ordinary functions.
1114   @xref{Lexical Binding}, for an example of using a closure.
1116   Currently, an Emacs Lisp closure object is represented by a list
1117 with the symbol @code{closure} as the first element, a list
1118 representing the lexical environment as the second element, and the
1119 argument list and body forms as the remaining elements:
1121 @example
1122 ;; @r{lexical binding is enabled.}
1123 (lambda (x) (* x x))
1124      @result{} (closure (t) (x) (* x x))
1125 @end example
1127 @noindent
1128 However, the fact that the internal structure of a closure is
1129 ``exposed'' to the rest of the Lisp world is considered an internal
1130 implementation detail.  For this reason, we recommend against directly
1131 examining or altering the structure of closure objects.
1133 @node Obsolete Functions
1134 @section Declaring Functions Obsolete
1136   You can mark a named function as @dfn{obsolete}, meaning that it may
1137 be removed at some point in the future.  This causes Emacs to warn
1138 that the function is obsolete whenever it byte-compiles code
1139 containing that function, and whenever it displays the documentation
1140 for that function.  In all other respects, an obsolete function
1141 behaves like any other function.
1143   The easiest way to mark a function as obsolete is to put a
1144 @code{(declare (obsolete @dots{}))} form in the function's
1145 @code{defun} definition.  @xref{Declare Form}.  Alternatively, you can
1146 use the @code{make-obsolete} function, described below.
1148   A macro (@pxref{Macros}) can also be marked obsolete with
1149 @code{make-obsolete}; this has the same effects as for a function.  An
1150 alias for a function or macro can also be marked as obsolete; this
1151 makes the alias itself obsolete, not the function or macro which it
1152 resolves to.
1154 @defun make-obsolete obsolete-name current-name &optional when
1155 This function marks @var{obsolete-name} as obsolete.
1156 @var{obsolete-name} should be a symbol naming a function or macro, or
1157 an alias for a function or macro.
1159 If @var{current-name} is a symbol, the warning message says to use
1160 @var{current-name} instead of @var{obsolete-name}.  @var{current-name}
1161 does not need to be an alias for @var{obsolete-name}; it can be a
1162 different function with similar functionality.  @var{current-name} can
1163 also be a string, which serves as the warning message.  The message
1164 should begin in lower case, and end with a period.  It can also be
1165 @code{nil}, in which case the warning message provides no additional
1166 details.
1168 If provided, @var{when} should be a string indicating when the function
1169 was first made obsolete---for example, a date or a release number.
1170 @end defun
1172 @defmac define-obsolete-function-alias obsolete-name current-name &optional when docstring
1173 This convenience macro marks the function @var{obsolete-name} obsolete
1174 and also defines it as an alias for the function @var{current-name}.
1175 It is equivalent to the following:
1177 @example
1178 (defalias @var{obsolete-name} @var{current-name} @var{docstring})
1179 (make-obsolete @var{obsolete-name} @var{current-name} @var{when})
1180 @end example
1181 @end defmac
1183 In addition, you can mark a certain a particular calling convention
1184 for a function as obsolete:
1186 @defun set-advertised-calling-convention function signature when
1187 This function specifies the argument list @var{signature} as the
1188 correct way to call @var{function}.  This causes the Emacs byte
1189 compiler to issue a warning whenever it comes across an Emacs Lisp
1190 program that calls @var{function} any other way (however, it will
1191 still allow the code to be byte compiled).  @var{when} should be a
1192 string indicating when the variable was first made obsolete (usually a
1193 version number string).
1195 For instance, in old versions of Emacs the @code{sit-for} function
1196 accepted three arguments, like this
1198 @example
1199   (sit-for seconds milliseconds nodisp)
1200 @end example
1202 However, calling @code{sit-for} this way is considered obsolete
1203 (@pxref{Waiting}).  The old calling convention is deprecated like
1204 this:
1206 @example
1207 (set-advertised-calling-convention
1208   'sit-for '(seconds &optional nodisp) "22.1")
1209 @end example
1210 @end defun
1212 @node Inline Functions
1213 @section Inline Functions
1214 @cindex inline functions
1216 @defmac defsubst name argument-list body-forms...
1217 Define an inline function.  The syntax is exactly the same as
1218 @code{defun} (@pxref{Defining Functions}).
1219 @end defmac
1221   You can define an @dfn{inline function} by using @code{defsubst}
1222 instead of @code{defun}.  An inline function works just like an
1223 ordinary function except for one thing: when you byte-compile a call
1224 to the function (@pxref{Byte Compilation}), the function's definition
1225 is expanded into the caller.
1227   Making a function inline often makes its function calls run faster.
1228 But it also has disadvantages.  For one thing, it reduces flexibility;
1229 if you change the definition of the function, calls already inlined
1230 still use the old definition until you recompile them.
1232   Another disadvantage is that making a large function inline can
1233 increase the size of compiled code both in files and in memory.  Since
1234 the speed advantage of inline functions is greatest for small
1235 functions, you generally should not make large functions inline.
1237   Also, inline functions do not behave well with respect to debugging,
1238 tracing, and advising (@pxref{Advising Functions}).  Since ease of
1239 debugging and the flexibility of redefining functions are important
1240 features of Emacs, you should not make a function inline, even if it's
1241 small, unless its speed is really crucial, and you've timed the code
1242 to verify that using @code{defun} actually has performance problems.
1244   It's possible to define a macro to expand into the same code that an
1245 inline function would execute (@pxref{Macros}).  But the macro would
1246 be limited to direct use in expressions---a macro cannot be called
1247 with @code{apply}, @code{mapcar} and so on.  Also, it takes some work
1248 to convert an ordinary function into a macro.  To convert it into an
1249 inline function is easy; just replace @code{defun} with
1250 @code{defsubst}.  Since each argument of an inline function is
1251 evaluated exactly once, you needn't worry about how many times the
1252 body uses the arguments, as you do for macros.
1254   After an inline function is defined, its inline expansion can be
1255 performed later on in the same file, just like macros.
1257 @node Declare Form
1258 @section The @code{declare} Form
1259 @findex declare
1261   @code{declare} is a special macro which can be used to add ``meta''
1262 properties to a function or macro: for example, marking it as
1263 obsolete, or giving its forms a special @key{TAB} indentation
1264 convention in Emacs Lisp mode.
1266 @anchor{Definition of declare}
1267 @defmac declare @var{specs}@dots{}
1268 This macro ignores its arguments and evaluates to @code{nil}; it has
1269 no run-time effect.  However, when a @code{declare} form occurs as the
1270 @emph{very first form} in the body of a @code{defun} function
1271 definition or a @code{defmacro} macro definition (@pxref{Defining
1272 Macros}, for a description of @code{defmacro}), it appends the
1273 properties specified by @var{specs} to the function or macro.  This
1274 work is specially performed by the @code{defun} and @code{defmacro}
1275 macros.
1277 Note that if you put a @code{declare} form in an interactive function,
1278 it should go before the @code{interactive} form.
1280 Each element in @var{specs} should have the form @code{(@var{property}
1281 @var{args}@dots{})}, which should not be quoted.  These have the
1282 following effects:
1284 @table @code
1285 @item (advertised-calling-convention @var{signature} @var{when})
1286 This acts like a call to @code{set-advertised-calling-convention}
1287 (@pxref{Obsolete Functions}); @var{signature} specifies the correct
1288 argument list for calling the function or macro, and @var{when} should
1289 be a string indicating when the variable was first made obsolete.
1291 @item (debug @var{edebug-form-spec})
1292 This is valid for macros only.  When stepping through the macro with
1293 Edebug, use @var{edebug-form-spec}.  @xref{Instrumenting Macro Calls}.
1295 @item (doc-string @var{n})
1296 Use element number @var{n}, if any, as the documentation string.
1298 @item (indent @var{indent-spec})
1299 Indent calls to this function or macro according to @var{indent-spec}.
1300 This is typically used for macros, though it works for functions too.
1301 @xref{Indenting Macros}.
1303 @item (obsolete @var{current-name} @var{when})
1304 Mark the function or macro as obsolete, similar to a call to
1305 @code{make-obsolete} (@pxref{Obsolete Functions}).  @var{current-name}
1306 should be a symbol (in which case the warning message says to use that
1307 instead), a string (specifying the warning message), or @code{nil} (in
1308 which case the warning message gives no extra details).  @var{when}
1309 should be a string indicating when the function or macro was first
1310 made obsolete.
1311 @end table
1312 @end defmac
1314 @node Declaring Functions
1315 @section Telling the Compiler that a Function is Defined
1316 @cindex function declaration
1317 @cindex declaring functions
1318 @findex declare-function
1320 Byte-compiling a file often produces warnings about functions that the
1321 compiler doesn't know about (@pxref{Compiler Errors}).  Sometimes this
1322 indicates a real problem, but usually the functions in question are
1323 defined in other files which would be loaded if that code is run.  For
1324 example, byte-compiling @file{fortran.el} used to warn:
1326 @example
1327 In end of data:
1328 fortran.el:2152:1:Warning: the function `gud-find-c-expr' is not
1329     known to be defined.
1330 @end example
1332 In fact, @code{gud-find-c-expr} is only used in the function that
1333 Fortran mode uses for the local value of
1334 @code{gud-find-expr-function}, which is a callback from GUD; if it is
1335 called, the GUD functions will be loaded.  When you know that such a
1336 warning does not indicate a real problem, it is good to suppress the
1337 warning.  That makes new warnings which might mean real problems more
1338 visible.  You do that with @code{declare-function}.
1340 All you need to do is add a @code{declare-function} statement before the
1341 first use of the function in question:
1343 @example
1344 (declare-function gud-find-c-expr "gud.el" nil)
1345 @end example
1347 This says that @code{gud-find-c-expr} is defined in @file{gud.el} (the
1348 @samp{.el} can be omitted).  The compiler takes for granted that that file
1349 really defines the function, and does not check.
1351   The optional third argument specifies the argument list of
1352 @code{gud-find-c-expr}.  In this case, it takes no arguments
1353 (@code{nil} is different from not specifying a value).  In other
1354 cases, this might be something like @code{(file &optional overwrite)}.
1355 You don't have to specify the argument list, but if you do the
1356 byte compiler can check that the calls match the declaration.
1358 @defmac declare-function function file &optional arglist fileonly
1359 Tell the byte compiler to assume that @var{function} is defined, with
1360 arguments @var{arglist}, and that the definition should come from the
1361 file @var{file}.  @var{fileonly} non-@code{nil} means only check that
1362 @var{file} exists, not that it actually defines @var{function}.
1363 @end defmac
1365   To verify that these functions really are declared where
1366 @code{declare-function} says they are, use @code{check-declare-file}
1367 to check all @code{declare-function} calls in one source file, or use
1368 @code{check-declare-directory} check all the files in and under a
1369 certain directory.
1371   These commands find the file that ought to contain a function's
1372 definition using @code{locate-library}; if that finds no file, they
1373 expand the definition file name relative to the directory of the file
1374 that contains the @code{declare-function} call.
1376   You can also say that a function is a primitive by specifying a file
1377 name ending in @samp{.c} or @samp{.m}.  This is useful only when you
1378 call a primitive that is defined only on certain systems.  Most
1379 primitives are always defined, so they will never give you a warning.
1381   Sometimes a file will optionally use functions from an external package.
1382 If you prefix the filename in the @code{declare-function} statement with
1383 @samp{ext:}, then it will be checked if it is found, otherwise skipped
1384 without error.
1386   There are some function definitions that @samp{check-declare} does not
1387 understand (e.g. @code{defstruct} and some other macros).  In such cases,
1388 you can pass a non-@code{nil} @var{fileonly} argument to
1389 @code{declare-function}, meaning to only check that the file exists, not
1390 that it actually defines the function.  Note that to do this without
1391 having to specify an argument list, you should set the @var{arglist}
1392 argument to @code{t} (because @code{nil} means an empty argument list, as
1393 opposed to an unspecified one).
1395 @node Function Safety
1396 @section Determining whether a Function is Safe to Call
1397 @cindex function safety
1398 @cindex safety of functions
1400 Some major modes, such as SES, call functions that are stored in user
1401 files.  (@inforef{Top, ,ses}, for more information on SES.)  User
1402 files sometimes have poor pedigrees---you can get a spreadsheet from
1403 someone you've just met, or you can get one through email from someone
1404 you've never met.  So it is risky to call a function whose source code
1405 is stored in a user file until you have determined that it is safe.
1407 @defun unsafep form &optional unsafep-vars
1408 Returns @code{nil} if @var{form} is a @dfn{safe} Lisp expression, or
1409 returns a list that describes why it might be unsafe.  The argument
1410 @var{unsafep-vars} is a list of symbols known to have temporary
1411 bindings at this point; it is mainly used for internal recursive
1412 calls.  The current buffer is an implicit argument, which provides a
1413 list of buffer-local bindings.
1414 @end defun
1416 Being quick and simple, @code{unsafep} does a very light analysis and
1417 rejects many Lisp expressions that are actually safe.  There are no
1418 known cases where @code{unsafep} returns @code{nil} for an unsafe
1419 expression.  However, a ``safe'' Lisp expression can return a string
1420 with a @code{display} property, containing an associated Lisp
1421 expression to be executed after the string is inserted into a buffer.
1422 This associated expression can be a virus.  In order to be safe, you
1423 must delete properties from all strings calculated by user code before
1424 inserting them into buffers.
1426 @ignore
1427 What is a safe Lisp expression?  Basically, it's an expression that
1428 calls only built-in functions with no side effects (or only innocuous
1429 ones).  Innocuous side effects include displaying messages and
1430 altering non-risky buffer-local variables (but not global variables).
1432 @table @dfn
1433 @item Safe expression
1434 @itemize
1435 @item
1436 An atom or quoted thing.
1437 @item
1438 A call to a safe function (see below), if all its arguments are
1439 safe expressions.
1440 @item
1441 One of the special forms @code{and}, @code{catch}, @code{cond},
1442 @code{if}, @code{or}, @code{prog1}, @code{prog2}, @code{progn},
1443 @code{while}, and @code{unwind-protect}], if all its arguments are
1444 safe.
1445 @item
1446 A form that creates temporary bindings (@code{condition-case},
1447 @code{dolist}, @code{dotimes}, @code{lambda}, @code{let}, or
1448 @code{let*}), if all args are safe and the symbols to be bound are not
1449 explicitly risky (see @pxref{File Local Variables}).
1450 @item
1451 An assignment using @code{add-to-list}, @code{setq}, @code{push}, or
1452 @code{pop}, if all args are safe and the symbols to be assigned are
1453 not explicitly risky and they already have temporary or buffer-local
1454 bindings.
1455 @item
1456 One of [apply, mapc, mapcar, mapconcat] if the first argument is a
1457 safe explicit lambda and the other args are safe expressions.
1458 @end itemize
1460 @item Safe function
1461 @itemize
1462 @item
1463 A lambda containing safe expressions.
1464 @item
1465 A symbol on the list @code{safe-functions}, so the user says it's safe.
1466 @item
1467 A symbol with a non-@code{nil} @code{side-effect-free} property.
1468 @item
1469 A symbol with a non-@code{nil} @code{safe-function} property.  The
1470 value @code{t} indicates a function that is safe but has innocuous
1471 side effects.  Other values will someday indicate functions with
1472 classes of side effects that are not always safe.
1473 @end itemize
1475 The @code{side-effect-free} and @code{safe-function} properties are
1476 provided for built-in functions and for low-level functions and macros
1477 defined in @file{subr.el}.  You can assign these properties for the
1478 functions you write.
1479 @end table
1480 @end ignore
1482 @node Related Topics
1483 @section Other Topics Related to Functions
1485   Here is a table of several functions that do things related to
1486 function calling and function definitions.  They are documented
1487 elsewhere, but we provide cross references here.
1489 @table @code
1490 @item apply
1491 See @ref{Calling Functions}.
1493 @item autoload
1494 See @ref{Autoload}.
1496 @item call-interactively
1497 See @ref{Interactive Call}.
1499 @item called-interactively-p
1500 See @ref{Distinguish Interactive}.
1502 @item commandp
1503 See @ref{Interactive Call}.
1505 @item documentation
1506 See @ref{Accessing Documentation}.
1508 @item eval
1509 See @ref{Eval}.
1511 @item funcall
1512 See @ref{Calling Functions}.
1514 @item function
1515 See @ref{Anonymous Functions}.
1517 @item ignore
1518 See @ref{Calling Functions}.
1520 @item indirect-function
1521 See @ref{Function Indirection}.
1523 @item interactive
1524 See @ref{Using Interactive}.
1526 @item interactive-p
1527 See @ref{Distinguish Interactive}.
1529 @item mapatoms
1530 See @ref{Creating Symbols}.
1532 @item mapcar
1533 See @ref{Mapping Functions}.
1535 @item map-char-table
1536 See @ref{Char-Tables}.
1538 @item mapconcat
1539 See @ref{Mapping Functions}.
1541 @item undefined
1542 See @ref{Functions for Key Lookup}.
1543 @end table