Emacs Lisp has no statements. Sequencing, choice, repetition and error handling are all forms that return values. A few are special forms in the evaluator (Evaluation); most are macros built on them. This page lists the forms by purpose, then describes non-local exits and the error system, which is the largest part.
Sequencing
| Form | Value |
|---|---|
(progn FORMS…) | evaluates the forms in order; returns the last. (progn) is nil |
(prog1 FIRST FORMS…) | returns the value of the first form |
(prog2 A B FORMS…) | returns the value of the second form; the style guides prefer prog1 with a nested progn |
Conditionals
| Form | Meaning |
|---|---|
(if TEST THEN ELSE…) | the then-part is one form; the else-part is any number of forms, as in a progn |
(when TEST BODY…) | if without an else, body in sequence; returns nil when TEST fails |
(unless TEST BODY…) | runs the body when TEST is nil; returns the last body value, or nil when TEST is true |
(cond (TEST BODY…)…) | takes the first clause whose test is non-nil; a clause with only a test returns that test’s value; the last clause is often (t …) |
(and A B…), (or A B…) | stop at the first nil or at the first non-nil; return that value, and (and) is t, (or) is nil |
(not X), (null X) | true when X is nil; the two are the same function, and not is the usual spelling for a boolean and null for a list |
(pcase EXP (PATTERN BODY…)…) | pattern matching; pcase-exhaustive signals an error when nothing matches. The pattern language is in Macros |
(if-let*, when-let*, and-let*, while-let …) | bind and test in one step; described in Macros |
(cl-case, cl-ecase, cl-typecase …) | dispatch on a value or its type with eql keys (cl-lib) |
(cond
((null xs) 'empty)
((= (length xs) 1) 'single)
(t 'many))
Loops
| Form | Meaning |
|---|---|
(while TEST BODY…) | repeats while TEST is non-nil; always returns nil |
(dolist (VAR LIST [RESULT]) BODY…) | binds VAR to each element; RESULT is evaluated at the end, with VAR bound to nil |
(dotimes (VAR COUNT [RESULT]) BODY…) | VAR runs from 0 up to COUNT minus 1 |
(named-let NAME BINDINGS BODY…) | a local recursive function that the compiler turns into a loop when its calls are in tail position; Emacs 28 |
(cl-loop CLAUSES…) | the Common Lisp loop macro (below) |
cl-dolist, cl-dotimes, cl-do, cl-do*, cl-do-symbols | variants that are inside an implicit cl-block nil, so cl-return works |
mapc, mapcar, mapcan, mapconcat, mapatoms, maphash, seq-do, seq-doseq, seq-map, seq-filter, seq-reduce | iteration by function; named here only, see Lists and hash tables |
Emacs Lisp does not perform general tail-call elimination, so a loop should be written as while, dolist or named-let and not as deep recursion.
cl-loop outline
The clauses come in this order: named NAME, then variable clauses (for, with, repeat), then main clauses. Common ones are listed below.
| Clause | Meaning |
|---|---|
for X in LIST, on, in-ref | elements, tails, places |
for X across ARRAY | array elements |
for I from A to B by N, below, downfrom | numeric ranges |
for K being the hash-keys of TABLE using (hash-values V) | hash tables |
for X = INIT then NEXT | general stepping |
while, until, always, never, thereis | termination tests |
collect, append, nconc, sum, count, maximize, minimize, concat, vconcat | accumulate a result |
if, when, unless … and … end | conditional clauses |
do FORMS…, return X, finally, initially | side effects and exit |
(cl-loop for x in '(1 2 3 4)
when (cl-evenp x) collect (* x x)) ; => (4 16)
Non-local exits
| Form | Meaning |
|---|---|
(catch TAG BODY…) | runs BODY; if a throw with an eq tag runs inside, it returns the thrown value instead |
(throw TAG VALUE) | jumps to the innermost catch for TAG; with no catch, signals no-catch |
(cl-block NAME BODY…), (cl-return-from NAME VALUE), (cl-return VALUE) | lexically scoped exit; cl-return exits a block named nil. With lexical binding the compiler turns it into a jump, and it is cheaper than catch and throw |
(unwind-protect BODY CLEANUP…) | runs the cleanup forms on any exit: normal, throw, error or quit; the value is the value of BODY |
(keyboard-quit), quit-flag, inhibit-quit | see Quitting below |
(catch 'found
(dolist (x items)
(when (matches-p x)
(throw 'found x)))
nil)
Signalling errors
An error is a list (ERROR-SYMBOL . DATA). The symbol has an error-conditions property, a list of the condition names it belongs to, and error-message, a string. A handler matches a condition name, so handling a general condition such as arith-error also handles its children.
| Function | Meaning |
|---|---|
(signal ERROR-SYMBOL DATA) | the primitive that raises an error |
(error FORMAT-STRING &rest ARGS) | signals error with the string made by format-message, so grave accents and apostrophes become curved quotes |
(user-error FORMAT-STRING &rest ARGS) | signals user-error, for a mistake by the user; the debugger does not stop on it, and the message is shown in the echo area |
(define-error NAME MESSAGE &optional PARENT) | defines a new error symbol with a message and one or more parents (default error) |
(error-message-string ERR) | turns an error object into the text that Emacs would show |
(cl-assert FORM), (cl-check-type FORM TYPE) | signal cl-assertion-failed or wrong-type-argument |
(define-error 'my-parse-error "Cannot parse" 'error)
(signal 'my-parse-error '("line" 12))
Handling errors
| Form | Meaning |
|---|---|
(condition-case VAR BODY HANDLERS…) | runs BODY. A handler is (CONDITIONS BODY…), where CONDITIONS is a condition name or a list of them, or t for every error. If an error matches, VAR is bound to the error object (SYMBOL . DATA) and the handler body’s value is returned. VAR may be nil. A handler (:success BODY…) runs when BODY returns normally, with VAR bound to its value (Emacs 28) |
(ignore-errors BODY…) | returns nil if BODY signals any error |
(ignore-error CONDITION BODY…) | the same for one named condition (Emacs 27) |
(with-demoted-errors FORMAT BODY…) | catches errors, prints them as a message with FORMAT, returns nil |
(condition-case-unless-debug VAR BODY HANDLERS…) | like condition-case, but does not catch when debug-on-error is non-nil, so the debugger sees the error |
(handler-bind ((CONDITIONS HANDLER)…) BODY…) | Emacs 30. Runs HANDLER, a function of the error object, at the place where the error is signalled, before the stack is unwound; if the handler returns, the search for other handlers goes on. It is for logging a backtrace and for adding information; it cannot return a value for BODY, and for that a throw or condition-case is needed |
(unwind-protect BODY CLEANUP…) | cleanup that runs while the error propagates |
(condition-case err
(read-from-string text)
(end-of-file (message "Incomplete input"))
(invalid-read-syntax (message "Bad syntax: %S" (cdr err)))
(error (message "Other error: %s" (error-message-string err)))
(:success (message "Read %S" err)))
Quoting a condition in condition-case or ignore-error, as in (ignore-error 'foo …), is a mistake that the compiler warns about since Emacs 30.
Debugger interaction
With debug-on-error non-nil the Lisp debugger starts when an error is signalled and no handler is going to catch it; errors named in debug-ignored-errors are skipped. debug-on-signal starts the debugger at the point of signal, even when a handler exists. debug-on-quit and debug-on-message are other triggers, and (debug) enters the debugger from a program. condition-case-unless-debug exists so that a handler does not hide an error from the debugger.
Standard error symbols
| Symbol | Raised when |
|---|---|
error | the root of all errors; the generic error function |
quit | the user pressed C-g; not a child of error |
minibuffer-quit | quit in the minibuffer |
user-error | the user did something wrong |
wrong-type-argument | an argument failed a type predicate; the data are the predicate and the value |
args-out-of-range | an index or position is outside the bounds |
wrong-number-of-arguments | a call has too few or too many arguments |
void-function, void-variable | the function cell or value cell is empty |
invalid-function | the object called is not a function |
setting-constant | an attempt to set nil, t, a keyword or a constant |
cyclic-function-indirection, cyclic-variable-indirection | a loop of aliases |
circular-list | a list operation met a circular list |
no-catch | throw without a matching catch |
end-of-file | the reader met the end of input inside an object |
invalid-read-syntax | the reader met a malformed token |
arith-error | a numeric error; children overflow-error, range-error, domain-error, singularity-error, underflow-error; division of integers by zero signals arith-error |
beginning-of-buffer, end-of-buffer | movement past the edge of the buffer |
buffer-read-only, text-read-only | an edit of read-only text |
search-failed, invalid-regexp | a search does not match; a regexp is malformed |
scan-error | unbalanced parentheses in scan-lists, forward-sexp, up-list |
file-error | the parent of file-missing, file-already-exists, file-date-error, file-notify-error; data hold the OS error text and file name |
coding-system-error | an unknown coding system |
excessive-lisp-nesting, excessive-variable-binding | the recursion limits, children of recursion-error (see Evaluation) |
wrong-length-argument, mark-inactive, cl-no-applicable-method | further conditions defined in C and Lisp |
Quitting
When the user presses C-g, Emacs sets quit-flag and, at the next safe point, signals quit. While inhibit-quit is non-nil, the signal waits; when the variable is set back to nil the quit takes effect. Code that must not be interrupted binds it with let; with-local-quit and while-no-input help for the opposite case. Handlers in condition-case that list t or error do not catch quit, because quit has no error condition; a handler must name quit explicitly.
Generators
The library generator.el ((require 'generator)) defines lazy sequences by code that can pause. The compiler turns the body into a state machine; it needs lexical-binding.
| Name | Meaning |
|---|---|
(iter-defun NAME ARGS BODY…) | defines a function that returns an iterator when called |
(iter-lambda ARGS BODY…) | an anonymous generator function |
(iter-yield VALUE) | hands VALUE to the consumer and pauses; evaluates to the value sent back by iter-next |
(iter-yield-from ITERATOR) | delegates to another iterator |
(iter-next ITERATOR [VALUE]) | runs to the next yield; signals iter-end-of-sequence when finished |
(iter-do (VAR ITERATOR) BODY…) | loops over an iterator |
(iter-close ITERATOR) | stops it and runs unwind-protect cleanups |
(iter-defun count-to (n)
(let ((i 0))
(while (< i n)
(iter-yield i)
(setq i (1+ i)))))
(iter-do (x (count-to 3)) (message "%d" x))
Not described
Known, not yet covered
- Reference: the complete
cl-loopgrammar (destructuring,being the elements,using,namedand the order rules) is outlined, not listed. - Reference: the full tree of condition names (which standard error is a child of which) is not given; the table lists the common ones. A few rows in it were not checked against the current source.
- Reference:
pcasepattern syntax, in Macros; the debugger commands andbacktracefunctions are not described. - Reference:
with-local-quit,while-no-input,catch-allstyle helpers andcl-fletstyle local exits are only named.
See also
- Evaluation – the special forms these build on
- Macros –
pcase,if-let*and the other binding conditionals - Lists and hash tables – mapping and sequence functions
- Control Structures – the manual’s chapter
- Errors – the manual’s chapter on signalling and handling
- Standard Errors – the manual’s table of error symbols