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