Next: Init Rebinding, Previous: Minibuffer Maps, Up: Key Bindings
The way to redefine an Emacs key is to change its entry in a keymap. You can change the global keymap, in which case the change is effective in all major modes (except those that have their own overriding local bindings for the same key). Or you can change a local keymap, which affects all buffers using the same major mode.
In this section, we describe how to rebind keys for the present Emacs session. See Init Rebinding, for a description of how to make key rebindings affect future Emacs sessions.
For example, the following binds C-z to the
command (see Interactive Shell), replacing the normal global
definition of C-z:
M-x global-set-key <RET> C-z shell <RET>
global-set-key command reads the command name after the
key. After you press the key, a message like this appears so that you
can confirm that you are binding the key you want:
Set key C-z to command:
You can redefine function keys and mouse events in the same way; just type the function key or click the mouse when it's time to specify the key to rebind.
You can rebind a key that contains more than one event in the same way. Emacs keeps reading the key to rebind until it is a complete key (that is, not a prefix key). Thus, if you type C-f for key, that's the end; it enters the minibuffer immediately to read cmd. But if you type C-x, since that's a prefix, it reads another character; if that is 4, another prefix character, it reads one more character, and so on. For example,
M-x global-set-key <RET> C-x 4 $ spell-other-window <RET>
redefines C-x 4 $ to run the (fictitious) command
You can remove the global definition of a key with
global-unset-key. This makes the key undefined; if you
type it, Emacs will just beep. Similarly,
a key undefined in the current major mode keymap, which makes the global
definition (or lack of one) come back into effect in that major mode.
If you have redefined (or undefined) a key and you subsequently wish to retract the change, undefining the key will not do the job—you need to redefine the key with its standard definition. To find the name of the standard definition of a key, go to a Fundamental mode buffer in a fresh Emacs and use C-h c. The documentation of keys in this manual also lists their command names.
If you want to prevent yourself from invoking a command by mistake, it is better to disable the command than to undefine the key. A disabled command is less work to invoke when you really want to. See Disabling.