Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 38 ยท Configuration and Elisp

Elisp Functions, Control Flow and Lexical Binding

Define your own Emacs commands with defun and interactive, use when, cond, dolist and mapcar, and understand lexical versus dynamic binding.

Once you can read expressions, the next step is to write your own functions and commands. A function is a named, reusable piece of code; a command is a function that you can call with M-x or bind to a key because it is marked interactive. This lesson shows how to define both, how to branch and loop, and why the line lexical-binding: t at the top of your files matters.

The Lisp blocks are real Emacs Lisp. The runnable blocks are JavaScript stand-ins that model the semantics being discussed.

Defining a function

ELISP
(defun my/greet (name)
  "Return a greeting for NAME."
  (concat "Hello, " name "!"))

(my/greet "Emacs")   ; => "Hello, Emacs!"

After defun comes the name, the argument list, an optional docstring (always write one; it appears in C-h f), and the body. The value of the last form is the return value. The my/ prefix is a convention for your own functions: Emacs has one global namespace for functions, so a prefix avoids clashes with built-in or package names.

Optional and rest arguments use keywords:

ELISP
(defun my/join (sep &optional prefix &rest items)
  (concat (or prefix "") (string-join items sep)))

Making a command: interactive

Add (interactive) after the docstring to make a function callable with M-x:

ELISP
(defun my/insert-date ()
  "Insert today's date at point."
  (interactive)
  (insert (format-time-string "%Y-%m-%d")))

(global-set-key (kbd "C-c d") #'my/insert-date)

interactive can also read arguments for you. (interactive "sName: ") prompts for a string, "p" passes the numeric prefix argument, and "r" passes the start and end of the active region:

ELISP
(defun my/count-words-region (start end)
  "Show the number of words between START and END."
  (interactive "r")
  (message "%d words" (count-words start end)))

The #' before a function name is shorthand for (function ...); it tells the byte compiler that you mean a function, and is the preferred way to pass functions around.

Branching

ELISP
(if (> n 0) "positive" "not positive")    ; if/then/else
(when (> n 0) (message "ok") 'done)       ; no else; body may have many forms
(unless buffer-read-only (insert "x"))    ; the opposite of when
(cond ((< n 0) "negative")
      ((= n 0) "zero")
      (t "positive"))                     ; t is the default branch

and and or short-circuit and return the last evaluated value, which gives a common idiom for defaults: (or user-value "fallback"). For richer matching, pcase destructures lists and other data.

Loops and mapping

ELISP
(dolist (x '(1 2 3)) (message "%d" x))     ; for each element
(dotimes (i 3) (message "%d" i))           ; 0, 1, 2
(while (< n 10) (setq n (1+ n)))           ; classic loop

(mapcar #'1+ '(1 2 3))              ; => (2 3 4)   transform a list
(mapc #'insert '("a" "b"))          ; run for side effects
(seq-filter #'cl-evenp '(1 2 3 4))  ; => (2 4)
(cl-remove-if-not #'stringp items)

The seq and cl-lib libraries add the functions you expect from other languages (seq-reduce, seq-find, cl-loop). In an init file, use (require 'cl-lib) before calling cl- functions.

JS Stand-in: when, unless, cond and defaults

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Lexical versus dynamic binding

Elisp historically used dynamic binding: a let of a variable changes its value for every function called while the let is active. Modern code uses lexical binding, where a variable is visible only inside the text of the form that binds it, and closures remember their environment. Emacs still treats a file without the cookie as dynamically bound (at least up to Emacs 30), so put this on the first line of every Elisp file:

ELISP
;;; my-file.el --- description  -*- lexical-binding: t; -*-

Variables declared with defvar or defcustom are always special: they stay dynamic even in lexical files, which is how (let ((case-fold-search nil)) (search-forward ...)) temporarily changes a setting for functions you call.

JS Stand-in: closures versus a dynamic stack

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Putting it together: a useful command

ELISP
(defun my/duplicate-line ()
  "Copy the current line below itself."
  (interactive)
  (let ((text (buffer-substring (line-beginning-position)
                                (line-end-position))))
    (end-of-line)
    (newline)
    (insert text)))
(global-set-key (kbd "C-c l") #'my/duplicate-line)

Notice the pieces: interactive, a let for a local value, and built-in editing primitives (line-beginning-position, newline, insert). Almost every Emacs command is built from buffer functions like these. Test it by placing the cursor after the closing parenthesis of the defun and pressing C-x C-e, then try M-x my/duplicate-line. If something fails, M-x toggle-debug-on-error shows a backtrace.

Use C-M-x (eval-defun) to re-evaluate the function the cursor is in. In a lexical-binding file it also resets defvar default values, which C-x C-e does not.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What makes a function callable with M-x?

    The interactive declaration marks a function as a command.
  2. 2. What does (or nil 0 "x") return?

    or returns the first non-nil value; 0 is not nil, so it wins.
  3. 3. Which line should open an Elisp file so that variables are lexically scoped?

    The file-local cookie lexical-binding: t enables lexical scoping for the file.
  4. 4. What does (mapcar #'1+ '(1 2 3)) return?

    mapcar returns a new list of results; 1+ adds one to each element.

Summary

  • defun defines functions; add a docstring and, for commands, (interactive).
  • if, when, unless, cond, and, or branch; dolist, dotimes, mapcar loop.
  • Prefix your own names (my/) and use #'name to refer to functions.
  • Start Elisp files with lexical-binding: t; defvar/defcustom variables remain dynamic on purpose.
  • Evaluate with C-x C-e or C-M-x; debug with toggle-debug-on-error.

Next: Key Bindings, Hooks and Advice