Emacs: Navigate Lisp Code as Tree
Lisp code with its nested parenthesis syntax represents a tree structure.
Emacs has many commands that are very helpful in moving around nested brackets, analogous to navigating a tree.
backward-sexp
【Ctrl+Alt+←】- Move to previous sibling. (move to the (beginning of) previous sexp unit)
forward-sexp
【Ctrl+Alt+→】- Move to next sibling. (move to the (end of) next sexp unit)
backward-up-list
【Ctrl+Alt+↑】- Move to parent. (move to the (beginning of) outer paren pair)
down-list
【Ctrl+Alt+↓】- Move to first child. (move into the (beginning of) first inner paren pair)
(For historical reasons, lisp code are called “sexp”, short for Symbolic EXPression.)
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+arrow, 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:
forward-sexp
result:(a (b) c▮ d (e f))
forward-list
result:(a (b) c d (e f)▮)
Tip
In practice, navigation by tree structure is not that useful. It's much more useful to move cursor to a bracket. See Emacs: Move Cursor to Bracket 🚀
Emacs, Work with Brackets
- Emacs: Highlight Brackets
- Emacs: Insert Bracket Pairs, electric-pair-mode
- Emacs: Insert Brackets by Pair 🚀
- Emacs: Delete Brackets by Pair 🚀
- Emacs: Move Cursor to Bracket 🚀
- Emacs: Jump to Matching Bracket 🚀
- Emacs: Change Brackets/Quotes 🚀
- Emacs: Navigate Lisp Code as Tree
- Emacs: Select Line, between Quotes, Extend Selection 🚀
- Emacs: Xah Elisp Mode