Elisp: If then else (Conditional)

By Xah Lee. Date: . Last updated: .

If Then Else

The form for “if” expression is:

(if test body)

or

(if test true_body false_body)

(if (< 3 2)
    (progn 8)
  (progn 7))
;; 7

;; if no false clause, return nil
(if (< 3 2)
    (progn 8))
;; nil

when

If you do not need a “else” part, you can use the function when , because it is more clear. The form is:

(when test expr1 expr2 etc)

Its meaning is the same as

(if test (progn expr1 expr2 etc) nil)

Control Structures (ELISP Manual)

cond (Switch)

The cond function tests each clause, if true, it runs that branch and exit.

syntax:

(cond (CONDITION1 BODY1) (CONDITION2 BODY2) etc (t BODY) )

;; example of cond, real world code

(cond
 ((eq major-mode 'dired-mode) (dired-get-marked-files))
 ((eq major-mode 'image-mode) (list buffer-file-name))
 (t (list (read-from-minibuffer "file name:"))))

Reference

Emacs Lisp, Boolean