Movement by S-Expressions

If you've written any Lisp code before, you're familiar with S-Expressions. Since everything in Lisp is an expression, and everything is wrapped in balanced parentheses, it's fairly easy to deduce where each thing starts and ends. For example, here's a piece of Clojure code:

(defn random-color-50 []
  (let [x (rand-int 2)]
    (if (= x 0)
      (random-color)
      dead-color)))

Each block of code limited with parentheses is an S-Expression. Emacs can move cursor by S-Expressions (commonly shortened to sexp). For example, if the cursor (marked with ‖) is at:

(defn random-color-50 []
  (let [x (rand-int 2)]
    (if ‖(= x 0)
      (random-color)
      dead-color)))

Pressing C-M-f moves it forward to the end of sexp:

(defn random-color-50 []
  (let [x (rand-int 2)]
    (if (= x 0)‖
      (random-color)
      dead-color)))

And back with C-M-b:

(defn random-color-50 []
  (let [x (rand-int 2)]
    (if ‖(= x 0)
      (random-color)
      dead-color)))

Luckily, Emacs considers S-expressions in any text and any code, not only in Lisp, and operates on balanced expressions:

  • Any pairs brackets
  • Common pairs of delimeters like "" or ''

For example, with some C code you can easily move from:

int main() ‖{
   ...
}

to:

int main() {
   ...
}‖
MeaningBindingCommand
Forward by s-expC-M-fforward-sexp
Backwards by s-expC-M-bbackward-sexp