]> code.delx.au - gnu-emacs/blob - doc/lispref/functions.texi
Doc fixes for fclist and grep
[gnu-emacs] / doc / lispref / functions.texi
1 @c -*- mode: texinfo; coding: utf-8 -*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998-1999, 2001-2016 Free Software
4 @c Foundation, Inc.
5 @c See the file elisp.texi for copying conditions.
6 @node Functions
7 @chapter Functions
8
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.
12
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 * Generic Functions:: Polymorphism, Emacs-style.
22 * Function Cells:: Accessing or setting the function definition
23 of a symbol.
24 * Closures:: Functions that enclose a lexical environment.
25 * Advising Functions:: Adding to the definition of a function.
26 * Obsolete Functions:: Declaring functions obsolete.
27 * Inline Functions:: Functions that the compiler will expand inline.
28 * Declare Form:: Adding additional information about a function.
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 @cindex return value
39 @cindex value of function
40 @cindex argument
41 In a general sense, a function is a rule for carrying out a
42 computation given input values called @dfn{arguments}. The result of
43 the computation is called the @dfn{value} or @dfn{return value} of the
44 function. The computation can also have side effects, such as lasting
45 changes in the values of variables or the contents of data structures.
46
47 In most computer languages, every function has a name. But in Lisp,
48 a function in the strictest sense has no name: it is an object which
49 can @emph{optionally} be associated with a symbol (e.g., @code{car})
50 that serves as the function name. @xref{Function Names}. When a
51 function has been given a name, we usually also refer to that symbol
52 as a ``function'' (e.g., we refer to ``the function @code{car}'').
53 In this manual, the distinction between a function name and the
54 function object itself is usually unimportant, but we will take note
55 wherever it is relevant.
56
57 Certain function-like objects, called @dfn{special forms} and
58 @dfn{macros}, also accept arguments to carry out computations.
59 However, as explained below, these are not considered functions in
60 Emacs Lisp.
61
62 Here are important terms for functions and function-like objects:
63
64 @table @dfn
65 @item lambda expression
66 A function (in the strict sense, i.e., a function object) which is
67 written in Lisp. These are described in the following section.
68 @ifnottex
69 @xref{Lambda Expressions}.
70 @end ifnottex
71
72 @item primitive
73 @cindex primitive
74 @cindex subr
75 @cindex built-in function
76 A function which is callable from Lisp but is actually written in C@.
77 Primitives are also called @dfn{built-in functions}, or @dfn{subrs}.
78 Examples include functions like @code{car} and @code{append}. In
79 addition, all special forms (see below) are also considered
80 primitives.
81
82 Usually, a function is implemented as a primitive because it is a
83 fundamental part of Lisp (e.g., @code{car}), or because it provides a
84 low-level interface to operating system services, or because it needs
85 to run fast. Unlike functions defined in Lisp, primitives can be
86 modified or added only by changing the C sources and recompiling
87 Emacs. See @ref{Writing Emacs Primitives}.
88
89 @item special form
90 A primitive that is like a function but does not evaluate all of its
91 arguments in the usual way. It may evaluate only some of the
92 arguments, or may evaluate them in an unusual order, or several times.
93 Examples include @code{if}, @code{and}, and @code{while}.
94 @xref{Special Forms}.
95
96 @item macro
97 @cindex macro
98 A construct defined in Lisp, which differs from a function in that it
99 translates a Lisp expression into another expression which is to be
100 evaluated instead of the original expression. Macros enable Lisp
101 programmers to do the sorts of things that special forms can do.
102 @xref{Macros}.
103
104 @item command
105 @cindex command
106 An object which can be invoked via the @code{command-execute}
107 primitive, usually due to the user typing in a key sequence
108 @dfn{bound} to that command. @xref{Interactive Call}. A command is
109 usually a function; if the function is written in Lisp, it is made
110 into a command by an @code{interactive} form in the function
111 definition (@pxref{Defining Commands}). Commands that are functions
112 can also be called from Lisp expressions, just like other functions.
113
114 Keyboard macros (strings and vectors) are commands also, even though
115 they are not functions. @xref{Keyboard Macros}. We say that a symbol
116 is a command if its function cell contains a command (@pxref{Symbol
117 Components}); such a @dfn{named command} can be invoked with
118 @kbd{M-x}.
119
120 @item closure
121 A function object that is much like a lambda expression, except that
122 it also encloses an environment of lexical variable bindings.
123 @xref{Closures}.
124
125 @item byte-code function
126 A function that has been compiled by the byte compiler.
127 @xref{Byte-Code Type}.
128
129 @item autoload object
130 @cindex autoload object
131 A place-holder for a real function. If the autoload object is called,
132 Emacs loads the file containing the definition of the real function,
133 and then calls the real function. @xref{Autoload}.
134 @end table
135
136 You can use the function @code{functionp} to test if an object is a
137 function:
138
139 @defun functionp object
140 This function returns @code{t} if @var{object} is any kind of
141 function, i.e., can be passed to @code{funcall}. Note that
142 @code{functionp} returns @code{t} for symbols that are function names,
143 and returns @code{nil} for special forms.
144 @end defun
145
146 @noindent
147 Unlike @code{functionp}, the next three functions do @emph{not} treat
148 a symbol as its function definition.
149
150 @defun subrp object
151 This function returns @code{t} if @var{object} is a built-in function
152 (i.e., a Lisp primitive).
153
154 @example
155 @group
156 (subrp 'message) ; @r{@code{message} is a symbol,}
157 @result{} nil ; @r{not a subr object.}
158 @end group
159 @group
160 (subrp (symbol-function 'message))
161 @result{} t
162 @end group
163 @end example
164 @end defun
165
166 @defun byte-code-function-p object
167 This function returns @code{t} if @var{object} is a byte-code
168 function. For example:
169
170 @example
171 @group
172 (byte-code-function-p (symbol-function 'next-line))
173 @result{} t
174 @end group
175 @end example
176 @end defun
177
178 @defun subr-arity subr
179 This function provides information about the argument list of a
180 primitive, @var{subr}. The returned value is a pair
181 @code{(@var{min} . @var{max})}. @var{min} is the minimum number of
182 args. @var{max} is the maximum number or the symbol @code{many}, for a
183 function with @code{&rest} arguments, or the symbol @code{unevalled} if
184 @var{subr} is a special form.
185 @end defun
186
187 @node Lambda Expressions
188 @section Lambda Expressions
189 @cindex lambda expression
190
191 A lambda expression is a function object written in Lisp. Here is
192 an example:
193
194 @example
195 (lambda (x)
196 "Return the hyperbolic cosine of X."
197 (* 0.5 (+ (exp x) (exp (- x)))))
198 @end example
199
200 @noindent
201 In Emacs Lisp, such a list is a valid expression which evaluates to
202 a function object.
203
204 A lambda expression, by itself, has no name; it is an @dfn{anonymous
205 function}. Although lambda expressions can be used this way
206 (@pxref{Anonymous Functions}), they are more commonly associated with
207 symbols to make @dfn{named functions} (@pxref{Function Names}).
208 Before going into these details, the following subsections describe
209 the components of a lambda expression and what they do.
210
211 @menu
212 * Lambda Components:: The parts of a lambda expression.
213 * Simple Lambda:: A simple example.
214 * Argument List:: Details and special features of argument lists.
215 * Function Documentation:: How to put documentation in a function.
216 @end menu
217
218 @node Lambda Components
219 @subsection Components of a Lambda Expression
220
221 A lambda expression is a list that looks like this:
222
223 @example
224 (lambda (@var{arg-variables}@dots{})
225 [@var{documentation-string}]
226 [@var{interactive-declaration}]
227 @var{body-forms}@dots{})
228 @end example
229
230 @cindex lambda list
231 The first element of a lambda expression is always the symbol
232 @code{lambda}. This indicates that the list represents a function. The
233 reason functions are defined to start with @code{lambda} is so that
234 other lists, intended for other uses, will not accidentally be valid as
235 functions.
236
237 The second element is a list of symbols---the argument variable names.
238 This is called the @dfn{lambda list}. When a Lisp function is called,
239 the argument values are matched up against the variables in the lambda
240 list, which are given local bindings with the values provided.
241 @xref{Local Variables}.
242
243 The documentation string is a Lisp string object placed within the
244 function definition to describe the function for the Emacs help
245 facilities. @xref{Function Documentation}.
246
247 The interactive declaration is a list of the form @code{(interactive
248 @var{code-string})}. This declares how to provide arguments if the
249 function is used interactively. Functions with this declaration are called
250 @dfn{commands}; they can be called using @kbd{M-x} or bound to a key.
251 Functions not intended to be called in this way should not have interactive
252 declarations. @xref{Defining Commands}, for how to write an interactive
253 declaration.
254
255 @cindex body of function
256 The rest of the elements are the @dfn{body} of the function: the Lisp
257 code to do the work of the function (or, as a Lisp programmer would say,
258 ``a list of Lisp forms to evaluate''). The value returned by the
259 function is the value returned by the last element of the body.
260
261 @node Simple Lambda
262 @subsection A Simple Lambda Expression Example
263
264 Consider the following example:
265
266 @example
267 (lambda (a b c) (+ a b c))
268 @end example
269
270 @noindent
271 We can call this function by passing it to @code{funcall}, like this:
272
273 @example
274 @group
275 (funcall (lambda (a b c) (+ a b c))
276 1 2 3)
277 @end group
278 @end example
279
280 @noindent
281 This call evaluates the body of the lambda expression with the variable
282 @code{a} bound to 1, @code{b} bound to 2, and @code{c} bound to 3.
283 Evaluation of the body adds these three numbers, producing the result 6;
284 therefore, this call to the function returns the value 6.
285
286 Note that the arguments can be the results of other function calls, as in
287 this example:
288
289 @example
290 @group
291 (funcall (lambda (a b c) (+ a b c))
292 1 (* 2 3) (- 5 4))
293 @end group
294 @end example
295
296 @noindent
297 This evaluates the arguments @code{1}, @code{(* 2 3)}, and @code{(- 5
298 4)} from left to right. Then it applies the lambda expression to the
299 argument values 1, 6 and 1 to produce the value 8.
300
301 As these examples show, you can use a form with a lambda expression
302 as its @sc{car} to make local variables and give them values. In the
303 old days of Lisp, this technique was the only way to bind and
304 initialize local variables. But nowadays, it is clearer to use the
305 special form @code{let} for this purpose (@pxref{Local Variables}).
306 Lambda expressions are mainly used as anonymous functions for passing
307 as arguments to other functions (@pxref{Anonymous Functions}), or
308 stored as symbol function definitions to produce named functions
309 (@pxref{Function Names}).
310
311 @node Argument List
312 @subsection Other Features of Argument Lists
313 @kindex wrong-number-of-arguments
314 @cindex argument binding
315 @cindex binding arguments
316 @cindex argument lists, features
317
318 Our simple sample function, @code{(lambda (a b c) (+ a b c))},
319 specifies three argument variables, so it must be called with three
320 arguments: if you try to call it with only two arguments or four
321 arguments, you get a @code{wrong-number-of-arguments} error.
322
323 It is often convenient to write a function that allows certain
324 arguments to be omitted. For example, the function @code{substring}
325 accepts three arguments---a string, the start index and the end
326 index---but the third argument defaults to the @var{length} of the
327 string if you omit it. It is also convenient for certain functions to
328 accept an indefinite number of arguments, as the functions @code{list}
329 and @code{+} do.
330
331 @cindex optional arguments
332 @cindex rest arguments
333 @kindex &optional
334 @kindex &rest
335 To specify optional arguments that may be omitted when a function
336 is called, simply include the keyword @code{&optional} before the optional
337 arguments. To specify a list of zero or more extra arguments, include the
338 keyword @code{&rest} before one final argument.
339
340 Thus, the complete syntax for an argument list is as follows:
341
342 @example
343 @group
344 (@var{required-vars}@dots{}
345 @r{[}&optional @var{optional-vars}@dots{}@r{]}
346 @r{[}&rest @var{rest-var}@r{]})
347 @end group
348 @end example
349
350 @noindent
351 The square brackets indicate that the @code{&optional} and @code{&rest}
352 clauses, and the variables that follow them, are optional.
353
354 A call to the function requires one actual argument for each of the
355 @var{required-vars}. There may be actual arguments for zero or more of
356 the @var{optional-vars}, and there cannot be any actual arguments beyond
357 that unless the lambda list uses @code{&rest}. In that case, there may
358 be any number of extra actual arguments.
359
360 If actual arguments for the optional and rest variables are omitted,
361 then they always default to @code{nil}. There is no way for the
362 function to distinguish between an explicit argument of @code{nil} and
363 an omitted argument. However, the body of the function is free to
364 consider @code{nil} an abbreviation for some other meaningful value.
365 This is what @code{substring} does; @code{nil} as the third argument to
366 @code{substring} means to use the length of the string supplied.
367
368 @cindex CL note---default optional arg
369 @quotation
370 @b{Common Lisp note:} Common Lisp allows the function to specify what
371 default value to use when an optional argument is omitted; Emacs Lisp
372 always uses @code{nil}. Emacs Lisp does not support @code{supplied-p}
373 variables that tell you whether an argument was explicitly passed.
374 @end quotation
375
376 For example, an argument list that looks like this:
377
378 @example
379 (a b &optional c d &rest e)
380 @end example
381
382 @noindent
383 binds @code{a} and @code{b} to the first two actual arguments, which are
384 required. If one or two more arguments are provided, @code{c} and
385 @code{d} are bound to them respectively; any arguments after the first
386 four are collected into a list and @code{e} is bound to that list. If
387 there are only two arguments, @code{c} is @code{nil}; if two or three
388 arguments, @code{d} is @code{nil}; if four arguments or fewer, @code{e}
389 is @code{nil}.
390
391 There is no way to have required arguments following optional
392 ones---it would not make sense. To see why this must be so, suppose
393 that @code{c} in the example were optional and @code{d} were required.
394 Suppose three actual arguments are given; which variable would the
395 third argument be for? Would it be used for the @var{c}, or for
396 @var{d}? One can argue for both possibilities. Similarly, it makes
397 no sense to have any more arguments (either required or optional)
398 after a @code{&rest} argument.
399
400 Here are some examples of argument lists and proper calls:
401
402 @example
403 (funcall (lambda (n) (1+ n)) ; @r{One required:}
404 1) ; @r{requires exactly one argument.}
405 @result{} 2
406 (funcall (lambda (n &optional n1) ; @r{One required and one optional:}
407 (if n1 (+ n n1) (1+ n))) ; @r{1 or 2 arguments.}
408 1 2)
409 @result{} 3
410 (funcall (lambda (n &rest ns) ; @r{One required and one rest:}
411 (+ n (apply '+ ns))) ; @r{1 or more arguments.}
412 1 2 3 4 5)
413 @result{} 15
414 @end example
415
416 @node Function Documentation
417 @subsection Documentation Strings of Functions
418 @cindex documentation of function
419
420 A lambda expression may optionally have a @dfn{documentation string}
421 just after the lambda list. This string does not affect execution of
422 the function; it is a kind of comment, but a systematized comment
423 which actually appears inside the Lisp world and can be used by the
424 Emacs help facilities. @xref{Documentation}, for how the
425 documentation string is accessed.
426
427 It is a good idea to provide documentation strings for all the
428 functions in your program, even those that are called only from within
429 your program. Documentation strings are like comments, except that they
430 are easier to access.
431
432 The first line of the documentation string should stand on its own,
433 because @code{apropos} displays just this first line. It should consist
434 of one or two complete sentences that summarize the function's purpose.
435
436 The start of the documentation string is usually indented in the
437 source file, but since these spaces come before the starting
438 double-quote, they are not part of the string. Some people make a
439 practice of indenting any additional lines of the string so that the
440 text lines up in the program source. @emph{That is a mistake.} The
441 indentation of the following lines is inside the string; what looks
442 nice in the source code will look ugly when displayed by the help
443 commands.
444
445 You may wonder how the documentation string could be optional, since
446 there are required components of the function that follow it (the body).
447 Since evaluation of a string returns that string, without any side effects,
448 it has no effect if it is not the last form in the body. Thus, in
449 practice, there is no confusion between the first form of the body and the
450 documentation string; if the only body form is a string then it serves both
451 as the return value and as the documentation.
452
453 The last line of the documentation string can specify calling
454 conventions different from the actual function arguments. Write
455 text like this:
456
457 @example
458 \(fn @var{arglist})
459 @end example
460
461 @noindent
462 following a blank line, at the beginning of the line, with no newline
463 following it inside the documentation string. (The @samp{\} is used
464 to avoid confusing the Emacs motion commands.) The calling convention
465 specified in this way appears in help messages in place of the one
466 derived from the actual arguments of the function.
467
468 This feature is particularly useful for macro definitions, since the
469 arguments written in a macro definition often do not correspond to the
470 way users think of the parts of the macro call.
471
472 @node Function Names
473 @section Naming a Function
474 @cindex function definition
475 @cindex named function
476 @cindex function name
477
478 A symbol can serve as the name of a function. This happens when the
479 symbol's @dfn{function cell} (@pxref{Symbol Components}) contains a
480 function object (e.g., a lambda expression). Then the symbol itself
481 becomes a valid, callable function, equivalent to the function object
482 in its function cell.
483
484 The contents of the function cell are also called the symbol's
485 @dfn{function definition}. The procedure of using a symbol's function
486 definition in place of the symbol is called @dfn{symbol function
487 indirection}; see @ref{Function Indirection}. If you have not given a
488 symbol a function definition, its function cell is said to be
489 @dfn{void}, and it cannot be used as a function.
490
491 In practice, nearly all functions have names, and are referred to by
492 their names. You can create a named Lisp function by defining a
493 lambda expression and putting it in a function cell (@pxref{Function
494 Cells}). However, it is more common to use the @code{defun} special
495 form, described in the next section.
496 @ifnottex
497 @xref{Defining Functions}.
498 @end ifnottex
499
500 We give functions names because it is convenient to refer to them by
501 their names in Lisp expressions. Also, a named Lisp function can
502 easily refer to itself---it can be recursive. Furthermore, primitives
503 can only be referred to textually by their names, since primitive
504 function objects (@pxref{Primitive Function Type}) have no read
505 syntax.
506
507 A function need not have a unique name. A given function object
508 @emph{usually} appears in the function cell of only one symbol, but
509 this is just a convention. It is easy to store it in several symbols
510 using @code{fset}; then each of the symbols is a valid name for the
511 same function.
512
513 Note that a symbol used as a function name may also be used as a
514 variable; these two uses of a symbol are independent and do not
515 conflict. (This is not the case in some dialects of Lisp, like
516 Scheme.)
517
518 @node Defining Functions
519 @section Defining Functions
520 @cindex defining a function
521
522 We usually give a name to a function when it is first created. This
523 is called @dfn{defining a function}, and it is done with the
524 @code{defun} macro.
525
526 @defmac defun name args [doc] [declare] [interactive] body@dots{}
527 @code{defun} is the usual way to define new Lisp functions. It
528 defines the symbol @var{name} as a function with argument list
529 @var{args} and body forms given by @var{body}. Neither @var{name} nor
530 @var{args} should be quoted.
531
532 @var{doc}, if present, should be a string specifying the function's
533 documentation string (@pxref{Function Documentation}). @var{declare},
534 if present, should be a @code{declare} form specifying function
535 metadata (@pxref{Declare Form}). @var{interactive}, if present,
536 should be an @code{interactive} form specifying how the function is to
537 be called interactively (@pxref{Interactive Call}).
538
539 The return value of @code{defun} is undefined.
540
541 Here are some examples:
542
543 @example
544 @group
545 (defun foo () 5)
546 (foo)
547 @result{} 5
548 @end group
549
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
564
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
575
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
583
584 @cindex function aliases
585 @cindex alias, for functions
586 @defun defalias name definition &optional doc
587 @anchor{Definition of defalias}
588 This function defines the symbol @var{name} as a function, with
589 definition @var{definition} (which can be any valid Lisp function).
590 Its return value is @emph{undefined}.
591
592 If @var{doc} is non-@code{nil}, it becomes the function documentation
593 of @var{name}. Otherwise, any documentation provided by
594 @var{definition} is used.
595
596 @cindex defalias-fset-function property
597 Internally, @code{defalias} normally uses @code{fset} to set the definition.
598 If @var{name} has a @code{defalias-fset-function} property, however,
599 the associated value is used as a function to call in place of @code{fset}.
600
601 The proper place to use @code{defalias} is where a specific function
602 name is being defined---especially where that name appears explicitly in
603 the source file being loaded. This is because @code{defalias} records
604 which file defined the function, just like @code{defun}
605 (@pxref{Unloading}).
606
607 By contrast, in programs that manipulate function definitions for other
608 purposes, it is better to use @code{fset}, which does not keep such
609 records. @xref{Function Cells}.
610 @end defun
611
612 You cannot create a new primitive function with @code{defun} or
613 @code{defalias}, but you can use them to change the function definition of
614 any symbol, even one such as @code{car} or @code{x-popup-menu} whose
615 normal definition is a primitive. However, this is risky: for
616 instance, it is next to impossible to redefine @code{car} without
617 breaking Lisp completely. Redefining an obscure function such as
618 @code{x-popup-menu} is less dangerous, but it still may not work as
619 you expect. If there are calls to the primitive from C code, they
620 call the primitive's C definition directly, so changing the symbol's
621 definition will have no effect on them.
622
623 See also @code{defsubst}, which defines a function like @code{defun}
624 and tells the Lisp compiler to perform inline expansion on it.
625 @xref{Inline Functions}.
626
627 Alternatively, you can define a function by providing the code which
628 will inline it as a compiler macro. The following macros make this
629 possible.
630
631 @c FIXME: Can define-inline use the interactive spec?
632 @defmac define-inline name args [doc] [declare] body@dots{}
633 Define a function @var{name} by providing code that does its inlining,
634 as a compiler macro. The function will accept the argument list
635 @var{args} and will have the specified @var{body}.
636
637 If present, @var{doc} should be the function's documentation string
638 (@pxref{Function Documentation}); @var{declare}, if present, should be
639 a @code{declare} form (@pxref{Declare Form}) specifying the function's
640 metadata.
641 @end defmac
642
643 Functions defined via @code{define-inline} have several advantages
644 with respect to macros defined by @code{defsubst} or @code{defmacro}:
645
646 @itemize @minus
647 @item
648 They can be passed to @code{mapcar} (@pxref{Mapping Functions}).
649
650 @item
651 They are more efficient.
652
653 @item
654 They can be used as @dfn{place forms} to store values
655 (@pxref{Generalized Variables}).
656
657 @item
658 They behave in a more predictable way than @code{cl-defsubst}
659 (@pxref{Argument Lists,,, cl, Common Lisp Extensions for GNU Emacs
660 Lisp}).
661 @end itemize
662
663 Like @code{defmacro}, a function inlined with @code{define-inline}
664 inherits the scoping rules, either dynamic or lexical, from the call
665 site. @xref{Variable Scoping}.
666
667 The following macros should be used in the body of a function defined
668 by @code{define-inline}.
669
670 @defmac inline-quote expression
671 Quote @var{expression} for @code{define-inline}. This is similar to
672 the backquote (@pxref{Backquote}), but quotes code and accepts only
673 @code{,}, not @code{,@@}.
674 @end defmac
675
676 @defmac inline-letevals (bindings@dots{}) body@dots{}
677 This is is similar to @code{let} (@pxref{Local Variables}): it sets up
678 local variables as specified by @var{bindings}, and then evaluates
679 @var{body} with those bindings in effect. Each element of
680 @var{bindings} should be either a symbol or a list of the form
681 @w{@code{(@var{var} @var{expr})}}; the result is to evaluate
682 @var{expr} and bind @var{var} to the result. The tail of
683 @var{bindings} can be either @code{nil} or a symbol which should hold
684 a list of arguments, in which case each argument is evaluated, and the
685 symbol is bound to the resulting list.
686 @end defmac
687
688 @defmac inline-const-p expression
689 Return non-@code{nil} if the value of @var{expression} is already
690 known.
691 @end defmac
692
693 @defmac inline-const-val expression
694 Return the value of @var{expression}.
695 @end defmac
696
697 @defmac inline-error format &rest args
698 Signal an error, formatting @var{args} according to @var{format}.
699 @end defmac
700
701 Here's an example of using @code{define-inline}:
702
703 @lisp
704 (define-inline myaccessor (obj)
705 (inline-letevals (obj)
706 (inline-quote (if (foo-p ,obj) (aref (cdr ,obj) 3) (aref ,obj 2)))))
707 @end lisp
708
709 @noindent
710 This is equivalent to
711
712 @lisp
713 (defsubst myaccessor (obj)
714 (if (foo-p obj) (aref (cdr obj) 3) (aref obj 2)))
715 @end lisp
716
717 @node Calling Functions
718 @section Calling Functions
719 @cindex function invocation
720 @cindex calling a function
721
722 Defining functions is only half the battle. Functions don't do
723 anything until you @dfn{call} them, i.e., tell them to run. Calling a
724 function is also known as @dfn{invocation}.
725
726 The most common way of invoking a function is by evaluating a list.
727 For example, evaluating the list @code{(concat "a" "b")} calls the
728 function @code{concat} with arguments @code{"a"} and @code{"b"}.
729 @xref{Evaluation}, for a description of evaluation.
730
731 When you write a list as an expression in your program, you specify
732 which function to call, and how many arguments to give it, in the text
733 of the program. Usually that's just what you want. Occasionally you
734 need to compute at run time which function to call. To do that, use
735 the function @code{funcall}. When you also need to determine at run
736 time how many arguments to pass, use @code{apply}.
737
738 @defun funcall function &rest arguments
739 @code{funcall} calls @var{function} with @var{arguments}, and returns
740 whatever @var{function} returns.
741
742 Since @code{funcall} is a function, all of its arguments, including
743 @var{function}, are evaluated before @code{funcall} is called. This
744 means that you can use any expression to obtain the function to be
745 called. It also means that @code{funcall} does not see the
746 expressions you write for the @var{arguments}, only their values.
747 These values are @emph{not} evaluated a second time in the act of
748 calling @var{function}; the operation of @code{funcall} is like the
749 normal procedure for calling a function, once its arguments have
750 already been evaluated.
751
752 The argument @var{function} must be either a Lisp function or a
753 primitive function. Special forms and macros are not allowed, because
754 they make sense only when given the unevaluated argument
755 expressions. @code{funcall} cannot provide these because, as we saw
756 above, it never knows them in the first place.
757
758 If you need to use @code{funcall} to call a command and make it behave
759 as if invoked interactively, use @code{funcall-interactively}
760 (@pxref{Interactive Call}).
761
762 @example
763 @group
764 (setq f 'list)
765 @result{} list
766 @end group
767 @group
768 (funcall f 'x 'y 'z)
769 @result{} (x y z)
770 @end group
771 @group
772 (funcall f 'x 'y '(z))
773 @result{} (x y (z))
774 @end group
775 @group
776 (funcall 'and t nil)
777 @error{} Invalid function: #<subr and>
778 @end group
779 @end example
780
781 Compare these examples with the examples of @code{apply}.
782 @end defun
783
784 @defun apply function &rest arguments
785 @code{apply} calls @var{function} with @var{arguments}, just like
786 @code{funcall} but with one difference: the last of @var{arguments} is a
787 list of objects, which are passed to @var{function} as separate
788 arguments, rather than a single list. We say that @code{apply}
789 @dfn{spreads} this list so that each individual element becomes an
790 argument.
791
792 @code{apply} returns the result of calling @var{function}. As with
793 @code{funcall}, @var{function} must either be a Lisp function or a
794 primitive function; special forms and macros do not make sense in
795 @code{apply}.
796
797 @example
798 @group
799 (setq f 'list)
800 @result{} list
801 @end group
802 @group
803 (apply f 'x 'y 'z)
804 @error{} Wrong type argument: listp, z
805 @end group
806 @group
807 (apply '+ 1 2 '(3 4))
808 @result{} 10
809 @end group
810 @group
811 (apply '+ '(1 2 3 4))
812 @result{} 10
813 @end group
814
815 @group
816 (apply 'append '((a b c) nil (x y z) nil))
817 @result{} (a b c x y z)
818 @end group
819 @end example
820
821 For an interesting example of using @code{apply}, see @ref{Definition
822 of mapcar}.
823 @end defun
824
825 @cindex partial application of functions
826 @cindex currying
827 Sometimes it is useful to fix some of the function's arguments at
828 certain values, and leave the rest of arguments for when the function
829 is actually called. The act of fixing some of the function's
830 arguments is called @dfn{partial application} of the function@footnote{
831 This is related to, but different from @dfn{currying}, which
832 transforms a function that takes multiple arguments in such a way that
833 it can be called as a chain of functions, each one with a single
834 argument.}.
835 The result is a new function that accepts the rest of
836 arguments and calls the original function with all the arguments
837 combined.
838
839 Here's how to do partial application in Emacs Lisp:
840
841 @defun apply-partially func &rest args
842 This function returns a new function which, when called, will call
843 @var{func} with the list of arguments composed from @var{args} and
844 additional arguments specified at the time of the call. If @var{func}
845 accepts @var{n} arguments, then a call to @code{apply-partially} with
846 @w{@code{@var{m} < @var{n}}} arguments will produce a new function of
847 @w{@code{@var{n} - @var{m}}} arguments.
848
849 Here's how we could define the built-in function @code{1+}, if it
850 didn't exist, using @code{apply-partially} and @code{+}, another
851 built-in function:
852
853 @example
854 @group
855 (defalias '1+ (apply-partially '+ 1)
856 "Increment argument by one.")
857 @end group
858 @group
859 (1+ 10)
860 @result{} 11
861 @end group
862 @end example
863 @end defun
864
865 @cindex functionals
866 It is common for Lisp functions to accept functions as arguments or
867 find them in data structures (especially in hook variables and property
868 lists) and call them using @code{funcall} or @code{apply}. Functions
869 that accept function arguments are often called @dfn{functionals}.
870
871 Sometimes, when you call a functional, it is useful to supply a no-op
872 function as the argument. Here are two different kinds of no-op
873 function:
874
875 @defun identity arg
876 This function returns @var{arg} and has no side effects.
877 @end defun
878
879 @defun ignore &rest args
880 This function ignores any arguments and returns @code{nil}.
881 @end defun
882
883 Some functions are user-visible @dfn{commands}, which can be called
884 interactively (usually by a key sequence). It is possible to invoke
885 such a command exactly as though it was called interactively, by using
886 the @code{call-interactively} function. @xref{Interactive Call}.
887
888 @node Mapping Functions
889 @section Mapping Functions
890 @cindex mapping functions
891
892 A @dfn{mapping function} applies a given function (@emph{not} a
893 special form or macro) to each element of a list or other collection.
894 Emacs Lisp has several such functions; this section describes
895 @code{mapcar}, @code{mapc}, and @code{mapconcat}, which map over a
896 list. @xref{Definition of mapatoms}, for the function @code{mapatoms}
897 which maps over the symbols in an obarray. @xref{Definition of
898 maphash}, for the function @code{maphash} which maps over key/value
899 associations in a hash table.
900
901 These mapping functions do not allow char-tables because a char-table
902 is a sparse array whose nominal range of indices is very large. To map
903 over a char-table in a way that deals properly with its sparse nature,
904 use the function @code{map-char-table} (@pxref{Char-Tables}).
905
906 @defun mapcar function sequence
907 @anchor{Definition of mapcar}
908 @code{mapcar} applies @var{function} to each element of @var{sequence}
909 in turn, and returns a list of the results.
910
911 The argument @var{sequence} can be any kind of sequence except a
912 char-table; that is, a list, a vector, a bool-vector, or a string. The
913 result is always a list. The length of the result is the same as the
914 length of @var{sequence}. For example:
915
916 @example
917 @group
918 (mapcar 'car '((a b) (c d) (e f)))
919 @result{} (a c e)
920 (mapcar '1+ [1 2 3])
921 @result{} (2 3 4)
922 (mapcar 'string "abc")
923 @result{} ("a" "b" "c")
924 @end group
925
926 @group
927 ;; @r{Call each function in @code{my-hooks}.}
928 (mapcar 'funcall my-hooks)
929 @end group
930
931 @group
932 (defun mapcar* (function &rest args)
933 "Apply FUNCTION to successive cars of all ARGS.
934 Return the list of results."
935 ;; @r{If no list is exhausted,}
936 (if (not (memq nil args))
937 ;; @r{apply function to @sc{car}s.}
938 (cons (apply function (mapcar 'car args))
939 (apply 'mapcar* function
940 ;; @r{Recurse for rest of elements.}
941 (mapcar 'cdr args)))))
942 @end group
943
944 @group
945 (mapcar* 'cons '(a b c) '(1 2 3 4))
946 @result{} ((a . 1) (b . 2) (c . 3))
947 @end group
948 @end example
949 @end defun
950
951 @defun mapc function sequence
952 @code{mapc} is like @code{mapcar} except that @var{function} is used for
953 side-effects only---the values it returns are ignored, not collected
954 into a list. @code{mapc} always returns @var{sequence}.
955 @end defun
956
957 @defun mapconcat function sequence separator
958 @code{mapconcat} applies @var{function} to each element of
959 @var{sequence}; the results, which must be sequences of characters
960 (strings, vectors, or lists), are concatenated into a single string
961 return value. Between each pair of result sequences, @code{mapconcat}
962 inserts the characters from @var{separator}, which also must be a
963 string, or a vector or list of characters. @xref{Sequences Arrays
964 Vectors}.
965
966 The argument @var{function} must be a function that can take one
967 argument and returns a sequence of characters: a string, a vector, or
968 a list. The argument @var{sequence} can be any kind of sequence
969 except a char-table; that is, a list, a vector, a bool-vector, or a
970 string.
971
972 @example
973 @group
974 (mapconcat 'symbol-name
975 '(The cat in the hat)
976 " ")
977 @result{} "The cat in the hat"
978 @end group
979
980 @group
981 (mapconcat (function (lambda (x) (format "%c" (1+ x))))
982 "HAL-8000"
983 "")
984 @result{} "IBM.9111"
985 @end group
986 @end example
987 @end defun
988
989 @node Anonymous Functions
990 @section Anonymous Functions
991 @cindex anonymous function
992
993 Although functions are usually defined with @code{defun} and given
994 names at the same time, it is sometimes convenient to use an explicit
995 lambda expression---an @dfn{anonymous function}. Anonymous functions
996 are valid wherever function names are. They are often assigned as
997 variable values, or as arguments to functions; for instance, you might
998 pass one as the @var{function} argument to @code{mapcar}, which
999 applies that function to each element of a list (@pxref{Mapping
1000 Functions}). @xref{describe-symbols example}, for a realistic example
1001 of this.
1002
1003 When defining a lambda expression that is to be used as an anonymous
1004 function, you can in principle use any method to construct the list.
1005 But typically you should use the @code{lambda} macro, or the
1006 @code{function} special form, or the @code{#'} read syntax:
1007
1008 @defmac lambda args [doc] [interactive] body@dots{}
1009 This macro returns an anonymous function with argument list
1010 @var{args}, documentation string @var{doc} (if any), interactive spec
1011 @var{interactive} (if any), and body forms given by @var{body}.
1012
1013 In effect, this macro makes @code{lambda} forms self-quoting:
1014 evaluating a form whose @sc{car} is @code{lambda} yields the form
1015 itself:
1016
1017 @example
1018 (lambda (x) (* x x))
1019 @result{} (lambda (x) (* x x))
1020 @end example
1021
1022 The @code{lambda} form has one other effect: it tells the Emacs
1023 evaluator and byte-compiler that its argument is a function, by using
1024 @code{function} as a subroutine (see below).
1025 @end defmac
1026
1027 @defspec function function-object
1028 @cindex function quoting
1029 This special form returns @var{function-object} without evaluating it.
1030 In this, it is similar to @code{quote} (@pxref{Quoting}). But unlike
1031 @code{quote}, it also serves as a note to the Emacs evaluator and
1032 byte-compiler that @var{function-object} is intended to be used as a
1033 function. Assuming @var{function-object} is a valid lambda
1034 expression, this has two effects:
1035
1036 @itemize
1037 @item
1038 When the code is byte-compiled, @var{function-object} is compiled into
1039 a byte-code function object (@pxref{Byte Compilation}).
1040
1041 @item
1042 When lexical binding is enabled, @var{function-object} is converted
1043 into a closure. @xref{Closures}.
1044 @end itemize
1045 @end defspec
1046
1047 @cindex @samp{#'} syntax
1048 The read syntax @code{#'} is a short-hand for using @code{function}.
1049 The following forms are all equivalent:
1050
1051 @example
1052 (lambda (x) (* x x))
1053 (function (lambda (x) (* x x)))
1054 #'(lambda (x) (* x x))
1055 @end example
1056
1057 In the following example, we define a @code{change-property}
1058 function that takes a function as its third argument, followed by a
1059 @code{double-property} function that makes use of
1060 @code{change-property} by passing it an anonymous function:
1061
1062 @example
1063 @group
1064 (defun change-property (symbol prop function)
1065 (let ((value (get symbol prop)))
1066 (put symbol prop (funcall function value))))
1067 @end group
1068
1069 @group
1070 (defun double-property (symbol prop)
1071 (change-property symbol prop (lambda (x) (* 2 x))))
1072 @end group
1073 @end example
1074
1075 @noindent
1076 Note that we do not quote the @code{lambda} form.
1077
1078 If you compile the above code, the anonymous function is also
1079 compiled. This would not happen if, say, you had constructed the
1080 anonymous function by quoting it as a list:
1081
1082 @c Do not unquote this lambda!
1083 @example
1084 @group
1085 (defun double-property (symbol prop)
1086 (change-property symbol prop '(lambda (x) (* 2 x))))
1087 @end group
1088 @end example
1089
1090 @noindent
1091 In that case, the anonymous function is kept as a lambda expression in
1092 the compiled code. The byte-compiler cannot assume this list is a
1093 function, even though it looks like one, since it does not know that
1094 @code{change-property} intends to use it as a function.
1095
1096 @node Generic Functions
1097 @section Generic Functions
1098 @cindex generic functions
1099 @cindex polymorphism
1100
1101 Functions defined using @code{defun} have a hard-coded set of
1102 assumptions about the types and expected values of their arguments.
1103 For example, a function that was designed to handle values of its
1104 argument that are either numbers or lists of numbers will fail or
1105 signal an error if called with a value of any other type, such as a
1106 vector or a string. This happens because the implementation of the
1107 function is not prepared to deal with types other than those assumed
1108 during the design.
1109
1110 By contrast, object-oriented programs use @dfn{polymorphic
1111 functions}: a set of specialized functions having the same name, each
1112 one of which was written for a certain specific set of argument types.
1113 Which of the functions is actually called is decided at run time based
1114 on the types of the actual arguments.
1115
1116 @cindex CLOS
1117 Emacs provides support for polymorphism. Like other Lisp
1118 environments, notably Common Lisp and its Common Lisp Object System
1119 (@acronym{CLOS}), this support is based on @dfn{generic functions}.
1120 The Emacs generic functions closely follow @acronym{CLOS}, including
1121 use of similar names, so if you have experience with @acronym{CLOS},
1122 the rest of this section will sound very familiar.
1123
1124 A generic function specifies an abstract operation, by defining its
1125 name and list of arguments, but (usually) no implementation. The
1126 actual implementation for several specific classes of arguments is
1127 provided by @dfn{methods}, which should be defined separately. Each
1128 method that implements a generic function has the same name as the
1129 generic function, but the method's definition indicates what kinds of
1130 arguments it can handle by @dfn{specializing} the arguments defined by
1131 the generic function. These @dfn{argument specializers} can be more
1132 or less specific; for example, a @code{string} type is more specific
1133 than a more general type, such as @code{sequence}.
1134
1135 Note that, unlike in message-based OO languages, such as C@t{++} and
1136 Simula, methods that implement generic functions don't belong to a
1137 class, they belong to the generic function they implement.
1138
1139 When a generic function is invoked, it selects the applicable
1140 methods by comparing the actual arguments passed by the caller with
1141 the argument specializers of each method. A method is applicable if
1142 the actual arguments of the call are compatible with the method's
1143 specializers. If more than one method is applicable, they are
1144 combined using certain rules, described below, and the combination
1145 then handles the call.
1146
1147 @defmac cl-defgeneric name arguments [documentation] [options-and-methods@dots{}] &rest body
1148 This macro defines a generic function with the specified @var{name}
1149 and @var{arguments}. If @var{body} is present, it provides the
1150 default implementation. If @var{documentation} is present (it should
1151 always be), it specifies the documentation string for the generic
1152 function, in the form @code{(:documentation @var{docstring})}. The
1153 optional @var{options-and-methods} can be one of the following forms:
1154
1155 @table @code
1156 @item (declare @var{declarations})
1157 A declare form, as described in @ref{Declare Form}.
1158 @item (:argument-precedence-order &rest @var{args})
1159 This form affects the sorting order for combining applicable methods.
1160 Normally, when two methods are compared during combination, method
1161 arguments are examined left to right, and the first method whose
1162 argument specializer is more specific will come before the other one.
1163 The order defined by this form overrides that, and the arguments are
1164 examined according to their order in this form, and not left to right.
1165 @item (:method [@var{qualifiers}@dots{}] args &rest body)
1166 This form defines a method like @code{cl-defmethod} does.
1167 @end table
1168 @end defmac
1169
1170 @defmac cl-defmethod name [qualifier] arguments &rest [docstring] body
1171 This macro defines a particular implementation for the generic
1172 function called @var{name}. The implementation code is given by
1173 @var{body}. If present, @var{docstring} is the documentation string
1174 for the method. The @var{arguments} list, which must be identical in
1175 all the methods that implement a generic function, and must match the
1176 argument list of that function, provides argument specializers of the
1177 form @code{(@var{arg} @var{spec})}, where @var{arg} is the argument
1178 name as specified in the @code{cl-defgeneric} call, and @var{spec} is
1179 one of the following specializer forms:
1180
1181 @table @code
1182 @item @var{type}
1183 This specializer requires the argument to be of the given @var{type},
1184 one of the types from the type hierarchy described below.
1185 @item (eql @var{object})
1186 This specializer requires the argument be @code{eql} to the given
1187 @var{object}.
1188 @item (head @var{object})
1189 The argument must be a cons cell whose @code{car} is @code{eql} to
1190 @var{object}.
1191 @item @var{struct-tag}
1192 The argument must be an instance of a class named @var{struct-tag}
1193 defined with @code{cl-defstruct} (@pxref{Structures,,, cl, Common Lisp
1194 Extensions for GNU Emacs Lisp}), or of one of its parent classes.
1195 @end table
1196
1197 Alternatively, the argument specializer can be of the form
1198 @code{&context (@var{expr} @var{spec})}, in which case the value of
1199 @var{expr} must be compatible with the specializer provided by
1200 @var{spec}; @var{spec} can be any of the forms described above. In
1201 other words, this form of specializer uses the value of @var{expr}
1202 instead of arguments for the decision whether the method is
1203 applicable. For example, @code{&context (overwrite-mode (eql t))}
1204 will make the method compatible only when @code{overwrite-mode} is
1205 turned on.
1206
1207 The type specializer, @code{(@var{arg} @var{type})}, can specify one
1208 of the @dfn{system types} in the following list. When a parent type
1209 is specified, an argument whose type is any of its more specific child
1210 types, as well as grand-children, grand-grand-children, etc. will also
1211 be compatible.
1212
1213 @table @code
1214 @item integer
1215 Parent type: @code{number}.
1216 @item number
1217 @item null
1218 Parent type: @code{symbol}
1219 @item symbol
1220 @item string
1221 Parent type: @code{array}.
1222 @item array
1223 Parent type: @code{sequence}.
1224 @item cons
1225 Parent type: @code{list}.
1226 @item list
1227 Parent type: @code{sequence}.
1228 @item marker
1229 @item overlay
1230 @item float
1231 Parent type: @code{number}.
1232 @item window-configuration
1233 @item process
1234 @item window
1235 @item subr
1236 @item compiled-function
1237 @item buffer
1238 @item char-table
1239 Parent type: @code{array}.
1240 @item bool-vector
1241 Parent type: @code{array}.
1242 @item vector
1243 Parent type: @code{array}.
1244 @item frame
1245 @item hash-table
1246 @item font-spec
1247 @item font-entity
1248 @item font-object
1249 @end table
1250
1251 The optional @var{qualifier} allows combining several applicable
1252 methods. If it is not present, the defined method is a @dfn{primary}
1253 method, responsible for providing the primary implementation of the
1254 generic function for the specialized arguments. You can also define
1255 @dfn{auxiliary methods}, by using one of the following values as
1256 @var{qualifier}:
1257
1258 @table @code
1259 @item :before
1260 This auxiliary method will run before the primary method. More
1261 accurately, all the @code{:before} methods will run before the
1262 primary, in the most-specific-first order.
1263 @item :after
1264 This auxiliary method will run after the primary method. More
1265 accurately, all such methods will run after the primary, in the
1266 most-specific-last order.
1267 @item :around
1268 This auxiliary method will run @emph{instead} of the primary method.
1269 The most specific of such methods will be run before any other method.
1270 Such methods normally use @code{cl-call-next-method}, described below,
1271 to invoke the other auxiliary or primary methods.
1272 @item :extra @var{string}
1273 This allows you to add more methods, distinguished by @var{string},
1274 for the same specializers and qualifiers.
1275 @end table
1276 @end defmac
1277
1278 @cindex dispatch of methods for generic function
1279 @cindex multiple-dispatch methods
1280 Each time a generic function is called, it builds the @dfn{effective
1281 method} which will handle this invocation by combining the applicable
1282 methods defined for the function. The process of finding the
1283 applicable methods and producing the effective method is called
1284 @dfn{dispatch}. The applicable methods are those all of whose
1285 specializers are compatible with the actual arguments of the call.
1286 Since all of the arguments must be compatible with the specializers,
1287 they all determine whether a method is applicable. Methods that
1288 explicitly specialize more than one argument are called
1289 @dfn{multiple-dispatch methods}.
1290
1291 The applicable methods are sorted into the order in which they will be
1292 combined. The method whose left-most argument specializer is the most
1293 specific one will come first in the order. (Specifying
1294 @code{:argument-precedence-order} as part of @code{cl-defmethod}
1295 overrides that, as described above.) If the method body calls
1296 @code{cl-call-next-method}, the next most-specific method will run.
1297 If there are applicable @code{:around} methods, the most-specific of
1298 them will run first; it should call @code{cl-call-next-method} to run
1299 any of the less specific @code{:around} methods. Next, the
1300 @code{:before} methods run in the order of their specificity, followed
1301 by the primary method, and lastly the @code{:after} methods in the
1302 reverse order of their specificity.
1303
1304 @defun cl-call-next-method &rest args
1305 When invoked from within the lexical body of a primary or an
1306 @code{:around} auxiliary method, call the next applicable method for
1307 the same generic function. Normally, it is called with no arguments,
1308 which means to call the next applicable method with the same arguments
1309 that the calling method was invoked. Otherwise, the specified
1310 arguments are used instead.
1311 @end defun
1312
1313 @defun cl-next-method-p
1314 This function, when called from within the lexical body of a primary
1315 or an @code{:around} auxiliary method, returns non-@code{nil} if there
1316 is a next method to call.
1317 @end defun
1318
1319
1320 @node Function Cells
1321 @section Accessing Function Cell Contents
1322
1323 The @dfn{function definition} of a symbol is the object stored in the
1324 function cell of the symbol. The functions described here access, test,
1325 and set the function cell of symbols.
1326
1327 See also the function @code{indirect-function}. @xref{Definition of
1328 indirect-function}.
1329
1330 @defun symbol-function symbol
1331 @kindex void-function
1332 This returns the object in the function cell of @var{symbol}. It does
1333 not check that the returned object is a legitimate function.
1334
1335 If the function cell is void, the return value is @code{nil}. To
1336 distinguish between a function cell that is void and one set to
1337 @code{nil}, use @code{fboundp} (see below).
1338
1339 @example
1340 @group
1341 (defun bar (n) (+ n 2))
1342 (symbol-function 'bar)
1343 @result{} (lambda (n) (+ n 2))
1344 @end group
1345 @group
1346 (fset 'baz 'bar)
1347 @result{} bar
1348 @end group
1349 @group
1350 (symbol-function 'baz)
1351 @result{} bar
1352 @end group
1353 @end example
1354 @end defun
1355
1356 @cindex void function cell
1357 If you have never given a symbol any function definition, we say
1358 that that symbol's function cell is @dfn{void}. In other words, the
1359 function cell does not have any Lisp object in it. If you try to call
1360 the symbol as a function, Emacs signals a @code{void-function} error.
1361
1362 Note that void is not the same as @code{nil} or the symbol
1363 @code{void}. The symbols @code{nil} and @code{void} are Lisp objects,
1364 and can be stored into a function cell just as any other object can be
1365 (and they can be valid functions if you define them in turn with
1366 @code{defun}). A void function cell contains no object whatsoever.
1367
1368 You can test the voidness of a symbol's function definition with
1369 @code{fboundp}. After you have given a symbol a function definition, you
1370 can make it void once more using @code{fmakunbound}.
1371
1372 @defun fboundp symbol
1373 This function returns @code{t} if the symbol has an object in its
1374 function cell, @code{nil} otherwise. It does not check that the object
1375 is a legitimate function.
1376 @end defun
1377
1378 @defun fmakunbound symbol
1379 This function makes @var{symbol}'s function cell void, so that a
1380 subsequent attempt to access this cell will cause a
1381 @code{void-function} error. It returns @var{symbol}. (See also
1382 @code{makunbound}, in @ref{Void Variables}.)
1383
1384 @example
1385 @group
1386 (defun foo (x) x)
1387 (foo 1)
1388 @result{}1
1389 @end group
1390 @group
1391 (fmakunbound 'foo)
1392 @result{} foo
1393 @end group
1394 @group
1395 (foo 1)
1396 @error{} Symbol's function definition is void: foo
1397 @end group
1398 @end example
1399 @end defun
1400
1401 @defun fset symbol definition
1402 This function stores @var{definition} in the function cell of
1403 @var{symbol}. The result is @var{definition}. Normally
1404 @var{definition} should be a function or the name of a function, but
1405 this is not checked. The argument @var{symbol} is an ordinary evaluated
1406 argument.
1407
1408 The primary use of this function is as a subroutine by constructs that define
1409 or alter functions, like @code{defun} or @code{advice-add} (@pxref{Advising
1410 Functions}). You can also use it to give a symbol a function definition that
1411 is not a function, e.g., a keyboard macro (@pxref{Keyboard Macros}):
1412
1413 @example
1414 ;; @r{Define a named keyboard macro.}
1415 (fset 'kill-two-lines "\^u2\^k")
1416 @result{} "\^u2\^k"
1417 @end example
1418
1419 It you wish to use @code{fset} to make an alternate name for a
1420 function, consider using @code{defalias} instead. @xref{Definition of
1421 defalias}.
1422 @end defun
1423
1424 @node Closures
1425 @section Closures
1426
1427 As explained in @ref{Variable Scoping}, Emacs can optionally enable
1428 lexical binding of variables. When lexical binding is enabled, any
1429 named function that you create (e.g., with @code{defun}), as well as
1430 any anonymous function that you create using the @code{lambda} macro
1431 or the @code{function} special form or the @code{#'} syntax
1432 (@pxref{Anonymous Functions}), is automatically converted into a
1433 @dfn{closure}.
1434
1435 @cindex closure
1436 A closure is a function that also carries a record of the lexical
1437 environment that existed when the function was defined. When it is
1438 invoked, any lexical variable references within its definition use the
1439 retained lexical environment. In all other respects, closures behave
1440 much like ordinary functions; in particular, they can be called in the
1441 same way as ordinary functions.
1442
1443 @xref{Lexical Binding}, for an example of using a closure.
1444
1445 Currently, an Emacs Lisp closure object is represented by a list
1446 with the symbol @code{closure} as the first element, a list
1447 representing the lexical environment as the second element, and the
1448 argument list and body forms as the remaining elements:
1449
1450 @example
1451 ;; @r{lexical binding is enabled.}
1452 (lambda (x) (* x x))
1453 @result{} (closure (t) (x) (* x x))
1454 @end example
1455
1456 @noindent
1457 However, the fact that the internal structure of a closure is
1458 exposed to the rest of the Lisp world is considered an internal
1459 implementation detail. For this reason, we recommend against directly
1460 examining or altering the structure of closure objects.
1461
1462 @node Advising Functions
1463 @section Advising Emacs Lisp Functions
1464 @cindex advising functions
1465 @cindex piece of advice
1466
1467 When you need to modify a function defined in another library, or when you need
1468 to modify a hook like @code{@var{foo}-function}, a process filter, or basically
1469 any variable or object field which holds a function value, you can use the
1470 appropriate setter function, such as @code{fset} or @code{defun} for named
1471 functions, @code{setq} for hook variables, or @code{set-process-filter} for
1472 process filters, but those are often too blunt, completely throwing away the
1473 previous value.
1474
1475 The @dfn{advice} feature lets you add to the existing definition of
1476 a function, by @dfn{advising the function}. This is a cleaner method
1477 than redefining the whole function.
1478
1479 Emacs's advice system provides two sets of primitives for that: the core set,
1480 for function values held in variables and object fields (with the corresponding
1481 primitives being @code{add-function} and @code{remove-function}) and another
1482 set layered on top of it for named functions (with the main primitives being
1483 @code{advice-add} and @code{advice-remove}).
1484
1485 For example, in order to trace the calls to the process filter of a process
1486 @var{proc}, you could use:
1487
1488 @example
1489 (defun my-tracing-function (proc string)
1490 (message "Proc %S received %S" proc string))
1491
1492 (add-function :before (process-filter @var{proc}) #'my-tracing-function)
1493 @end example
1494
1495 This will cause the process's output to be passed to @code{my-tracing-function}
1496 before being passed to the original process filter. @code{my-tracing-function}
1497 receives the same arguments as the original function. When you're done with
1498 it, you can revert to the untraced behavior with:
1499
1500 @example
1501 (remove-function (process-filter @var{proc}) #'my-tracing-function)
1502 @end example
1503
1504 Similarly, if you want to trace the execution of the function named
1505 @code{display-buffer}, you could use:
1506
1507 @example
1508 (defun his-tracing-function (orig-fun &rest args)
1509 (message "display-buffer called with args %S" args)
1510 (let ((res (apply orig-fun args)))
1511 (message "display-buffer returned %S" res)
1512 res))
1513
1514 (advice-add 'display-buffer :around #'his-tracing-function)
1515 @end example
1516
1517 Here, @code{his-tracing-function} is called instead of the original function
1518 and receives the original function (additionally to that function's arguments)
1519 as argument, so it can call it if and when it needs to.
1520 When you're tired of seeing this output, you can revert to the untraced
1521 behavior with:
1522
1523 @example
1524 (advice-remove 'display-buffer #'his-tracing-function)
1525 @end example
1526
1527 The arguments @code{:before} and @code{:around} used in the above examples
1528 specify how the two functions are composed, since there are many different
1529 ways to do it. The added function is also called a piece of @emph{advice}.
1530
1531 @menu
1532 * Core Advising Primitives:: Primitives to manipulate advice.
1533 * Advising Named Functions:: Advising named functions.
1534 * Advice combinators:: Ways to compose advice.
1535 * Porting old advice:: Adapting code using the old defadvice.
1536 @end menu
1537
1538 @node Core Advising Primitives
1539 @subsection Primitives to manipulate advices
1540 @cindex advice, add and remove
1541
1542 @defmac add-function where place function &optional props
1543 This macro is the handy way to add the advice @var{function} to the function
1544 stored in @var{place} (@pxref{Generalized Variables}).
1545
1546 @var{where} determines how @var{function} is composed with the
1547 existing function, e.g., whether @var{function} should be called before, or
1548 after the original function. @xref{Advice combinators}, for the list of
1549 available ways to compose the two functions.
1550
1551 When modifying a variable (whose name will usually end with @code{-function}),
1552 you can choose whether @var{function} is used globally or only in the current
1553 buffer: if @var{place} is just a symbol, then @var{function} is added to the
1554 global value of @var{place}. Whereas if @var{place} is of the form
1555 @code{(local @var{symbol})}, where @var{symbol} is an expression which returns
1556 the variable name, then @var{function} will only be added in the
1557 current buffer. Finally, if you want to modify a lexical variable, you will
1558 have to use @code{(var @var{variable})}.
1559
1560 Every function added with @code{add-function} can be accompanied by an
1561 association list of properties @var{props}. Currently only two of those
1562 properties have a special meaning:
1563
1564 @table @code
1565 @item name
1566 This gives a name to the advice, which @code{remove-function} can use to
1567 identify which function to remove. Typically used when @var{function} is an
1568 anonymous function.
1569
1570 @item depth
1571 This specifies how to order the advice, should several pieces of
1572 advice be present. By default, the depth is 0. A depth of 100
1573 indicates that this piece of advice should be kept as deep as
1574 possible, whereas a depth of -100 indicates that it should stay as the
1575 outermost piece. When two pieces of advice specify the same depth,
1576 the most recently added one will be outermost.
1577
1578 For @code{:before} advice, being outermost means that this advice will
1579 be run first, before any other advice, whereas being innermost means
1580 that it will run right before the original function, with no other
1581 advice run between itself and the original function. Similarly, for
1582 @code{:after} advice innermost means that it will run right after the
1583 original function, with no other advice run in between, whereas
1584 outermost means that it will be run right at the end after all other
1585 advice. An innermost @code{:override} piece of advice will only
1586 override the original function and other pieces of advice will apply
1587 to it, whereas an outermost @code{:override} piece of advice will
1588 override not only the original function but all other advice applied
1589 to it as well.
1590 @end table
1591
1592 If @var{function} is not interactive, then the combined function will inherit
1593 the interactive spec, if any, of the original function. Else, the combined
1594 function will be interactive and will use the interactive spec of
1595 @var{function}. One exception: if the interactive spec of @var{function}
1596 is a function (rather than an expression or a string), then the interactive
1597 spec of the combined function will be a call to that function with as sole
1598 argument the interactive spec of the original function. To interpret the spec
1599 received as argument, use @code{advice-eval-interactive-spec}.
1600
1601 Note: The interactive spec of @var{function} will apply to the combined
1602 function and should hence obey the calling convention of the combined function
1603 rather than that of @var{function}. In many cases, it makes no difference
1604 since they are identical, but it does matter for @code{:around},
1605 @code{:filter-args}, and @code{filter-return}, where @var{function}.
1606 @end defmac
1607
1608 @defmac remove-function place function
1609 This macro removes @var{function} from the function stored in
1610 @var{place}. This only works if @var{function} was added to @var{place}
1611 using @code{add-function}.
1612
1613 @var{function} is compared with functions added to @var{place} using
1614 @code{equal}, to try and make it work also with lambda expressions. It is
1615 additionally compared also with the @code{name} property of the functions added
1616 to @var{place}, which can be more reliable than comparing lambda expressions
1617 using @code{equal}.
1618 @end defmac
1619
1620 @defun advice-function-member-p advice function-def
1621 Return non-@code{nil} if @var{advice} is already in @var{function-def}.
1622 Like for @code{remove-function} above, instead of @var{advice} being the actual
1623 function, it can also be the @code{name} of the piece of advice.
1624 @end defun
1625
1626 @defun advice-function-mapc f function-def
1627 Call the function @var{f} for every piece of advice that was added to
1628 @var{function-def}. @var{f} is called with two arguments: the advice function
1629 and its properties.
1630 @end defun
1631
1632 @defun advice-eval-interactive-spec spec
1633 Evaluate the interactive @var{spec} just like an interactive call to a function
1634 with such a spec would, and then return the corresponding list of arguments
1635 that was built. E.g., @code{(advice-eval-interactive-spec "r\nP")} will
1636 return a list of three elements, containing the boundaries of the region and
1637 the current prefix argument.
1638 @end defun
1639
1640 @node Advising Named Functions
1641 @subsection Advising Named Functions
1642 @cindex advising named functions
1643
1644 A common use of advice is for named functions and macros.
1645 You could just use @code{add-function} as in:
1646
1647 @example
1648 (add-function :around (symbol-function '@var{fun}) #'his-tracing-function)
1649 @end example
1650
1651 But you should use @code{advice-add} and @code{advice-remove} for that
1652 instead. This separate set of functions to manipulate pieces of advice applied
1653 to named functions, offers the following extra features compared to
1654 @code{add-function}: they know how to deal with macros and autoloaded
1655 functions, they let @code{describe-function} preserve the original docstring as
1656 well as document the added advice, and they let you add and remove advice
1657 before a function is even defined.
1658
1659 @code{advice-add} can be useful for altering the behavior of existing calls
1660 to an existing function without having to redefine the whole function.
1661 However, it can be a source of bugs, since existing callers to the function may
1662 assume the old behavior, and work incorrectly when the behavior is changed by
1663 advice. Advice can also cause confusion in debugging, if the person doing the
1664 debugging does not notice or remember that the function has been modified
1665 by advice.
1666
1667 For these reasons, advice should be reserved for the cases where you
1668 cannot modify a function's behavior in any other way. If it is
1669 possible to do the same thing via a hook, that is preferable
1670 (@pxref{Hooks}). If you simply want to change what a particular key
1671 does, it may be better to write a new command, and remap the old
1672 command's key bindings to the new one (@pxref{Remapping Commands}).
1673 In particular, Emacs's own source files should not put advice on
1674 functions in Emacs. (There are currently a few exceptions to this
1675 convention, but we aim to correct them.)
1676
1677 Special forms (@pxref{Special Forms}) cannot be advised, however macros can
1678 be advised, in much the same way as functions. Of course, this will not affect
1679 code that has already been macro-expanded, so you need to make sure the advice
1680 is installed before the macro is expanded.
1681
1682 It is possible to advise a primitive (@pxref{What Is a Function}),
1683 but one should typically @emph{not} do so, for two reasons. Firstly,
1684 some primitives are used by the advice mechanism, and advising them
1685 could cause an infinite recursion. Secondly, many primitives are
1686 called directly from C, and such calls ignore advice; hence, one ends
1687 up in a confusing situation where some calls (occurring from Lisp
1688 code) obey the advice and other calls (from C code) do not.
1689
1690 @defmac define-advice symbol (where lambda-list &optional name depth) &rest body
1691 This macro defines a piece of advice and adds it to the function named
1692 @var{symbol}. The advice is an anonymous function if @var{name} is
1693 nil or a function named @code{symbol@@name}. See @code{advice-add}
1694 for explanation of other arguments.
1695 @end defmac
1696
1697 @defun advice-add symbol where function &optional props
1698 Add the advice @var{function} to the named function @var{symbol}.
1699 @var{where} and @var{props} have the same meaning as for @code{add-function}
1700 (@pxref{Core Advising Primitives}).
1701 @end defun
1702
1703 @defun advice-remove symbol function
1704 Remove the advice @var{function} from the named function @var{symbol}.
1705 @var{function} can also be the @code{name} of a piece of advice.
1706 @end defun
1707
1708 @defun advice-member-p function symbol
1709 Return non-@code{nil} if the advice @var{function} is already in the named
1710 function @var{symbol}. @var{function} can also be the @code{name} of
1711 a piece of advice.
1712 @end defun
1713
1714 @defun advice-mapc function symbol
1715 Call @var{function} for every piece of advice that was added to the
1716 named function @var{symbol}. @var{function} is called with two
1717 arguments: the advice function and its properties.
1718 @end defun
1719
1720 @node Advice combinators
1721 @subsection Ways to compose advice
1722
1723 Here are the different possible values for the @var{where} argument of
1724 @code{add-function} and @code{advice-add}, specifying how the advice
1725 @var{function} and the original function should be composed.
1726
1727 @table @code
1728 @item :before
1729 Call @var{function} before the old function. Both functions receive the
1730 same arguments, and the return value of the composition is the return value of
1731 the old function. More specifically, the composition of the two functions
1732 behaves like:
1733 @example
1734 (lambda (&rest r) (apply @var{function} r) (apply @var{oldfun} r))
1735 @end example
1736 @code{(add-function :before @var{funvar} @var{function})} is comparable for
1737 single-function hooks to @code{(add-hook '@var{hookvar} @var{function})} for
1738 normal hooks.
1739
1740 @item :after
1741 Call @var{function} after the old function. Both functions receive the
1742 same arguments, and the return value of the composition is the return value of
1743 the old function. More specifically, the composition of the two functions
1744 behaves like:
1745 @example
1746 (lambda (&rest r) (prog1 (apply @var{oldfun} r) (apply @var{function} r)))
1747 @end example
1748 @code{(add-function :after @var{funvar} @var{function})} is comparable for
1749 single-function hooks to @code{(add-hook '@var{hookvar} @var{function}
1750 'append)} for normal hooks.
1751
1752 @item :override
1753 This completely replaces the old function with the new one. The old function
1754 can of course be recovered if you later call @code{remove-function}.
1755
1756 @item :around
1757 Call @var{function} instead of the old function, but provide the old function
1758 as an extra argument to @var{function}. This is the most flexible composition.
1759 For example, it lets you call the old function with different arguments, or
1760 many times, or within a let-binding, or you can sometimes delegate the work to
1761 the old function and sometimes override it completely. More specifically, the
1762 composition of the two functions behaves like:
1763 @example
1764 (lambda (&rest r) (apply @var{function} @var{oldfun} r))
1765 @end example
1766
1767 @item :before-while
1768 Call @var{function} before the old function and don't call the old
1769 function if @var{function} returns @code{nil}. Both functions receive the
1770 same arguments, and the return value of the composition is the return value of
1771 the old function. More specifically, the composition of the two functions
1772 behaves like:
1773 @example
1774 (lambda (&rest r) (and (apply @var{function} r) (apply @var{oldfun} r)))
1775 @end example
1776 @code{(add-function :before-while @var{funvar} @var{function})} is comparable
1777 for single-function hooks to @code{(add-hook '@var{hookvar} @var{function})}
1778 when @var{hookvar} is run via @code{run-hook-with-args-until-failure}.
1779
1780 @item :before-until
1781 Call @var{function} before the old function and only call the old function if
1782 @var{function} returns @code{nil}. More specifically, the composition of the
1783 two functions behaves like:
1784 @example
1785 (lambda (&rest r) (or (apply @var{function} r) (apply @var{oldfun} r)))
1786 @end example
1787 @code{(add-function :before-until @var{funvar} @var{function})} is comparable
1788 for single-function hooks to @code{(add-hook '@var{hookvar} @var{function})}
1789 when @var{hookvar} is run via @code{run-hook-with-args-until-success}.
1790
1791 @item :after-while
1792 Call @var{function} after the old function and only if the old function
1793 returned non-@code{nil}. Both functions receive the same arguments, and the
1794 return value of the composition is the return value of @var{function}.
1795 More specifically, the composition of the two functions behaves like:
1796 @example
1797 (lambda (&rest r) (and (apply @var{oldfun} r) (apply @var{function} r)))
1798 @end example
1799 @code{(add-function :after-while @var{funvar} @var{function})} is comparable
1800 for single-function hooks to @code{(add-hook '@var{hookvar} @var{function}
1801 'append)} when @var{hookvar} is run via
1802 @code{run-hook-with-args-until-failure}.
1803
1804 @item :after-until
1805 Call @var{function} after the old function and only if the old function
1806 returned @code{nil}. More specifically, the composition of the two functions
1807 behaves like:
1808 @example
1809 (lambda (&rest r) (or (apply @var{oldfun} r) (apply @var{function} r)))
1810 @end example
1811 @code{(add-function :after-until @var{funvar} @var{function})} is comparable
1812 for single-function hooks to @code{(add-hook '@var{hookvar} @var{function}
1813 'append)} when @var{hookvar} is run via
1814 @code{run-hook-with-args-until-success}.
1815
1816 @item :filter-args
1817 Call @var{function} first and use the result (which should be a list) as the
1818 new arguments to pass to the old function. More specifically, the composition
1819 of the two functions behaves like:
1820 @example
1821 (lambda (&rest r) (apply @var{oldfun} (funcall @var{function} r)))
1822 @end example
1823
1824 @item :filter-return
1825 Call the old function first and pass the result to @var{function}.
1826 More specifically, the composition of the two functions behaves like:
1827 @example
1828 (lambda (&rest r) (funcall @var{function} (apply @var{oldfun} r)))
1829 @end example
1830 @end table
1831
1832
1833 @node Porting old advice
1834 @subsection Adapting code using the old defadvice
1835 @cindex old advices, porting
1836
1837 A lot of code uses the old @code{defadvice} mechanism, which is largely made
1838 obsolete by the new @code{advice-add}, whose implementation and semantics is
1839 significantly simpler.
1840
1841 An old piece of advice such as:
1842
1843 @example
1844 (defadvice previous-line (before next-line-at-end
1845 (&optional arg try-vscroll))
1846 "Insert an empty line when moving up from the top line."
1847 (if (and next-line-add-newlines (= arg 1)
1848 (save-excursion (beginning-of-line) (bobp)))
1849 (progn
1850 (beginning-of-line)
1851 (newline))))
1852 @end example
1853
1854 could be translated in the new advice mechanism into a plain function:
1855
1856 @example
1857 (defun previous-line--next-line-at-end (&optional arg try-vscroll)
1858 "Insert an empty line when moving up from the top line."
1859 (if (and next-line-add-newlines (= arg 1)
1860 (save-excursion (beginning-of-line) (bobp)))
1861 (progn
1862 (beginning-of-line)
1863 (newline))))
1864 @end example
1865
1866 Obviously, this does not actually modify @code{previous-line}. For that the
1867 old advice needed:
1868 @example
1869 (ad-activate 'previous-line)
1870 @end example
1871 whereas the new advice mechanism needs:
1872 @example
1873 (advice-add 'previous-line :before #'previous-line--next-line-at-end)
1874 @end example
1875
1876 Note that @code{ad-activate} had a global effect: it activated all pieces of
1877 advice enabled for that specified function. If you wanted to only activate or
1878 deactivate a particular piece, you needed to @emph{enable} or @emph{disable}
1879 it with @code{ad-enable-advice} and @code{ad-disable-advice}.
1880 The new mechanism does away with this distinction.
1881
1882 Around advice such as:
1883
1884 @example
1885 (defadvice foo (around foo-around)
1886 "Ignore case in `foo'."
1887 (let ((case-fold-search t))
1888 ad-do-it))
1889 (ad-activate 'foo)
1890 @end example
1891
1892 could translate into:
1893
1894 @example
1895 (defun foo--foo-around (orig-fun &rest args)
1896 "Ignore case in `foo'."
1897 (let ((case-fold-search t))
1898 (apply orig-fun args)))
1899 (advice-add 'foo :around #'foo--foo-around)
1900 @end example
1901
1902 Regarding the advice's @emph{class}, note that the new @code{:before} is not
1903 quite equivalent to the old @code{before}, because in the old advice you could
1904 modify the function's arguments (e.g., with @code{ad-set-arg}), and that would
1905 affect the argument values seen by the original function, whereas in the new
1906 @code{:before}, modifying an argument via @code{setq} in the advice has no
1907 effect on the arguments seen by the original function.
1908 When porting @code{before} advice which relied on this behavior, you'll need
1909 to turn it into new @code{:around} or @code{:filter-args} advice instead.
1910
1911 Similarly old @code{after} advice could modify the returned value by
1912 changing @code{ad-return-value}, whereas new @code{:after} advice cannot, so
1913 when porting such old @code{after} advice, you'll need to turn it into new
1914 @code{:around} or @code{:filter-return} advice instead.
1915
1916 @node Obsolete Functions
1917 @section Declaring Functions Obsolete
1918 @cindex obsolete functions
1919
1920 You can mark a named function as @dfn{obsolete}, meaning that it may
1921 be removed at some point in the future. This causes Emacs to warn
1922 that the function is obsolete whenever it byte-compiles code
1923 containing that function, and whenever it displays the documentation
1924 for that function. In all other respects, an obsolete function
1925 behaves like any other function.
1926
1927 The easiest way to mark a function as obsolete is to put a
1928 @code{(declare (obsolete @dots{}))} form in the function's
1929 @code{defun} definition. @xref{Declare Form}. Alternatively, you can
1930 use the @code{make-obsolete} function, described below.
1931
1932 A macro (@pxref{Macros}) can also be marked obsolete with
1933 @code{make-obsolete}; this has the same effects as for a function. An
1934 alias for a function or macro can also be marked as obsolete; this
1935 makes the alias itself obsolete, not the function or macro which it
1936 resolves to.
1937
1938 @defun make-obsolete obsolete-name current-name &optional when
1939 This function marks @var{obsolete-name} as obsolete.
1940 @var{obsolete-name} should be a symbol naming a function or macro, or
1941 an alias for a function or macro.
1942
1943 If @var{current-name} is a symbol, the warning message says to use
1944 @var{current-name} instead of @var{obsolete-name}. @var{current-name}
1945 does not need to be an alias for @var{obsolete-name}; it can be a
1946 different function with similar functionality. @var{current-name} can
1947 also be a string, which serves as the warning message. The message
1948 should begin in lower case, and end with a period. It can also be
1949 @code{nil}, in which case the warning message provides no additional
1950 details.
1951
1952 If provided, @var{when} should be a string indicating when the function
1953 was first made obsolete---for example, a date or a release number.
1954 @end defun
1955
1956 @defmac define-obsolete-function-alias obsolete-name current-name &optional when doc
1957 This convenience macro marks the function @var{obsolete-name} obsolete
1958 and also defines it as an alias for the function @var{current-name}.
1959 It is equivalent to the following:
1960
1961 @example
1962 (defalias @var{obsolete-name} @var{current-name} @var{doc})
1963 (make-obsolete @var{obsolete-name} @var{current-name} @var{when})
1964 @end example
1965 @end defmac
1966
1967 In addition, you can mark a certain a particular calling convention
1968 for a function as obsolete:
1969
1970 @defun set-advertised-calling-convention function signature when
1971 This function specifies the argument list @var{signature} as the
1972 correct way to call @var{function}. This causes the Emacs byte
1973 compiler to issue a warning whenever it comes across an Emacs Lisp
1974 program that calls @var{function} any other way (however, it will
1975 still allow the code to be byte compiled). @var{when} should be a
1976 string indicating when the variable was first made obsolete (usually a
1977 version number string).
1978
1979 For instance, in old versions of Emacs the @code{sit-for} function
1980 accepted three arguments, like this
1981
1982 @example
1983 (sit-for seconds milliseconds nodisp)
1984 @end example
1985
1986 However, calling @code{sit-for} this way is considered obsolete
1987 (@pxref{Waiting}). The old calling convention is deprecated like
1988 this:
1989
1990 @example
1991 (set-advertised-calling-convention
1992 'sit-for '(seconds &optional nodisp) "22.1")
1993 @end example
1994 @end defun
1995
1996 @node Inline Functions
1997 @section Inline Functions
1998 @cindex inline functions
1999
2000 An @dfn{inline function} is a function that works just like an
2001 ordinary function, except for one thing: when you byte-compile a call
2002 to the function (@pxref{Byte Compilation}), the function's definition
2003 is expanded into the caller. To define an inline function, use
2004 @code{defsubst} instead of @code{defun}.
2005
2006 @defmac defsubst name args [doc] [declare] [interactive] body@dots{}
2007 This macro defines an inline function. Its syntax is exactly the same
2008 as @code{defun} (@pxref{Defining Functions}).
2009 @end defmac
2010
2011 Making a function inline often makes its function calls run faster.
2012 But it also has disadvantages. For one thing, it reduces flexibility;
2013 if you change the definition of the function, calls already inlined
2014 still use the old definition until you recompile them.
2015
2016 Another disadvantage is that making a large function inline can
2017 increase the size of compiled code both in files and in memory. Since
2018 the speed advantage of inline functions is greatest for small
2019 functions, you generally should not make large functions inline.
2020
2021 Also, inline functions do not behave well with respect to debugging,
2022 tracing, and advising (@pxref{Advising Functions}). Since ease of
2023 debugging and the flexibility of redefining functions are important
2024 features of Emacs, you should not make a function inline, even if it's
2025 small, unless its speed is really crucial, and you've timed the code
2026 to verify that using @code{defun} actually has performance problems.
2027
2028 After an inline function is defined, its inline expansion can be
2029 performed later on in the same file, just like macros.
2030
2031 It's possible to use @code{defsubst} to define a macro to expand
2032 into the same code that an inline function would execute
2033 (@pxref{Macros}). But the macro would be limited to direct use in
2034 expressions---a macro cannot be called with @code{apply},
2035 @code{mapcar} and so on. Also, it takes some work to convert an
2036 ordinary function into a macro. To convert it into an inline function
2037 is easy; just replace @code{defun} with @code{defsubst}. Since each
2038 argument of an inline function is evaluated exactly once, you needn't
2039 worry about how many times the body uses the arguments, as you do for
2040 macros.
2041
2042 As an alternative to @code{defsubst}, you can use
2043 @code{define-inline} to define functions via their exhaustive compiler
2044 macro. @xref{Defining Functions, define-inline}.
2045
2046 @node Declare Form
2047 @section The @code{declare} Form
2048 @findex declare
2049
2050 @code{declare} is a special macro which can be used to add meta
2051 properties to a function or macro: for example, marking it as
2052 obsolete, or giving its forms a special @key{TAB} indentation
2053 convention in Emacs Lisp mode.
2054
2055 @anchor{Definition of declare}
2056 @defmac declare specs@dots{}
2057 This macro ignores its arguments and evaluates to @code{nil}; it has
2058 no run-time effect. However, when a @code{declare} form occurs in the
2059 @var{declare} argument of a @code{defun} or @code{defsubst} function
2060 definition (@pxref{Defining Functions}) or a @code{defmacro} macro
2061 definition (@pxref{Defining Macros}), it appends the properties
2062 specified by @var{specs} to the function or macro. This work is
2063 specially performed by @code{defun}, @code{defsubst}, and
2064 @code{defmacro}.
2065
2066 Each element in @var{specs} should have the form @code{(@var{property}
2067 @var{args}@dots{})}, which should not be quoted. These have the
2068 following effects:
2069
2070 @table @code
2071 @item (advertised-calling-convention @var{signature} @var{when})
2072 This acts like a call to @code{set-advertised-calling-convention}
2073 (@pxref{Obsolete Functions}); @var{signature} specifies the correct
2074 argument list for calling the function or macro, and @var{when} should
2075 be a string indicating when the old argument list was first made obsolete.
2076
2077 @item (debug @var{edebug-form-spec})
2078 This is valid for macros only. When stepping through the macro with
2079 Edebug, use @var{edebug-form-spec}. @xref{Instrumenting Macro Calls}.
2080
2081 @item (doc-string @var{n})
2082 This is used when defining a function or macro which itself will be used to
2083 define entities like functions, macros, or variables. It indicates that
2084 the @var{n}th argument, if any, should be considered
2085 as a documentation string.
2086
2087 @item (indent @var{indent-spec})
2088 Indent calls to this function or macro according to @var{indent-spec}.
2089 This is typically used for macros, though it works for functions too.
2090 @xref{Indenting Macros}.
2091
2092 @item (interactive-only @var{value})
2093 Set the function's @code{interactive-only} property to @var{value}.
2094 @xref{The interactive-only property}.
2095
2096 @item (obsolete @var{current-name} @var{when})
2097 Mark the function or macro as obsolete, similar to a call to
2098 @code{make-obsolete} (@pxref{Obsolete Functions}). @var{current-name}
2099 should be a symbol (in which case the warning message says to use that
2100 instead), a string (specifying the warning message), or @code{nil} (in
2101 which case the warning message gives no extra details). @var{when}
2102 should be a string indicating when the function or macro was first
2103 made obsolete.
2104
2105 @item (compiler-macro @var{expander})
2106 This can only be used for functions, and tells the compiler to use
2107 @var{expander} as an optimization function. When encountering a call to the
2108 function, of the form @code{(@var{function} @var{args}@dots{})}, the macro
2109 expander will call @var{expander} with that form as well as with
2110 @var{args}@dots{}, and @var{expander} can either return a new expression to use
2111 instead of the function call, or it can return just the form unchanged,
2112 to indicate that the function call should be left alone. @var{expander} can
2113 be a symbol, or it can be a form @code{(lambda (@var{arg}) @var{body})} in
2114 which case @var{arg} will hold the original function call expression, and the
2115 (unevaluated) arguments to the function can be accessed using the function's
2116 formal arguments.
2117
2118 @item (gv-expander @var{expander})
2119 Declare @var{expander} to be the function to handle calls to the macro (or
2120 function) as a generalized variable, similarly to @code{gv-define-expander}.
2121 @var{expander} can be a symbol or it can be of the form @code{(lambda
2122 (@var{arg}) @var{body})} in which case that function will additionally have
2123 access to the macro (or function)'s arguments.
2124
2125 @item (gv-setter @var{setter})
2126 Declare @var{setter} to be the function to handle calls to the macro (or
2127 function) as a generalized variable. @var{setter} can be a symbol in which
2128 case it will be passed to @code{gv-define-simple-setter}, or it can be of the
2129 form @code{(lambda (@var{arg}) @var{body})} in which case that function will
2130 additionally have access to the macro (or function)'s arguments and it will
2131 passed to @code{gv-define-setter}.
2132
2133 @end table
2134
2135 @end defmac
2136
2137 @node Declaring Functions
2138 @section Telling the Compiler that a Function is Defined
2139 @cindex function declaration
2140 @cindex declaring functions
2141 @findex declare-function
2142
2143 Byte-compiling a file often produces warnings about functions that the
2144 compiler doesn't know about (@pxref{Compiler Errors}). Sometimes this
2145 indicates a real problem, but usually the functions in question are
2146 defined in other files which would be loaded if that code is run. For
2147 example, byte-compiling @file{fortran.el} used to warn:
2148
2149 @example
2150 In end of data:
2151 fortran.el:2152:1:Warning: the function ‘gud-find-c-expr’ is not
2152 known to be defined.
2153 @end example
2154
2155 In fact, @code{gud-find-c-expr} is only used in the function that
2156 Fortran mode uses for the local value of
2157 @code{gud-find-expr-function}, which is a callback from GUD; if it is
2158 called, the GUD functions will be loaded. When you know that such a
2159 warning does not indicate a real problem, it is good to suppress the
2160 warning. That makes new warnings which might mean real problems more
2161 visible. You do that with @code{declare-function}.
2162
2163 All you need to do is add a @code{declare-function} statement before the
2164 first use of the function in question:
2165
2166 @example
2167 (declare-function gud-find-c-expr "gud.el" nil)
2168 @end example
2169
2170 This says that @code{gud-find-c-expr} is defined in @file{gud.el} (the
2171 @samp{.el} can be omitted). The compiler takes for granted that that file
2172 really defines the function, and does not check.
2173
2174 The optional third argument specifies the argument list of
2175 @code{gud-find-c-expr}. In this case, it takes no arguments
2176 (@code{nil} is different from not specifying a value). In other
2177 cases, this might be something like @code{(file &optional overwrite)}.
2178 You don't have to specify the argument list, but if you do the
2179 byte compiler can check that the calls match the declaration.
2180
2181 @defmac declare-function function file &optional arglist fileonly
2182 Tell the byte compiler to assume that @var{function} is defined, with
2183 arguments @var{arglist}, and that the definition should come from the
2184 file @var{file}. @var{fileonly} non-@code{nil} means only check that
2185 @var{file} exists, not that it actually defines @var{function}.
2186 @end defmac
2187
2188 To verify that these functions really are declared where
2189 @code{declare-function} says they are, use @code{check-declare-file}
2190 to check all @code{declare-function} calls in one source file, or use
2191 @code{check-declare-directory} check all the files in and under a
2192 certain directory.
2193
2194 These commands find the file that ought to contain a function's
2195 definition using @code{locate-library}; if that finds no file, they
2196 expand the definition file name relative to the directory of the file
2197 that contains the @code{declare-function} call.
2198
2199 You can also say that a function is a primitive by specifying a file
2200 name ending in @samp{.c} or @samp{.m}. This is useful only when you
2201 call a primitive that is defined only on certain systems. Most
2202 primitives are always defined, so they will never give you a warning.
2203
2204 Sometimes a file will optionally use functions from an external package.
2205 If you prefix the filename in the @code{declare-function} statement with
2206 @samp{ext:}, then it will be checked if it is found, otherwise skipped
2207 without error.
2208
2209 There are some function definitions that @samp{check-declare} does not
2210 understand (e.g., @code{defstruct} and some other macros). In such cases,
2211 you can pass a non-@code{nil} @var{fileonly} argument to
2212 @code{declare-function}, meaning to only check that the file exists, not
2213 that it actually defines the function. Note that to do this without
2214 having to specify an argument list, you should set the @var{arglist}
2215 argument to @code{t} (because @code{nil} means an empty argument list, as
2216 opposed to an unspecified one).
2217
2218 @node Function Safety
2219 @section Determining whether a Function is Safe to Call
2220 @cindex function safety
2221 @cindex safety of functions
2222
2223 Some major modes, such as SES, call functions that are stored in user
2224 files. (@inforef{Top, ,ses}, for more information on SES@.) User
2225 files sometimes have poor pedigrees---you can get a spreadsheet from
2226 someone you've just met, or you can get one through email from someone
2227 you've never met. So it is risky to call a function whose source code
2228 is stored in a user file until you have determined that it is safe.
2229
2230 @defun unsafep form &optional unsafep-vars
2231 Returns @code{nil} if @var{form} is a @dfn{safe} Lisp expression, or
2232 returns a list that describes why it might be unsafe. The argument
2233 @var{unsafep-vars} is a list of symbols known to have temporary
2234 bindings at this point; it is mainly used for internal recursive
2235 calls. The current buffer is an implicit argument, which provides a
2236 list of buffer-local bindings.
2237 @end defun
2238
2239 Being quick and simple, @code{unsafep} does a very light analysis and
2240 rejects many Lisp expressions that are actually safe. There are no
2241 known cases where @code{unsafep} returns @code{nil} for an unsafe
2242 expression. However, a safe Lisp expression can return a string
2243 with a @code{display} property, containing an associated Lisp
2244 expression to be executed after the string is inserted into a buffer.
2245 This associated expression can be a virus. In order to be safe, you
2246 must delete properties from all strings calculated by user code before
2247 inserting them into buffers.
2248
2249 @ignore
2250 What is a safe Lisp expression? Basically, it's an expression that
2251 calls only built-in functions with no side effects (or only innocuous
2252 ones). Innocuous side effects include displaying messages and
2253 altering non-risky buffer-local variables (but not global variables).
2254
2255 @table @dfn
2256 @item Safe expression
2257 @itemize
2258 @item
2259 An atom or quoted thing.
2260 @item
2261 A call to a safe function (see below), if all its arguments are
2262 safe expressions.
2263 @item
2264 One of the special forms @code{and}, @code{catch}, @code{cond},
2265 @code{if}, @code{or}, @code{prog1}, @code{prog2}, @code{progn},
2266 @code{while}, and @code{unwind-protect}], if all its arguments are
2267 safe.
2268 @item
2269 A form that creates temporary bindings (@code{condition-case},
2270 @code{dolist}, @code{dotimes}, @code{lambda}, @code{let}, or
2271 @code{let*}), if all args are safe and the symbols to be bound are not
2272 explicitly risky (see @pxref{File Local Variables}).
2273 @item
2274 An assignment using @code{add-to-list}, @code{setq}, @code{push}, or
2275 @code{pop}, if all args are safe and the symbols to be assigned are
2276 not explicitly risky and they already have temporary or buffer-local
2277 bindings.
2278 @item
2279 One of [apply, mapc, mapcar, mapconcat] if the first argument is a
2280 safe explicit lambda and the other args are safe expressions.
2281 @end itemize
2282
2283 @item Safe function
2284 @itemize
2285 @item
2286 A lambda containing safe expressions.
2287 @item
2288 A symbol on the list @code{safe-functions}, so the user says it's safe.
2289 @item
2290 A symbol with a non-@code{nil} @code{side-effect-free} property.
2291 @item
2292 A symbol with a non-@code{nil} @code{safe-function} property. The
2293 value @code{t} indicates a function that is safe but has innocuous
2294 side effects. Other values will someday indicate functions with
2295 classes of side effects that are not always safe.
2296 @end itemize
2297
2298 The @code{side-effect-free} and @code{safe-function} properties are
2299 provided for built-in functions and for low-level functions and macros
2300 defined in @file{subr.el}. You can assign these properties for the
2301 functions you write.
2302 @end table
2303 @end ignore
2304
2305 @node Related Topics
2306 @section Other Topics Related to Functions
2307
2308 Here is a table of several functions that do things related to
2309 function calling and function definitions. They are documented
2310 elsewhere, but we provide cross references here.
2311
2312 @table @code
2313 @item apply
2314 See @ref{Calling Functions}.
2315
2316 @item autoload
2317 See @ref{Autoload}.
2318
2319 @item call-interactively
2320 See @ref{Interactive Call}.
2321
2322 @item called-interactively-p
2323 See @ref{Distinguish Interactive}.
2324
2325 @item commandp
2326 See @ref{Interactive Call}.
2327
2328 @item documentation
2329 See @ref{Accessing Documentation}.
2330
2331 @item eval
2332 See @ref{Eval}.
2333
2334 @item funcall
2335 See @ref{Calling Functions}.
2336
2337 @item function
2338 See @ref{Anonymous Functions}.
2339
2340 @item ignore
2341 See @ref{Calling Functions}.
2342
2343 @item indirect-function
2344 See @ref{Function Indirection}.
2345
2346 @item interactive
2347 See @ref{Using Interactive}.
2348
2349 @item interactive-p
2350 See @ref{Distinguish Interactive}.
2351
2352 @item mapatoms
2353 See @ref{Creating Symbols}.
2354
2355 @item mapcar
2356 See @ref{Mapping Functions}.
2357
2358 @item map-char-table
2359 See @ref{Char-Tables}.
2360
2361 @item mapconcat
2362 See @ref{Mapping Functions}.
2363
2364 @item undefined
2365 See @ref{Functions for Key Lookup}.
2366 @end table