How to Edit Lisp Code with Emacs

Buy Xah Emacs Tutorial. Master emacs benefits for life.
, , …,

This page is a tutorial on using emacs's default features to edit lisp code, or any text with matching brackets.

Auto Highlight Parenthesis: show-paren-mode

Emacs: Auto Highlight Parenthesis: show-paren-mode

Inserting Brackets by Pairs

Emacs: Insert Parenthesis by Pair: electric-pair-mode

Navigating Nested Code

Lisp code with its nested parenthesis syntax represents a tree structure. Emacs has several commands that are very helpful in moving around nested syntax, analogous to navigating a tree. The following is a table showing the names, keys, and purpose. (For historical reasons, lisp code units are sometimes called “sexp”, short for Symbolic EXPression.)

emacs lisp code navigation commands
KeyCommandPurpose
Ctrl+Alt+backward-sexpMove to previous sibling
(move to the (beginning of) previous sexp unit)
Ctrl+Alt+forward-sexpMove to next sibling
(move to the (end of) next sexp unit)
Ctrl+Alt+backward-up-listMove to parent
(move to the (beginning of) outer paren pair)
Ctrl+Alt+down-listMove to first child
(move into the (beginning of) first inner paren pair)

(You can define simpler keys for them. For example, single key press on your number pad keys. 〔➤ Emacs: How to Define Keys〕)

The following is lisp source code laid out in a way to show its tree structure. You should try the above commands on it. It is very helpful to understand how sexp corresponds to a tree, and how the commands move the cursor exactly.

(defun
  fold
  (f x li)
  "Applies (f x ele) recursively to the list li …"
  (let
    (
      (li2 li)
      (ele)
      (x2 x)
    )
    (while
      (setq ele (pop li2))
      (setq x2 (funcall f x2 ele))
    )
    x2
  )
)

Place your cursor at the beginning of the left bracket. Now, try to move your cursor, by using ONLY 【Ctrl+Alt+‹arrows›】, to the pop, then move it to let, then funcall.

Moving to Previous/Next Sibling that Has Children

Use backward-list and forward-list to jump to prev/next sibling that has children. (i.e. skip siblings that does not have children.)

For example, suppose you have (a (b) ▮ c d (e f)) and your cursor is before “c”. Then:

Freely Moving Cursor to Brackets

It's also very convenient to have keys that moves to any prev/next opening/closing bracket characters, without regarding the tree structure. See: Emacs: Commands to Move Cursor by Brackets, Quotes.

Selecting Lisp Code by Unit

You can use the command mark-sexpCtrl+Alt+Space】 to select a complete sexp. Your cursor must be on the left bracket.

To select a complete sexp, type 【Ctrl+Alt+】 then 【Ctrl+Alt+Space】.

Backward/Forward Code Section

Emacs: How to Move Cursor Around Source Code Section (^L)

Show lambda as λ

Emacs: Pretty Lambda λ in Emacs 24.4

Like it?
Buy Xah Emacs Tutorial
or share
blog comments powered by Disqus