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