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