Note: this quick ref is still for Emacs 23. It needs to be updated for Emacs 24.

Overview

This is my GNU Emacs quick reference. If you’re looking for a tutorial to help you get started right from the very beginning, see the links section at the bottom of this page.

You can usually run Emacs either as a windowed application or in your terminal window (see instructions below).

Key sequences in Emacs involving letters (like C-a) use only lowercase – that is, they don’t use the Shift key on letters to get a different command. The Shift key is only for reaching non-alphabetic characters like % and :.

In Emacs, all keys you hit result in commands being executed. The command associated with regular printing characters is self-insert-command and just inserts the character into the active buffer. Some commands are C-<some_key>, some M-<some_key>, and some are prefix commands (ex. C-c, C-x, and C-h). You hit them, then hit another key after them to get effect of the command.

A pattern that Emacs tends to follow is that complementary commands have 2 different keys – one to do the command and another to do the opposite. Another pattern is that M-<some_key> often gets you a souped-up version of C-<some_key>. For example, C-f moves the cursor forward one character, and M-f moves you forward one word. (An exception is the somewhat odd C-v to page down and M-v to page up.)

Emacs usually does Tab-completion for you, which is quite handy when typing the full name of a command (say, after hitting M-x), or when navigating around your directories to open files.

Installation

On Debian-based distros:

sudo apt-get install emacs emacs-goodies-el

Configuration

When you first start up GNU Emacs, you can go to the menu and make some customizations right there. I suggest making sure the following menu items have checkmarks next to them:

Then do “Options → Set Default Font…” and choose your favorite (Inconsolata is lovely (install: sudo apt-get install ttf-inconsolata)).

Finally, do “Options → Save Options” and Emacs will save any changes to your ~/.emacs file.

I then like to add the following to my ~/.emacs file:

