My GNU Emacs Quick Reference

John M. Gabriele

2022-02-23

Overview

This is my GNU Emacs quick reference. If you find any errors or out-of-date info, please let me know!

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 run Emacs either as a windowed (desktop) application or within your terminal window (see instructions below). When you run emacs from your terminal on your desktop, its the windowed app that starts up.

When you run the Emacs app, the window contains (in Emacs terminology):

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 (in the mini-buffer), 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

(You may also want to check out 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 (to install it: apt install fonts-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")

(require 'package)
;; We'll be installing packages from this Emacs package repo.
(add-to-list 'package-archives
             '("melpa" . "https://melpa.org/packages/"))
(package-initialize)

(setq-default inhibit-startup-screen t)

;; 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 some UI stuff, uncomment:
;(if (fboundp 'scroll-bar-mode) (scroll-bar-mode -1))
;(if (fboundp 'tool-bar-mode)   (tool-bar-mode -1))
;(if (fboundp 'menu-bar-mode)   (menu-bar-mode -1))

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

;; Set the color theme.
(load-theme 'zenburn t)

Using Emacs in the terminal

In your ~/.bashrc, add:

alias ec='emacsclient -nw'

Then, once the main Emacs app has been started, from any terminal you can run ec some-file.txt to edit in your terminal. Exit with “C-x C-c” or “C-x #”.

Copy/Paste

Using the Emacs desktop app, you can copy/paste to and from Emacs.

Installing Emacs Packages

To install a package from the Melpa Emacs package archive, visit https://melpa.org/ and find the package you want. (Note, they have some help docs.)

Then, within Emacs, do:

M-x package-refresh-contents RET
M-x package-install RET whatev-package RET

You can also do M-x package-list-packages to see what’s available, and install from that list instead of having to type in the package name yourself. While in that buffer:

M-x package-autoremove to remove any orphaned dependencies.

See https://www.emacswiki.org/emacs/InstallingPackages for more info.

Using Other Modules

Note: you’ll more commonly install modules from melpa.org using the package commands shown above, and the manual setup shown below will not usually be necessary.

To use modules you find while tooling around the internet, you can 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 automatically loaded each time you start up Emacs, add the following to your ~/.emacs:

(require 'module-name)

To toggle minor modes on and off, 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

Hex Mode

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

For more about hexl-mode, see https://www.emacswiki.org/emacs/HexlMode.

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. In the mini-buffer, 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, in some modes, when you hit Enter (“RET”), if you don’t automatically get the cursor indented on the next line, use C-j.

Sometimes there’s more than one key sequence for a given command. In the tables that follow, if more than one key sequence is listed, use the first one — less-often-used 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)

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

In the mini-buffer, 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 (case-insensitive) C-M-s
regex search bk (case-insensitive) C-M-r
experiment with regexen M-x re-builder
interactive search and replace M-%
interactive regex search and replace 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),

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

To quickly create a buffer for some scratch writing: C-x b aoeu

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.

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.

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:

Links

About this Document

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