A macro is a function that runs at expansion time. It receives its arguments as unevaluated forms, returns a new form, and the evaluator or compiler then uses the new form in the place of the call. A macro is stored as a list (macro . FUNCTION) in the function cell of its name. Most of the control constructs in this reference are macros. This page covers how to write and expand them, the pitfalls, the pattern-matching macro pcase, the binding conditionals and other macro libraries.
defmacro and expansion
(defmacro NAME ARGLIST [DOCSTRING] [DECLARE] BODY…) defines a macro. The argument list takes &optional and &rest, and &body as a synonym for &rest in cl-defmacro. The body returns the expansion.
(defmacro my-inc (var &optional n)
"Add N (default 1) to VAR."
(declare (indent 1))
`(setq ,var (+ ,var ,(or n 1))))
(macroexpand '(my-inc x 2)) ; => (setq x (+ x 2))
| Function | Meaning |
|---|---|
(macroexpand FORM [ENV]) | expands the outer form until it is no longer a macro call |
(macroexpand-1 FORM [ENV]) | one step |
(macroexpand-all FORM [ENV]) | every macro in the form, at every depth |
(macrop OBJ) | true for a macro, or a symbol whose function is a macro |
(cl-macrolet …), (cl-symbol-macrolet …), (macroexp-progn FORMS), (macroexp-quote V), (macroexp-unprogn F) | local macros, and helper functions for writing expanders |
A macro is expanded each time the form is evaluated by the interpreter, unless eager macro expansion has already replaced it when the file was loaded. A compiled file holds the expansion, and a macro that the file uses must be defined when it is compiled, not only when it is run (see below).
Backquote
| Syntax | Meaning |
|---|---|
`TEMPLATE | a quoted template in which commas mark computed parts |
,FORM | evaluate FORM and insert the value |
,@FORM | evaluate FORM to a list and splice its elements in; the list is copied except when it is the last element of the template, where it is shared |
Backquote also works inside vectors, and the commas count by nesting depth. In a nested template, `(a `(b ,(c ,x))) a comma belongs to the innermost backquote that has not yet been matched: the inner ,(c …) belongs to the inner backquote, and ,x to the outer one, so x is evaluated first. A second comma, written ,,x, evaluates in the outer pass and leaves the inner comma in the result. Macros that write macros need this.
(let ((x 5))
`(a `(b ,(c ,x)))) ; => (a `(b ,(c 5)))
Pitfalls and hygiene
Emacs Lisp macros are not hygienic. The expansion is ordinary code, evaluated in the scope of the caller.
| Problem | Cause | Remedy |
|---|---|---|
| evaluating an argument twice | the macro puts the argument form in the expansion more than once, so side effects repeat | bind it once with let in the expansion |
| variable capture | a variable that the macro introduces has the same name as one the caller uses, or shadows it | use a name that cannot clash: (make-symbol "tmp") or (gensym "tmp"), which are uninterned |
| free-variable capture | the expansion uses a function or variable whose meaning is changed by a local binding in the caller (cl-flet, let) | use unusual names, or keep the logic in a helper function that the macro calls |
| evaluation order | arguments are evaluated in the order the expansion puts them, which may not be the order written | bind them in order with let* |
| macro does what a function could | nothing needs to be unevaluated | write a function (and perhaps defsubst) |
| Helper | Meaning |
|---|---|
(make-symbol NAME) | a fresh uninterned symbol; prints as #:NAME only with print-gensym on |
(gensym [PREFIX]) | a fresh uninterned symbol with a counter in its name |
(macroexp-let2 TEST SYM EXP BODY…), (macroexp-let2* …) | binds SYM to a variable holding EXP in the expansion, unless EXP is already a constant or symbol (according to TEST); Emacs 29 lets macroexp-let2* omit TEST and take single-variable bindings |
(cl-with-gensyms (A B…) BODY…), (cl-once-only (A B…) BODY…) | macro-writing macros: fresh symbols; evaluate each argument once (Emacs 29) |
(defmacro my-swap (a b)
(let ((tmp (make-symbol "tmp")))
`(let ((,tmp ,a))
(setq ,a ,b)
(setq ,b ,tmp))))
Declarations on macros
A declare form (see Functions) in a macro may carry (indent N), which tells the editor how to indent calls, and (debug SPEC), an Edebug specification: t to evaluate the arguments normally, or a list built from form, body, sexp, symbolp, &optional, &rest, &or, lambda-expr and similar tokens so that Edebug knows which arguments are code. (no-font-lock-keyword t) and (autoload-macro expand) are also accepted.
Compiler macros and the compiler
A compiler macro is attached to a function and rewrites a call to it, but only when the code is byte-compiled; the interpreter ignores it. It is defined with (declare (compiler-macro FN)) or cl-define-compiler-macro, and it may return its argument form unchanged to decline. Use it to fold constants or to open-code a common call while keeping the function itself ordinary.
| Form | When it runs |
|---|---|
| a macro call in compiled code | expanded once at compile time; the compiled file contains only the expansion |
(eval-when-compile BODY…) | evaluated at compile time only; in a compiled file its value replaces the form as a constant, so the body does not run at load time |
(eval-and-compile BODY…) | evaluated both at compile time and at load time, for definitions that a macro needs while the file is being compiled |
(require 'cl-lib) inside eval-when-compile | a common way to use macros from a library without loading it at run time |
A macro used before its definition has been read fails to expand, and the call is treated as a function call. The compiler then warns that the function is not known to be defined. Define macros earlier in the file than their uses, or put them in a separate file and require it at compile time. See Byte-compilation.
pcase
(pcase EXP (PATTERN BODY…)…) evaluates EXP once and tries the clauses in order. The first matching pattern runs its body, with any variables the pattern bound. If no pattern matches, the value is nil. Patterns are not evaluated as code; they have their own language.
| Pattern | Matches |
|---|---|
_ | anything, binds nothing |
SYMBOL | anything, and binds SYMBOL to the value |
'VAL | a value equal to VAL; 'nil also matches nil |
KEYWORD, INTEGER, STRING | that literal, compared with equal |
`QPAT | a quasi-quoted pattern: a list, cons or vector matched piece by piece, with ,PAT inside it for a nested ordinary pattern; other elements match themselves |
(pred FUN) | when (FUN value) is true; FUN is a symbol, a lambda, or a form with the value added as the last argument; (pred (not FUN)) negates it |
(guard EXPR) | when EXPR is true, evaluated with the variables bound so far |
(and PAT…) | all patterns match, in order |
(or PAT…) | any pattern matches; each branch should bind the same variables |
(app FUN PAT) | applies FUN to the value and matches the result against PAT |
(cl-type TYPE) | when (cl-typep value 'TYPE) is true (Emacs 28) |
(seq PAT…) | a sequence whose elements match the patterns; &rest PAT matches the tail; from seq.el |
(map KEY… (KEY PAT)… ) | a map (alist, plist, hash table or array); a bare KEY or 'key binds a variable of that name; from map.el |
(rx RX…) | a string that matches the regexp, with (let VAR RX…) binding a group and (backref VAR) repeating it |
(let PAT EXP) | matches PAT against the value of EXP |
(pcase value
('nil "nothing")
((pred integerp) "integer")
(`(,op ,a ,b) (format "%s of %s and %s" op a b))
((and (pred stringp) (app length (and n (guard (> n 3))))) "long string")
(_ "other"))
| Macro | Meaning |
|---|---|
(pcase-exhaustive EXP CLAUSES…) | signals an error when no clause matches |
(pcase-let ((PAT EXP)…) BODY…), (pcase-let* …) | destructuring let and let*, using patterns in place of variables |
(pcase-setq PAT VAL…) | destructuring setq (Emacs 28) |
(pcase-dolist (PAT LIST) BODY…) | dolist with a pattern in place of the variable |
(pcase-lambda (PAT…) BODY…) | a lambda whose parameters are patterns |
(pcase-defmacro NAME ARGS BODY…) | defines a new pattern (NAME …) that expands into other patterns |
Binding conditionals and related macros
| Macro | Meaning |
|---|---|
(if-let* VARLIST THEN ELSE…) | binds sequentially like let* and stops at the first nil; an entry is (SYMBOL VALUE-FORM), (VALUE-FORM), or a lone SYMBOL to test the current binding; _ as the symbol checks the value without binding |
(when-let* VARLIST BODY…) | the same with no else branch |
(and-let* VARLIST BODY…) | like when-let*, but the value is that of the last binding when the body is empty |
(while-let VARLIST BODY…) | repeats the body while all bindings are non-nil (Emacs 29) |
(if-let …), (when-let …) | older names, which also accept a single (SYMBOL VALUE) pair in place of a list; obsolete in Emacs 31 in favour of the * forms |
(named-let NAME BINDINGS BODY…) | a local function that can call itself by NAME; self-calls in tail position are compiled as jumps (Emacs 28) |
(static-if CONDITION THEN ELSE…) | evaluates CONDITION at macro-expansion time and keeps only one branch, so the other is never compiled or warned about (Emacs 30) |
(static-when CONDITION BODY…), (static-unless …) | the same, with no else branch (Emacs 31) |
(when-let* ((buf (get-buffer "*scratch*"))
((buffer-live-p buf))
(name (buffer-name buf)))
(message "Found %s" name))
(static-if (fboundp 'treesit-available-p)
(treesit-available-p)
nil)
Libraries of macros
| Area | Macros |
|---|---|
| cl-lib control | cl-block, cl-return, cl-case, cl-typecase, cl-loop, cl-do, cl-dolist, cl-dotimes, cl-assert, cl-check-type |
| cl-lib binding | cl-flet, cl-labels, cl-letf, cl-macrolet, cl-symbol-macrolet, cl-multiple-value-bind, cl-destructuring-bind, cl-psetq, cl-psetf |
| cl-lib definitions | cl-defun, cl-defmacro, cl-defstruct, cl-defgeneric, cl-defmethod, cl-deftype, cl-defsubst |
places (gv.el) | setf, push, pop, cl-incf, cl-decf, cl-pushnew, cl-callf,gv-define-setter, gv-define-simple-setter, gv-letplace, gv-ref, gv-deref; a place is a variable, (car X), (nth N L), (aref V I), (gethash K H), (alist-get K A), (plist-get P K), (buffer-local-value …) and others with a setter |
deferred evaluation (thunk.el) | thunk-delay makes a thunk, thunk-force evaluates it once and keeps the value, thunk-evaluated-p tests, and thunk-let and thunk-let* (Emacs 27) bind variables that are computed on first use |
| other | with-suppressed-warnings (Emacs 27), with-eval-after-load, with-temp-buffer, with-current-buffer, save-match-data, letrec, dlet, setq-local, defvar-local, defcustom, define-minor-mode, define-derived-mode |
Not described
Known, not yet covered
- Reference: Edebug specification syntax in full (
debugdeclarations) is only summarised. - Reference: the complete list of
cl-libmacros, with their arguments, and thegvsetter table are not listed; the table above names the common ones. - Reference: the precise rule for nested backquote and splicing at the tail of a dotted list is described by example, not formally.
- Reference: the details of
pcasevariable bindings inorpatterns and the behaviour ofpcase-letwhen a pattern does not match are not given; the behaviour ofseqandmappatterns with every option is also not described.
See also
- Evaluation – special forms,
macroexpandand backquote evaluation - Functions – the
declareform, inline functions and advice - Control structures – the conditionals and loops that these macros extend
- Byte-compilation – macro expansion at compile time
- Macros – the manual’s chapter
- Pattern-Matching Conditional – the manual’s section on
pcase