;; So you can drop .el files into your ~/.emacs.d directory.
(add-to-list 'load-path "~/.emacs.d")

;; You may not want this one --- it stops Emacs from
;; leaving foo~ files all over the place. Uncomment at your peril.
;(setq make-backup-files nil)

;; Use only spaces (no tabs at all).
(setq-default indent-tabs-mode nil)

;; Show column numbers.
(setq-default column-number-mode t)

;; Scrolling the window up/down by one line.
;;
;; To scroll the down, you could do `C-u 1 C-v`.
;; And to scroll up: `C-u 1 M-v`.
;;
;; Set keyboard shortcuts for those:
(global-set-key "\M-n" '"\C-u1\C-v")
(global-set-key "\M-p" '"\C-u1\M-v")

;; Note, you can also use `C-u C-v` and `C-u M-v` to scroll by 4
;; lines.
;; See also: scroll-preserve-screen-position

;; This one's so handy it should have its own alias:
(defalias 'qrr 'query-replace-regexp)
;; Then just use `M-x qrr` when you want it. Where did I find this
;; one? Maybe Yegge's Emacs drunken blog post?

;; If you want to remove the X11 UI stuff.
;(if (fboundp 'scroll-bar-mode) (scroll-bar-mode -1))
;(if (fboundp 'tool-bar-mode) (tool-bar-mode -1))
;; Need this next one for copying then pasting into GUI apps.
;(if (fboundp 'menu-bar-mode) (menu-bar-mode -1))

;; Display full pathname for files.
(add-hook 'find-file-hooks
          '(lambda ()
             (setq mode-line-buffer-identification 'buffer-file-truename)))

;; Set the color theme.
(require 'color-theme)
(color-theme-initialize)
;; Here's a nice low-contrast one.
;(color-theme-bharadwaj)
;; or, for something with a dark background:
(color-theme-arjen)

(After setting color-theme-arjen, why won’t (set-background-color "gray22") work? XXX)

You might like to use emacs in terminal mode (I suggest rxvt-unicode-256color). You do this by running emacs -nw. If running in a terminal, the menu bar might not do you much good. You can remove it by toggling menu bar mode (M-x menu-bar-mode).

To make it even easier to run emacs in the terminal, I create an alias in my ~/.bashrc:

alias nw='emacs -nw'

xterm

If using xterm, you may want to set your $TERM environment variable like so:

export TERM=xterm-256color

Fixing the Alt (Meta) key when using xterm

Add this to your .Xresources file:

XTerm*metaSendsEscape: true

Though, I suggest just using urxvt (rxvt-unicode-256color) instead of xterm.

Fixing the backspace key when using Emacs over ssh

When you ssh in to another machine, the Backspace key may act like C-d. To fix this, try:

export TERM=xterm

Setting the xterm font

Again in your .Xresources file, you can add something like:

XTerm*font: 10x20

Using Specific Languages

Clojure

Grab the clojure-mode.el file from https://github.com/technomancy/clojure-mode and save it to your ~/.emacs.d dir. Then, into your ~/.emacs file, add:

(require 'clojure-mode)

If Using Perl

As of version 22, Emacs ships with cperl-mode. If you’re using an older version of Emacs, and cannot upgrade, download and install (into your ~/.emacs.d directory) the most recent cperl-mode.el file.

You might add the following to your ~/.emacs file:

;; Use cperl-mode instead of the default perl-mode.
(defalias 'perl-mode 'cperl-mode)

;; From Damian's PBP. --------------
(custom-set-variables
 '(cperl-close-paren-offset -4)
 '(cperl-continued-statment-offset 4)
 '(cperl-indent-level 4)
 '(cperl-indent-parens-as-block t)
 '(cperl-tab-always-indent t))
;; ---------------------------------

;; To eliminate that trailing space indicator.
(setq cperl-invalid-face nil)

;; See if you like this:
(setq cperl-hairy t)

;; And maybe even this, just to try it out:
;(setq cperl-auto-newline t)

(require 'pod-mode)

Quick tip: Note that, with cperl-mode, you may hit C-j in the middle of a line, and it doesn’t break that line.

General Usage Tips

You can use the Edit cut/copy/paste menu items for copying and pasting between Emacs and other desktop apps. Actually, C-y will paste into your buffer just fine – it’s copy that you need so you can paste into your other desktop apps (since M-w only works inside of Emacs).

Edit: Maybe try (setq x-select-enable-clipboard t) to get it to work right with X11.

Using Modules

To use modules you find around town, just drop them into your ~/.emacs.d directory and load the module using M-x load-library RET module_name (where module_name is the name of the .el file without the “.el”).

If you want the module loaded each time you start up Emacs, add the following to your ~/.emacs:

(require 'module_name)

To toggle minor modes on and off, just activate them again: M-x the-minor-mode.

Some particularly helpful modules and commands

Tramp

Lets you edit remote files:

C-x C-f /ssh:username@host.org:foo.txt

Boxquote

Boxquote comes with the extra emacs goodies package. Use it by selecting what you want quoted and running M-x boxquote-region RET. “Quotes” text like so:

,----
| Ah, she's built like a steakhouse
| but she handles like a bistro.
`----

Especially handy is to use with boxquote is the M-h command (selects the current paragraph).

Table

Use M-x table-insert to easily create plain text tables.

Apache

Apache mode for editing Apache config files. Comes with emacs-goodies-el.

Hex Mode

Use M-x hexl-find-file to open and edit files in hex mode.

Diff

Try M-x ediff-buffers.

Htmlize

Htmlize does a beautiful job. Comes with emacs-goodies-el. Try it:

M-x htmlize-<TAB>

where tapping Tab shows what you can htmlize.

Command Line Options

description option
don’t open a new X window -nw
don’t load any .emacs init file -q
load .emacs file for user -u <user>
give your Emacs window a title -name foo (or -title foo)
use a certain font -fn 6x13
use a certain background color -bg snow3

Emacs commands

The major prefix key sequences that you’ll see are:

C-x

This often has to do with managing files, windows, and buffers.

C-c

mostly used with commands specific to a major mode

C-h

getting into the help system

C-u

either changes the subsequent command in some way, or else used with a number C-u <n> for the next command to execute n times. With no n, C-u just means do it 4 times. C-u C-u means 16, and so on.

M-x

Running a command (mode) by name. M-x is followed by a long name. Use M-p and M-n to scroll through previously-run commands.

The C-<digit>, M-<digit>, and C-M-<digit> prefixes are all shortcuts for C-u <digit>.

Note, when you hit Enter (“RET”), you don’t automatically get the cursor indented on the next line. For that, use C-j.

Sometimes there’s more than 1 key sequence for a given command. In the tables that follow, if more than one key sequence is listed, use the first one – lesser-used ones equivalents are listed after it, in parentheses.

If a given command takes an argument, you’ll be prompted for it in the minibuffer. Hitting Enter terminates the argument.

General

command desc key sequence
cancel C-g
open (“find” a file) C-x C-f
open a file as read-only C-x C-r
toggle read-only-ness C-x C-q
save C-x C-s
save all (interactive) C-x s
save as C-x C-w
exit C-x C-c
open a shell M-x shell
undo C-/ (or C-x u or C-_)
undo only within region C-u C-/
redo (cancel undoing, then undo what you last undid) C-g C-x u
undo to last auto-save or last-save M-x revert-buffer
help ([more on info]) C-h <a|k|i|m|p|t>
Emacs tutorial C-h t
Info in Emacs C-h i
Return and indent C-j
Return & cont comment M-j
do a command n times C-u n command
do a command 4 times (a) C-u command
do a command 16 times C-u C-u command
print 33 hashes in a row C-u 33 #
repeat last command C-x z (then more z’s to keep repeating)

a: Note, sometimes though, the C-u prefix does something special instead. Ex., C-u C-l, or C-u M-|. The other funny prefix I’ve seen is M-0, as in M-0 C-k.

You don’t need to manually reload or refresh a buffer (say, after the file’s been modified by some other program). Just go to that buffer, and the moment you try to change it, Emacs will tell you about the file being modified and ask you what to do.

(For repeating a command, maybe also look into C-x M-: (repeat-complex-command). Haven’t looked into that one yet.)

Cursor navigation

command desc key sequence
forward by character C-f
backward by character C-b
forward by word M-f
backward by word M-b
go to first non-whitespace char M-m
move to beginning of line C-a
move to end of line C-e
beginning of sentence M-a
end of sentence M-e
up by line C-p
down by line C-n
up by paragraph M-{
down by paragraph M-}
page down C-v
page up M-v
goto line n M-g g <n> (see also goto-line)
to top of buffer M-<
to end of buffer M->
scroll window down n lines C-u <n> C-v
scroll window up n lines C-u <n> M-v
redraw screen and center cursor C-l (wait, C-u C-l?)
make cursor line n lines from top C-u <n> C-l

M-m moves the point to the first non-whitespace character on the line.

At first, it can be very tempting to use the arrow keys instead of C-{f|b|p|n}, the HOME and END keys instead of C-a and C-e, the PgUp and PgDn keys instead of C-v and M-v, and the DELETE key instead of C-d. It would seem to be wise to resist this temptation. This is because, once you get fast with the Emacs key sequences, you’re still fast even if you switch to, say, using a laptop where the arrow (and other) keys are smaller or harder to reach. Also you may be using Emacs on a remote machine over ssh, and the arrow/Home/PgUp/PgDn keys might not even work.

By the way, in the GNU Emacs docs, “DelBack” means the Backspace key. I don’t think the docs refer to the keyboard’s Delete key (since you’d just use C-d for that anyway).

Delete, insert, and cut/copy/paste

command desc key sequence
delete C-d
delete word M-d
delete horiz. space M-\
backspace over word M-Backspace
insert new line above current line C-o
insert new line above cur line, but indent C-M-o
cut to end of line C-k
cut to beginning of line C-u 0 C-k (or C-0 C-k)
delete multiple blank lines, leaving only one C-x C-o
paste C-y
cycle through kill ring M-y [M-y ...]

Note: “kill” (or “wipe out”) means cut. “Yank”, strangely enough, means paste (as in, “yank the text out of the kill ring and into the buffer”).

When going back through the kill ring (M-y), if you go back too far and want to move through the ring in the reverse direction, do: C-u -1 M-y (Ugh!)

Searching

Use M-p and M-n to recall previously-searched-for terms.

command desc key sequence
search forward (incremental, case- insensitive) C-s
search backward (incr, case-insensitive) C-r
regex search fwd (c-i) C-M-s
regex search bk (c-i) C-M-r
experiment with regexen M-x re-builder
interactive search and replace M-%
interactive regex s & r M-x query-replace-regexp

During an interactive search & replace:

To continue your search to the next search result, just keep hitting the same command you started the search with (ex. C-s). To end the search, hit RET. Use C-g to abort the whole search and go back to where you started.

See also: M-x re-search-forward, M-x re-search-backward.

Regexen

Regarding regexes, to match {, }, |, (, ), <, or > you just type them as-is. If you want their special meaning, you need to escape them:

Note that Emacs regexen allow the non-greedy matches *?, +?, and ??. Use \w for matching a “word character”.

Your replace term may contain the following special sequences:

Misc programming features

command desc key sequence
autocomplete M-/ (hit repeatedly for other choices)
comment/uncomment region M-;
re-indent/reformat region M-x indent-region
forward-sexp, backward-sexp C-M-f and C-M-b
to end and beginning of function C-M-e and C-M-a
move to next close or prev open paren/bracket/brace C-M-n and C-M-p
up/down scope (clash with Gnome keys though) C-M-u and C-M-d
Load a tags file (a) Loads automatically. See below.
Go to definition of name under cursor. Uses loaded tag file. M-.
rigid indent/de-dent C-x TAB (see also: C-u [-]n C-x TAB)
enable syntax highlighting (b) M-x font-lock-mode
switch to different lang mode M-x other-mode
Convert a well-formed file to unix line-endings (c) C-x C-m f unix
Convert line-endings (DOS to Unix) M-% C-q C-m RET RET
Convert line-endings (Mac to Unix) M-% C-q C-m RET C-q C-j RET

Edit: When using the GUI version of Emacs, you can click (with mouse-button 1) on where it says “(DOS)” or “(MAC)” in the mode line to change the buffer’s line-endings.

a – Regarding tagfiles, Emacs will automatically load ./tags when you first use the M-. command. It may prompt you for the location of the tags file. Emacs can only have one tag file loaded at a time.

b – Regarding syntax highlighting, to switch to, say, XML, do M-x sgml-mode.

c – Regarding converting line-endings from DOS/Windows or Mac to just standard newlines, recall that DOS files have an extra \r in them before the \n, and Mac files have an \r instead of an \n. See http://www.emacswiki.org/cgi-bin/wiki/EndOfLine for more info.

Misc text processing & selecting text

For selecting text (see next table), “mark” == where you put a mark, “point” == current cursor location, and “region” == area between mark and point.

command desc key sequence
capitalize word M-c
uppercase word M-u
lowercase word M-l
center text on line M-x center-line
set-fill-prefix C-x .
transpose character (drag prev char fwd) C-t
transpose word (drag prev word fwd) M-t
set mark C-Space (or C-@)
go back to most recent mark C-u C-Space (repeat to cycle back)
mark to end of word M-@
mark paragraph M-h
mark the whole buffer C-x h
exchange mark and point C-x C-x
cut (“wipe out”) region C-w
copy region M-w
cut to char (zap-to-char) M-z
fill region M-x fill-region
fill paragraph M-q
join cur line with previous one M-^
delete horizontal space M-\
trim trailing whitespace M-x delete-trailing-whitespace
Insert some other file’s contents here C-x i
Filter (pipe) region though shell cmd C-u M-|
insert output from shell command C-u M-! (or M-1 M-!)

Note: you may see the term “justify” (or reflow, or reformat), which is the same as fill.

C-x C-x is useful for popping back to where you just were after any movement or operation that moves the point and sets the mark to your previous location.

You may make rectangular selections as well. Sort of. Just set your mark and point as usual, and then use C-x r k to cut (“kill”), and C-x r y to paste (“yank”). With transient-mark-mode on, you’ll see a regular (not rectangular) selection between mark and point, but the special commands just given will operate on the rectangular region between mark and point.

To convert existing tabs to spaces for a given region: M-x untabify.

Bookmarks

Multiple buffers

action key
switch to other buffer C-x b
list buffers C-x C-b
close (“kill”) a buffer C-x k
toggle RO/RW for a buffer C-x C-q

Split windows

action key
switch to other window C-x o
scroll other window down C-M-v
close other windows C-x 1
close current window C-x 0
split window, same buffer C-x <2|3> (vert, horiz)
balance-windows C-x +
make window taller (1 line) C-x ^
make window taller (4 lines) C-u C-x ^
make window wider (4 lines) C-x }

If you have more than 2 windows, just keep hitting C-x o to cycle through them.

Misc

action key
enter a mode M-x mode-name
execute arbitrary Lisp code (i.e. “Eval”) M-: code, for example, M-: (setq tab-width 4)
execute arbitrary Lisp code in your file Position cursor at closing ‘)’ and then C-x C-e
Insert verbatim (“quoted”) C-q <key>
Enter ascii-art drawing mode M-x picture-mode
Toggle auto-fill mode M-x auto-fill-mode
spell-check current word M-$
spell-check current buffer M-x spell-buffer
narrow buffer to current region C-x n n
Restore (“widen”) buffer again C-x n w

Regarding picture-mode, for something much simpler, you can just enter insert mode with M-x overwrite-mode, or usually just hit the Insert key.

Note, GNU Emacs has its own built-in file system browser. To use it, use C-x d or M-x dired.

Setting variables

You can set a variable in a number of ways. Say you want to set indent-tabs mode to nil:

  1. In your .emacs file, put (setq-default indent-tabs-mode nil)

  2. For the current buffer you’re editing: M-x set-variable RET indent-tabs-mode RET nil RET or M-: (setq indent-tabs-mode nil)

  3. Using the Emacs “in-situ GUI”: M-x customize, then navigate to indent-tabs-mode, or else just go straight to it: M-x customize-variable RET indent-tabs-mode RET

When folks talk about “customizing” a variable, they’re usually talking about using that built-in point-and-click interface. Clicking “save for future sessions” means write it to your ~/.emacs file.

Note that setq works only for the current buffer. setq-default sets a given variable for all buffers.

Backups and auto-save

There’s three ways Emacs helps you recover a file when you need to:

  1. auto-save – Emacs does an auto-save every 300 keystrokes. If you befoul your buffer and need it back the way it was the last time Emacs did an auto-save, use M-x revert-buffer.

  2. Emacs can also give you back your file the way it was the last time you saved it. Again, it’s M-x revert-buffer (you’ll be prompted if there’s also a recent auto-save available).

  3. The backup~ file. Unless told otherwise, Emacs will automatically make a backup of every file you open, when you open it, naming it with the ~ suffix. If you really foul things up, you can go back to this version manually: mv yourfile~ yourfile.

Of course, you should usually be using version control software (like Git, for example) for more coarse-grained file recovery.

More help on help

You need to learn to use the help system to effectively use Emacs. Here’s my executive summary on using built-in help. First, the two biggies:

C-h k

describe-key. Prompts for a keystroke, then shows you the docs for the command to which that keystroke is bound.

C-h f

Then give the name of a function to get help on it.

Also:

C-h b

describe-bindings. Shows you all the current key bindings.

C-h c

describe-key-briefly. Prompts for a keystroke, then tells you what command that keystroke is bound to.

C-h v

Then give the name of a variable to get help on it.

C-h m

describe-mode. Tells you about the current major mode you’re “in”. You’re gonna love this one. :) (Same as M-x describe-mode)

C-h a

apropos-command. Prompts you for a keyword, then opens a 2nd window showing all commands with that word in it.

C-h p

finder-by-keyword. For browsing Emacs packages on this system.

C-h t

Takes you to the built-in Emacs tutorial.

C-h i

info. Takes you to the built-in info (just like typing info on the command line).

C-h C-h

Gives you a list of all the things you can type after C-h.

To get help with what keys may follow a given prefix, type the prefix followed by C-h. This is how C-h C-h works. :)

To get any specially-marked “commentary” text from a library, use the finder-commentary command. For example: M-x finder-commentary RET htmlize RET.

I’ve put together some notes on using the info tool.

To see a listing of the last gaggle of Emacs commands you previously typed, use M-x view-lossage.

Keyboard macros

To record a keyboard macro, follow these steps:

  1. Start recording the macro: C-x (

  2. Execute some editing commands.

  3. End recording of the macro: C-x )

To execute the keyboard macro, hit C-x e (which runs the last one you recorded). Keep hitting e to get the macro to run successively. To tell it to just run over and over until it fails, use M-0 C-x e.

Random background notes

Note that,

GNU Emacs accepts as input 8-bit ascii. The symbols on your keyboard only really cover 7-bit ascii. Using the ALT modifier actually sets that higher bit for you, getting you those last upper 128 ascii characters.

Some good tips

Some tips condensed down from Stevey’s Effective Emacs:

Also,

Features I may not need after all

Q. Does Emacs have H, M, and L like Vim? Otherwise I’ve got to hop paragraph-by-paragraph.

A. M-r is like Vim’s M, but it turns out it’s even better to just use C-s & C-r (and M-{ & M-}) to zip around.

I suppose if you really wanted to, you could try using [C-u *n*] {M-a|M-e}, and [C-u *n*] {C-v|M-v}.

Q. Can I make RET actually do what C-j does?

A. You might consider just getting used to using C-j – it’s actually not so bad to have both RET and C-j. Also, it’s probably the mode’s responsibility for remapping C-j to RET, if that’s what you want. If you really want RET to always do a newline-and-indent, add this to your ~/.emacs::

(global-set-key "\r" 'newline-and-indent)

or, for just, say, Python, the following should work: (add-hook 'python-mode-hook (lambda () (local-set-key (kbd "RET") 'newline-and-indent))).

Learning Lisp

If you really want to master Emacs, you might consider learning Emacs Lisp (aka “elisp”).

The manual is Programming in Emacs Lisp. Links to that and also the Emacs Lisp Reference Manual are listed on the Emacs website.

Before either of those though, you might want to read the tips near the end of shiny and new emacs 22. Quoting that article:

Of course, if you’re interested in Lisp, you might also have a look at Common Lisp and Scheme. The book you want to read is “Structure and Interpretation of Computer Programs” by Abelson and Sussman.

Links

About this Document

Written in Pandoc’s enhanced Markdown, and then processed by Pandoc.