Next: Modifier Keys, Previous: Rebinding, Up: Key Bindings
If you have a set of key bindings that you like to use all the time, you can specify them in your initialization file by writing Lisp code (see Init File).
There are several ways to write a key binding using Lisp. The
simplest is to use the kbd macro, which converts a textual
representation of a key sequence—similar to how we have written key
sequences in this manual—into a form that can be passed as an
argument to global-set-key. For example, here's how to bind
C-z to shell (see Interactive Shell):
(global-set-key (kbd "C-z") 'shell)
The single-quote before the command name, shell, marks it as a
constant symbol rather than a variable. If you omit the quote, Emacs
would try to evaluate shell as a variable. This probably
causes an error; it certainly isn't what you want.
Here are some additional examples, including binding function keys and mouse events:
(global-set-key (kbd "C-c y") 'clipboard-yank)
(global-set-key (kbd "C-M-q") 'query-replace)
(global-set-key (kbd "<f5>") 'flyspell-mode)
(global-set-key (kbd "C-<f5>") 'linum-mode)
(global-set-key (kbd "C-<right>") 'forward-sentence)
(global-set-key (kbd "<mouse-2>") 'mouse-save-then-kill)
(global-set-key (kbd "C-<down-mouse-3>") 'mouse-yank-at-click)
Instead of using the kbd macro, you can use a Lisp string or
vector to specify the key sequence. Using a string is simpler, but
only works for ASCII characters and Meta-modified
ASCII characters. For example, here's how to bind C-x
M-l to make-symbolic-link (see Misc File Ops):
(global-set-key "\C-x\M-l" 'make-symbolic-link)
To put <TAB>, <RET>, <ESC>, or <DEL> in the string,
use the Emacs Lisp escape sequences ‘\t’, ‘\r’, ‘\e’,
and ‘\d’ respectively. Here is an example which binds C-x
<TAB> to indent-rigidly (see Indentation):
(global-set-key "\C-x\t" 'indent-rigidly)
When the key sequence includes function keys or mouse button events,
or non-ASCII characters such as C-= or H-a,
you must use a vector to specify the key sequence. Each element in
the vector stands for an input event; the elements are separated by
spaces and surrounded by a pair of square brackets. If an element is
a symbol, simply write the symbol's name—no other delimiters or
punctuation are needed. If a vector element is a character, write it
as a Lisp character constant: ‘?’ followed by the character as it
would appear in a string. Here are some examples:
(global-set-key [?\C-=] 'make-symbolic-link)
(global-set-key [?\M-\C-=] 'make-symbolic-link)
(global-set-key [?\H-a] 'make-symbolic-link)
(global-set-key [f7] 'make-symbolic-link)
(global-set-key [C-mouse-1] 'make-symbolic-link)
You can use a vector for the simple cases too:
(global-set-key [?\C-z ?\M-l] 'make-symbolic-link)
Language and coding systems may cause problems with key bindings for non-ASCII characters. See Init Non-ASCII.