Next: Rebinding Keys in Your Init File, Previous: Minibuffer Keymaps, Up: Customizing Key Bindings [Contents][Index]
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 Rebinding Keys in Your Init File, for a description of how to make key rebindings affect future Emacs sessions.
Define key globally to run cmd.
Define key locally (in the major mode now in effect) to run cmd.
Make key undefined in the global map.
Make key undefined locally (in the major mode now in effect).
For example, the following binds C-z to the shell
command (see Interactive Subshell), replacing the normal global
definition of C-z:
M-x keymap-global-set RET C-z shell RET
The keymap-global-set
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 keymap-global-set RET C-x 4 $ spell-other-window RET
redefines C-x 4 $ to run the (fictitious) command
spell-other-window
.
You can remove the global definition of a key with
keymap-global-unset
. This makes the key undefined; if you
type it, Emacs will just beep. Similarly, keymap-local-unset
makes
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 Commands.
Next: Rebinding Keys in Your Init File, Previous: Minibuffer Keymaps, Up: Customizing Key Bindings [Contents][Index]