Elisp Conditionals

Table of Contents

1. progn Function

Sometimes, we need to group multiple expressions together as one single expression. We can use progn. It returns the last expression.

  (progn
    (statement1)
    (statement2)
    ...)

The purpose of progn is similar to block expression { ... } in C.

Similarly, prog1, prog2 do the same job, but they return the first expression and second expression respectively.

  (progn 1 2 3) ; => 3
  (prog1 1 2 3) ; => 1
  (prog2 1 2 3) ; => 2

2. Common Conditional Flows

2.1. If, Then, Else

  (if test body)
  ;; or
  (if test true_body false_body)

Note that, we should use progn if we want to have multiple statements.

2.2. When

If we don’t need else part, we can use when:

  (when test
    expr1
    expr2
    ...)

When using when, we don’t need progn.

2.3. cond as Switch

The cond function tests each clause. If true, it runs that branch and exits.

  (cond
   (condition1 body1)
   (condition2 body2)
   ...
   (t body))

Note, each condition is a single expression; each body is one or more expressions. t branch acts like a default branch.

  ;; e.g.
  (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:"))))

Date: 2026-07-21 Tue