Advanced Emacs

November 14, 2008

1. The Emacs Help System

Emacs Tutorial

If you haven’t found it already, pressing C-h t will start the Emacs Tutorial, which is an interactive guide to the basic editing features you’ll need to get up and running. The tutorial is the best place to start learning to use Emacs. If you are currently using Emacs, this is most likely the place you started.

Getting Help

My usual entry points are using C-h <letter>, which display help for the objects specified by <letter>. In particular, C-h b will display a list of all defined key bindings (b is for bindings), and their definitions. Similarly, C-h k will describe a particular key binding (k for key). For writing Emacs Lisp code, two indispensable C-h letters are f for describe-function and v for describe-variable. For more general documentation about Emacs and other packages installed on your system, there’s also C-h i for running info.

To see all key bindings beginning with <prefix>, use <prefix> C-h. For example, many major modes use C-c as a prefix for most commands, so to see a list of bindings beginning with the prefix C-c, press C-c C-h.

Navigation

Also, once you know the commands exist, navigating is quite intuitive: C-c C-b takes you back to the previous help entry and C-c C-f takes you forward. Use TAB and S-TAB to jump between buttons (i.e., links). When the point is at a link (which will be highlighted in blue in a graphical environment), press RET to follow the link. For example, when looking at the help information for a function, usually there is a link to the location where the function is defined in the Emacs Lisp source code.

There is actually a second command for seeking additional help, which is less obvious at first. Pressing C-c C-c calls help-follow-symbol. A symbol, in Lisp parlance, is a generic name, which may be associated with a function, a variable, a face (e.g., for syntax highlighting), etc. The same symbol may be associated with a function and a variable at the same time. Therefore C-c C-c will search for all such documentation and present it all at once in the help buffer.

Apropos

Finally, there are two powerhouse commands that you’ll want to turn to when all else fails. For example, when you’re fairly certain that Emacs has commands for doing something, but aren’t able to find it using any of the usual methods. Say, you want to learn how to edit rectangular regions in Emacs, but can’t remember the commands. That’s where the apropos commands come in. Two important ones are C-h a, for apropos-command, and C-h d, for apropos-documentation.

For example, pressing C-h a RET rectangle RET will list all commands containing the string rectangle, along with their key bindings. Then you can quickly recall that the key binding for kill-rectangle is C-x r k, and that most of the other rectangle commands also begin with C-x r. Note that the “pattern” you provide to these apropos commands can also be a regular expression.

2. Advanced Editing

Cursor Movement

A fundamental scrolling command is C-l (recenter-top-bottom), which vertically centers the point within the current window. A lesser-known fact about C-l, is that pressing it muliple times cycles the position between the center, top, and bottom of the window (or as close as possible). That is, pressing C-l C-l scrolls so that the point is at the top line of the window and pressing C-l C-l C-l scrolls so that the point is at the bottom of the screen.

An even more useful scrolling command in some circumstances is C-M-l (reposition-window), which heuristically scrolls the window in an attempt to display as much useful information as possible. For example, when editing a C program and pressing C-M-l in the body of a function, Emacs will attempt to scroll the window so that the entire function is visible. Pressing C-M-l multiple times cycles the position much like C-l.

General

A hidden Emacs gem is dabbrev-expand, bound to M-/ by default. Emacs keeps an index of all tokens in currently open buffers. When you press M-/, Emacs attempts to autocomplete the current word. Pressing it again gives a second-best completion and so on. This works equally well for source code and text.

M-^ is bound to delete-indentation which joins the current line with the previous one. It is similar to J in vim but backwards. To join with the next line, use a prefix: C-u M-^.

Some useful deletion or kill commands are M-d, which kills forward until the end of the current word (kill-word), M-k, which kills from the point to the end of the sentence (kill-sentence), M-DEL, which kills the previous word (backward-kill-word), and C-x DEL, which kills the previous sentence (backward-kill-sentence).

Spell Check

