A function is a value that can be called. A named function is a symbol whose function cell holds such a value. Most Emacs Lisp code is made of defun forms, so this page begins with their shape: the argument list, the docstring, the declarations and the body. It then covers closures, the function cell, mapping, advice, the more capable cl-lib definers, and the functions written in C.
defun and lambda
(defun NAME ARGLIST [DOCSTRING] [DECLARE] [INTERACTIVE] BODY…) stores a function in the function cell of NAME and returns NAME. (lambda ARGLIST [DOCSTRING] [INTERACTIVE] BODY…) makes an anonymous one. Both return the value of the last body form; a body with no forms returns nil. The order of the optional parts matters: the docstring comes first, the declare form next, then interactive.
(defun greet (name &optional greeting)
"Return a greeting for NAME.
GREETING defaults to \"Hello\".
(fn NAME &optional GREETING)"
(declare (pure t) (side-effect-free t))
(format "%s, %s!" (or greeting "Hello") name))
Argument lists
| Part | Meaning |
|---|---|
(a b) | required parameters, matched in order; too few or too many arguments signal wrong-number-of-arguments |
&optional c d | parameters that may be omitted; an omitted one is nil |
&rest more | binds the remaining arguments as a list; it must be last, with one name after it |
The parameters of a lambda are local variables. There are no keyword parameters in the language itself; cl-defun adds them (below). A parameter whose name begins with an underscore signals to the compiler that it is unused. A function’s arity is found with func-arity, which returns (MIN . MAX) with many as MAX when there is a &rest.
Docstrings
The documentation is a string in the first position of the body, provided another form follows it, or provided it is the only body form (in which case it is also the return value). Its first line should be a full sentence that stands alone, because apropos shows only that line. Parameter names are written in capitals. Help shows the call signature taken from the argument list; if a function is advised, a macro, or compiled with a different list, the docstring may end with a line (fn ARGS), preceded by a blank line, to give the signature that should be displayed. A \\[command] sequence inside a docstring prints the key bound to a command, \\{map} prints a keymap, \\<map> chooses the keymap, and `symbol' or ‘symbol’ makes a link.
Closures
With lexical-binding on, evaluating a lambda (or function of one) yields a closure: the code plus the lexical variables it refers to. The captured variables live on after the form that made them has returned, and the closure can change them.
;;; -*- lexical-binding: t -*-
(defun make-counter ()
(let ((n 0))
(lambda () (setq n (1+ n)))))
(let ((c (make-counter)))
(funcall c) (funcall c)) ; => 2
Before Emacs 30 the interpreter represented a closure as a list (closure ENV ARGS BODY…). From Emacs 30 the interpreter produces an interpreted-function object, and a byte-compiled function is a byte-code-function object; the two are laid out in the same slots (arguments, code, constants, depth, docstring, interactive form), and closurep is true for both. A list that starts with lambda is now only source code that is still callable. Under dynamic binding there are no closures: a lambda sees the variable values at the time of the call. See Data types and Variables and scope.
The function cell, aliases and indirection
| Function | Meaning |
|---|---|
(symbol-function SYM) | the contents of the function cell, without following aliases; nil if void |
(indirect-function OBJ) | follows a chain of symbols to the final definition |
(fboundp SYM), (fmakunbound SYM) | test and clear the cell |
(fset SYM DEF) | stores DEF in the cell; DEF may be another symbol, which makes an alias |
(defalias SYM DEF [DOC]) | like fset, and records the definition’s file and docstring; it is the right call for aliases and for generated definitions, and it honours the defalias-fset-function property |
(define-obsolete-function-alias OLD NEW WHEN [DOC]) | an alias that the compiler warns about |
(make-obsolete FUNC NEW WHEN) | marks an existing function obsolete; WHEN is a version string; make-obsolete-variable does the same for variables |
(declare (obsolete NEW WHEN)) | the same, written inside a defun |
(functionp OBJ), (func-arity F), (commandp F) | test callability, find the arity, test interactivity |
A loop of aliases signals cyclic-function-indirection. The function cell may hold a lambda, a closure object, a byte-code object, a subr, a macro (macro . F), an autoload object, or a symbol.
Calling and mapping
| Function | Meaning |
|---|---|
(funcall F ARGS…) | calls F with the arguments |
(apply F ARGS… LIST) | the last argument is a list of further arguments |
(mapcar F SEQ) | returns a list of the results of F on each element |
(mapc F SEQ) | the same for side effects; returns SEQ |
(mapcan F SEQ) | concatenates the lists F returns, with nconc, so the lists must be fresh |
(mapconcat F SEQ [SEPARATOR]) | joins the strings F returns; from Emacs 29 SEPARATOR is optional |
(mapatoms F [OBARRAY]), (maphash F TABLE) | over symbols, and over a hash table |
(apply-partially F ARGS…) | a function with leading arguments filled in |
(identity X), (ignore …), (always …) | return X; return nil; return t (always is new in Emacs 28) |
(funcall-interactively F …), (call-interactively F) | call a command as the user would; see Commands and modes |
(func-arity F), (subr-arity S) | number of parameters |
The declare form
A (declare SPEC…) form at the top of a defun, defmacro or cl-defmethod body records facts about the definition. The specs are expanded by the macro at load time, through the lists defun-declarations-alist and macro-declarations-alist.
| Spec | Effect |
|---|---|
(indent N) | how to indent calls: a number of special arguments, defun for body style, or a function name |
(doc-string N) | the argument at position N is a docstring (for the tools that read it) |
(obsolete NEW WHEN) | marks the function as obsolete, with the replacement and the version |
(interactive-only VALUE) | warns when the function is called from Lisp; VALUE is a replacement name or t |
(pure VAL) | the function has no side effects and the same arguments always give the same value, so the compiler may fold constant calls |
(side-effect-free VAL) | no side effects, but the result may depend on state; unused calls can be dropped |
(important-return-value VAL) | the compiler warns when the value is discarded (Emacs 30) |
(gv-setter SETTER), (gv-expander EXPANDER) | how setf treats a call as a place |
(compiler-macro EXPANDER) | a function that may rewrite a call at compile time (see Macros) |
(completion PREDICATE) | when the command appears in M-x completion (Emacs 28) |
(modes MODE…) | the modes in which a command is meaningful; used for completion and help (Emacs 28) |
(interactive-args ARG…) | the values that are given to parameters by call-interactively, so a command can be called without prompting (Emacs 29) |
(autoload-macro VALUE) | for macros: lets the autoload generator expand them |
(speed N), (safety N), (ftype TYPE) | hints to the native compiler |
(debug SPEC), (no-font-lock-keyword t), (indent …) | macro-only specs: Edebug specification and font-lock behaviour |
Advice
Advice wraps an existing function without editing it. nadvice.el provides advice-add for named functions and add-function for any place that holds a function (a variable, a hook slot, a process filter). The advice receives the original function as an argument when it is an :around.
| Combinator | Behaviour |
|---|---|
:around | (ADVICE OLDFUN ARGS…): the advice decides if and when to call OLDFUN |
:before | advice, then the original with the same arguments; the original’s value is returned |
:after | the original, then the advice; the original’s value is returned |
:override | the advice replaces the original |
:after-until | the original, then the advice if the original returned nil |
:after-while | the original, then the advice if the original returned non-nil |
:before-until | the advice, then the original if the advice returned nil |
:before-while | the advice, then the original if the advice returned non-nil |
:filter-args | the advice receives the argument list and returns a new one |
:filter-return | the advice receives the return value and returns a new one |
| Function | Meaning |
|---|---|
(advice-add SYMBOL HOW FUNCTION [PROPS]) | adds advice; PROPS may hold name and depth |
(advice-remove SYMBOL FUNCTION-OR-NAME) | removes it |
(advice-member-p ADVICE SYMBOL), (advice-mapc F SYMBOL) | test and walk the advice |
(add-function HOW PLACE FUNCTION), (remove-function PLACE FUNCTION) | advice on a place, such as (local 'var), (var VAR), (process-filter P) |
(define-advice SYMBOL (HOW LAMBDA-LIST [NAME [DEPTH]]) BODY…) | defines a named advice function SYMBOL@NAME and adds it |
(define-advice save-buffer (:before (&rest _) trim)
(delete-trailing-whitespace))
(advice-add 'forward-line :around
(lambda (orig n) (funcall orig (* 2 n)))) Common Lisp style definitions
| Form | Meaning |
|---|---|
(cl-defun NAME CL-ARGS…), (cl-defmacro …), (cl-function (lambda …)) | a lambda list with &key (:name value pairs), &aux, &body, default values (x 5), supplied-p variables (x 5 x-p), &allow-other-keys, and destructuring of list parameters; cl-defun wraps the body in cl-block NAME, so cl-return-from works |
(cl-defgeneric NAME ARGS [DOC] [OPTIONS] [BODY]) | declares a generic function; a body is the default method; options include (declare …) and (:method …) |
(cl-defmethod NAME [QUALIFIER] ARGS BODY…) | adds a method. A parameter may be specialised as (x integer), (x (head SYMBOL)), (x (eql VALUE)), (x (derived-mode MODE)), or a cl-defstruct type. Qualifiers are :around, :before, :after, :extra "NAME"; (cl-call-next-method) and (cl-next-method-p) are available inside |
(cl-flet, cl-labels, cl-letf) | local functions, recursive local functions, and temporary rebinding of function cells and places |
(oclosure-define …), (oclosure-lambda …) | function objects with typed slots, in oclosure.el (Emacs 29); advice objects and some interactive-form handling use them |
Inline functions and primitives
| Form | Meaning |
|---|---|
(defsubst NAME ARGS BODY…) | defines a function that the byte compiler may substitute into the caller; it is still callable as an ordinary function |
(define-inline NAME ARGS BODY…) | an inline function written with inline-quote, inline-letevals and inline-const-p so that constant arguments are folded |
(declare-function NAME FILE [ARGLIST]) | tells the compiler a function is defined elsewhere; it silences a warning and emits nothing |
(subrp OBJ), (subr-arity S), (subr-name S), (primitive-function-p OBJ) | test and inspect a primitive |
A primitive (a subr) is written in C and has a fixed number of parameters from 0 up to 8, or takes MANY arguments as a vector, or is an UNEVALLED special form. From Lisp a subr is called like any function and signals wrong-number-of-arguments for a bad count; its arity is (MIN . MAX), where unevalled as MAX marks a special form. Help for a primitive shows a signature taken from the C source, which can differ from the real parameter names. Native compilation produces subr objects as well (Native compilation); the byte compiler is covered in Byte-compilation.
Not described
Known, not yet covered
- Reference: the full
cl-defunlambda-list grammar and the dispatch rules ofcl-defmethod(specialiser order, method combination) are outlined, not listed. - Reference: the interactive spec codes, covered in Commands and modes, and the functions that call commands.
- Reference:
oclosureis named, not described: its slot definitions, accessors and use inadviceare not given. - Reference: the versions that introduced
define-inline,define-adviceandcl-fletsemantics are not stated; the pages for Emacs releases are in Emacs versions.
See also
- Macros –
defmacro, compiler macros and expansion - Variables and scope – lexical and dynamic binding
- Commands and modes –
interactiveand key bindings - Byte-compilation – how functions become byte-code objects
- Functions – the manual’s chapter
- Advising Functions – the manual’s section on advice