Take the 2-minute tour ×

I'm in the process of learning how to extend my local GNU emacs software by learning emacs lisp. In one of the source codes I encountered I saw a "when" there. I think this is a control structure but I'm not sure. I've tried googling "the when keyword/expression in emacs lisp" (and other similar permutations of the sort). I even checked the gnu.org website. I only found source codes that contained "when" but no description for how and and when to use "when". Can someone tell me how and in what appropriate situations should I use "when" in control structures, etc, in emacs lisp? Thanks in advance.

share|improve this question

2 Answers 2

up vote 14 down vote accepted

Type C-h f when RET and you'll see the documentation:

when is a Lisp macro in subr.el.

(when COND BODY...)

When COND yields non-nil, eval BODY forms sequentially and return value of last one, or nil if there are none.

You can see how it's implemented if you macro-expand it:

ELISP> (macroexpand '(when cond body1 body2 body3))
(if cond
    (progn body1 body2 body3))

You should use when instead of if in the case where you don't have an "else" clause. It looks nicer, and it provides a hint to the reader that there's no "else" clause. If you have an "else" clause but no "then" clause you can write unless.

share|improve this answer
And also note that there's an unless, which may be preferable to (when (not ...) ...) –  sanityinc Jul 14 '11 at 17:26
See the last sentence of my answer! –  Gareth Rees Jul 14 '11 at 17:26
Doh! Yes indeed. –  sanityinc Jul 14 '11 at 17:27

Many people follow the convention of using when and unless to signal to human readers that the return value of the sexp is not important -- what is important are any side effects performed.

share|improve this answer

Your Answer