M-$ is bound to ispell-word and checks the spelling of the word under or before the cursor.

Search and Replace

M-% is bound to query-replace and performs string search and replace with confirmation. Similarly, C-M-% is bound to query-replace-regexp. The functions replace-string and replace-regexp perform similar functions without confirmation but are not bound by default.

Alignment

align is the most basic alignment command and aligns columns at whitespace.

lastname firstname           lastname firstname
Smith John 33-88             Smith    John      33-88
Gere Alan    24-23     =>    Gere     Alan      24-23
Verne Bill 12-34             Verne    Bill      12-34

M-- M-x align will align at decimal points. align-current works similarly, but works on the current section (for example, a subroutine or curly brace block).

align-regexp generalizes align by aligning columns at regular expressions. By default it only aligns at the first occurrence of the regular expression like its align- friends. However when prefixed (C-u align-regexp) it provides other options, namely the option of repeating the alignment.

See also: EmacsWiki:AlignCommands.

3. The Mark and the Region

Transient Mark Mode

Transient Mark mode provides the standard region-highlighting behavior of most other editors. When it is enabled, the region is only active temporarily (when the highlighting is visible). That is, if you highlight a region but decide you want to edit some text, the region becomes inactive as soon as you press another key. On the other hand, when Transient Mark is disabled, you can set the mark and do lots of other stuff before moving the point somewhere and running a command which acts on the region. The latter behavior can be quite a bit more powerful but provides less visual feedback (you have to remember where you set the mark).

When Transient Mark Mode is off, it can be temporarily enabled by pressing C-SPC C-SPC (repeating set-mark-command twice). This allows you to use the advanced features of the mark ring, etc. but quickly change into transient-mark-mode when needed.

In Emacs, some commands behave differently depending on whether Transient Mark mode is enabled or not. Once you become familiar with editing with Transient Mark mode disabled, you can use this fact to your advantage by toggling it with C-SPC C-SPC as necessary.

The mark ring

To generalize a bit, Emacs actually keeps a mark ring much like the kill ring. You can move back through the mark ring in the same way as you can yank previous kills. To complicate matters, there are actually two mark rings: one for the current buffer and a global mark ring.

Here are some useful commands for working with the mark ring:

4. Interacting with the System

Running Shell Commands

M-! is bound to shell-command and prompts for a shell command to run. This command isn’t hard to find with M-x since the name is expected but the meta-bang binding sometimes escapes me. If you use vi, then the binding is reminiscent of the corresponding vi command (!).

M-| is bound to shell-command-on-region (think pipe). When given a prefix (C-u), shell-command-on-region will replace the selected region with the output of the command.

5. etags

Emacs has built-in commands for working with etags tables. The etags command generates TAGS file for your project and Emacs reads this tag table to learn about the important symbols (e.g., subroutine and function names) in the project.

For example, with C source code (.c and .h files):

etags *.[ch]

An example Makefile rule for Fortran .f90 files:

tags:
    -rm -f TAGS
    etags *.f90

Emacs provides several commands and keybindings for using tags.

The first time you use one of these commands, you will be prompted for the location of the tag table, the TAGS file that was created by etags. If you only plan to use tags in this way on a project-by-project basis, then you can avoid this question in the future by adding the following to your .emacs file:

(setq tags-file-name "TAGS")

For more details, see the Tags section of the GNU Emacs Manual.

6. Emacs Lisp

You can use the *scratch* buffer for writing evaluating Lisp code. Notice that this buffer is always opened in Lisp Interaction mode. Lisp expressions that you write there can be evaluated by moving the point to the end of the expression (e.g., at the end of the closing parenthesis of a defun) and pressing C-x C-e.

If you’d like to see the result of the evaluation, use C-j (eval-print-last-sexp), which evaluates the expression in parentheses before the point and inserts the return value into the buffer.

Alternatively, you can execute Emacs Lisp code from the minibuffer by pressing M-:, which runs the command eval-expression.