2022-02-23
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.
On Debian-based distros:
sudo apt-get install emacs
(You may also want to check out emacs-goodies-el.)
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.
"~/.emacs.d")
(add-to-list 'load-path
(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:
"\M-n" '"\C-u1\C-v")
(global-set-key "\M-p" '"\C-u1\M-v")
(global-set-key
;; 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-hookslambda ()
'(
(setq mode-line-buffer-identification 'buffer-file-truename)))
;; Set the color theme.
(load-theme 'zenburn t)
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 #”.
Using the Emacs desktop app, you can copy/paste to and from Emacs.
To copy/paste from Emacs: select your region, hit M-w to copy, then move to the other gui app and ctrl-v to paste.
To copy/paste to Emacs: select what you want in the other GUI app, hit ctrl-c to copy, then move to Emacs and hit C-y to paste.
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:
d
to mark a package for deletionU
to mark all installed packages to be upgraded to most recent versionsx
to execute the above selectionsM-x package-autoremove
to remove any orphaned dependencies.
See https://www.emacswiki.org/emacs/InstallingPackages for more info.
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
.
Lets you edit remote files:
C-x C-f /ssh:username@host.org:foo.txt
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.
The major prefix key sequences that you’ll see are:
C-x
C-c
C-h
C-u
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
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.
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.)
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).
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!)
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:
y
– replace and find nextn
– find again!
– just go ahead and replace all.
– replace and stop searching^
– go back to previous matchTo 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
.
Regarding regexes, to match {
, }
, |
, (
, )
, <
, or >
you just type them as-is. If you want their special meaning, you need to escape them:
\{
and \}
for explicitly specifying number of occurences\|
for “or”\(
and \)
for grouping\<
and \>
for word boundaries (or just use \b
)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:
\n
– where is a number (starting at 1, ex. \1
, not \$1
) representing the n’th parenthesized group in the match.\&
– original text that was found\#
– number of replacements done so far\?
– prompts you during the search/replace for what to replace withcommand 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.
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
.
To set a bookmark: C-x r m
then make up a name for the bookmark.
To return to it: C-x r b
and give the name, or take the default, which is the last bookmark you used.
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
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.
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
.
You can set a variable in a number of ways. Say you want to set indent-tabs mode to nil:
In your .emacs
file, put (setq-default indent-tabs-mode nil)
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)
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.
There’s three ways Emacs helps you recover a file when you need to:
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
.
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).
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.
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
C-h f
Also:
C-h b
C-h c
C-h v
C-h m
M-x describe-mode
)
C-h a
C-h p
C-h t
C-h i
info
on the command line).
C-h 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
.
To record a keyboard macro, follow these steps:
Start recording the macro: C-x (
Execute some editing commands.
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
.
Note that,
M-x long-command-name
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.
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:
“It’s kinda like XML.”
“Writing elisp code is very much like scripting your actions in the editor.” … “It’s like you’ve got a little worker-bee version of yourself, doing automatically what you could have done by hand (albeit much more slowly) using editor commands.”