Minibuffer Maps Key Bindings Init Rebinding
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 definitions for the same key). Or you can change the current buffer's local map, which affects all buffers using the same major mode.
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, suppose you like to execute commands in a subshell within
an Emacs buffer, instead of suspending Emacs and executing commands in
your login shell. Normally, C-z is bound to the function
suspend-emacs (when not using the X Window System), but you can
change C-z to invoke an interactive subshell within Emacs, by
binding it to
shell as follows:
global-set-key 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; the minibuffer is entered immediately to read cmd. But if you type C-x, another character is read; if that is 4, another character is read, and so on. For example,
RETC-x 4 $ spell-other-window
redefines C-x 4 $ to run the (fictitious) command
The two-character keys consisting of C-c followed by a letter are reserved for user customizations. Lisp programs are not supposed to define these keys, so the bindings you make for them will be available in all major modes and will never get in the way of anything.
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 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.Minibuffer Maps Key Bindings Init Rebinding