| Author: | John M. Gabriele |
|---|---|
| Updated: | Feb 2008 |
| Back to: | homepage |
This is my GNU Emacs quick reference. GNU Emacs may be the most capable text editor on this planet. Also, after many years of development, it's editing environment is very finely tuned for high productivity. It comes with world-class documentation, and as an added bonus, it shares many of the same key combinations with Bash. 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.
Key combos in Emacs using 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 :.
Also, recall that with Emacs, all keys you hit are commands. The command associated with printing characters is self-insert-command and just prints the character on the screen. 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.
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.
On Debian, install with aptitude install emacs. You probably also want to grab emacs-goodies-el, which contains all sorts of useful stuff (like boxquote and table).
To get a more recent version, and one that uses GTK+, you can instead do:
aptitude install emacs-snapshot-gtk emacs-goodies-el
As of Feb 2008, if you want emacs to use antialiased fonts, follow the Pretty Emacs instructions.
As an alternative to adding the following to your ~/.emacs file, you may use GNU Emacs's built-in customize facility (see "Setting variables" below).
I like to add the following to my ~/.emacs file:
;; So you can drop .el files into your ~/elisp directory.
(setq load-path (cons "~/elisp/" load-path))
;; You may or may not want this one -- it stops Emacs from
;; leaving foo~ files all over the place.
(setq-default make-backup-files nil)
;; See below if your version of Emacs doesn't yet support
;; antialiased fonts.
(set-default-font "DejaVu Sans Mono-8")
;; Use only spaces (no tabs at all).
(setq-default indent-tabs-mode nil)
;; Visually highlight regions when you select them.
;;(setq-default transient-mark-mode t) <--- handled by customize
;; Enable syntax highlighting. XXX
;;(setq-default global-font-lock-mode t) <--- handled elsewhere
;; To stop the window from popping down a half screen when you get to the bottom.
;(setq-default scroll-conservatively 9999)
;; Show column numbers.
(setq-default column-number-mode t)
;; Make a nice quote box around some text.
;(require 'boxquote) <--- Maybe req'd if installed manually.
;; Scrolling the window up/down by one line.
;;
;; To scroll the down, you can do ``C-u 1 C-v``. Then, to repeat it, first
;; ``C-x z``, and then just tap the ``z`` key to do it some more. Same goes for
;; scroll up (``C-u 1 M-v``).
;;
;; To set up keys to map to ``C-u 1 C-v`` and ``C-u 1 M-v``, let's use:
(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.
;; Useful for when you have to repeat a macro many times.
;; Though, as of Emacs 22, just use ``C-x e e e ...`` for this.
;(global-set-key [f5] 'call-last-kbd-macro)
;; 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))
;(if (fboundp 'menu-bar-mode) (menu-bar-mode -1))
;; Display full pathname if appropriate.
(add-hook 'find-file-hooks
'(lambda ()
(setq mode-line-buffer-identification 'buffer-file-truename)))
;; Set the color scheme.
(require 'color-theme)
;(color-theme-initialize) ;; Might be req'd if you manually install.
(color-theme-bharadwaj)
Aside from showing the full pathname in the modeline, if editing a file, you can always just C-x C-f to see the current directory it's in.
Note, that setting global-font-lock-mode may not actually work just right (you might still have to toggle it off and back on to get it enabled). On my system, I instead used the Emacs GUI customize feature to enable it (actually, the GUI menu item), and it works. The top of my ~/.emacs file ends up looking like this:
(custom-set-variables ;; custom-set-variables was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. '(show-paren-mode t) '(transient-mark-mode t) '(uniquify-buffer-name-style (quote forward) nil (uniquify))) (custom-set-faces ;; custom-set-faces was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. )
Emacs 22 now ships with cperl-mode. If you're using an older version of Emacs, and cannot upgrade, download and install (into your ~/elisp directory) the most recent cperl-mode.el file. You may also want to try pod-mode. You can get pod-mode from CPAN. Note though, that it has not yet been updated for Perl 6 Pod.
You might then 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.
Emacs 22 now ships with a python mode of its own (python.el). Previously, most users installed python-mode (last release of python-mode was December 2005).
You can set the font by using set-default-font in your .emacs file:
(set-default-font "DejaVu Sans Mono-8")
To see the list of available fonts, run the fc-list command that comes with the font-config package.
If your version of Emacs doesn't support antialiased fonts, you might like:
(set-default-font "-misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso10646-1")
Instead of using set-default-font, you may instead add a setting for Emacs.font to your ~/.Xresources file. Maybe:
emacs.font:6x13
or
emacs.font: -misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso10646-1
For more ideas on what you might add to your ~/.Xresources file, here's a few ideas that Peter Dyballa passed on to me.
On Debian, apt-get install emacs-color-themes.
Edit: It's been removed from Debian Etch for now, due to lack of a maintainer. See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=399228.
Update: Looks like the emacs-color-themes deb pkg has been superceded by emacs-goodies-el.
Links:
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).
To use modules (aka "libraries", aka "modes") you find around town, just drop them into your ~/elisp directory, restart emacs, 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)
Boxquote comes with the extra emacs goodies package. Use it by selecting what you want quoted and running M-x boxquote-region RET. Especially handy is to use with boxquote is the M-h command (selects the current paragraph).
Use M-x table-insert to easily create plain text tables.
apache-mode.el for editing Apache config files.
Use M-x hexl-find-file to open and edit files in hex mode.
Try M-x ediff-buffers.
| 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 |
The major control key prefixes you'll see are:
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 combination for a given command. In the tables that follow, if more than one key command 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 RET terminates the argument.
| 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.)
| forward by character | C-f |
| backward by character | C-b |
| forward by word | M-f |
| backward by word | M-b |
| smart home | 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 seems wise to resist this temptation. This is because, once you get fast with the Emacs key bindings, 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 | C-d |
| delete word | M-d |
| delete horiz. space | M- |
| backspace over word | M-Backspace |
| insert new line above cur 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").
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!)
Use M-p and M-n to recall previously-searched-for terms.
| 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.
Regarding regexes, note that GNU Emacs doesn't require backslashes for matching {, }, |, (, ), <, and > as text characters in a regex. 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:
| autocomplete | M-/ (hit repeatedly for other choices) |
| comment/uncomment region | M-; |
| 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 |
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, 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), "mark" == where you put a mark, "point" == current cursor location, and "region" == area between mark and point.
| capitalize word | M-c |
| uppercase word | M-u |
| lowercase word | M-l |
| center text on line | M-s |
| 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", 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.
| 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 |
| 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.
| 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:
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:
Of course, you should usually be using version control software (like Bazaar, 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:
Also:
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.
To record a keyboard macro, follow these steps:
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,
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 tips condensed down from Stevey's Effective Emacs:
Also,
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))).
Editing files remotely over ssh. Using dired over ssh. How do I gracefully exit the connection?
See Tramp (where you'll use stuff like C-x C-f /myname@remotehost:/remote/path/to/file.rst). Read about it: info tramp.
Unloading a minor mode?
You usually just run the command again to toggle it.
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.