Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I use the "when" keyword (or expression) in emacs lisp

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.

like image 207
alabid Avatar asked Jul 14 '11 16:07

alabid


2 Answers

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.

like image 62
Gareth Rees Avatar answered Oct 14 '22 16:10

Gareth Rees


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.

like image 30
Drew Avatar answered Oct 14 '22 18:10

Drew