113: How do I bind keys (including function keys) to commands?
Keys can be bound to commands either interactively or in your .emacs
file. To interactively bind keys for all modes, type
M-x global-set-key RET KEY CMD RET
To bind a key just in the current major mode, type
M-x local-set-key RET KEY CMD RET
See "Key Bindings" in the on-line manual for further details.
To bind keys on starting Emacs or on starting any given mode, use the
following "trick": First bind the key interactively, then immediately
type "C-x ESC ESC C-a C-k C-g". Now, the command needed to bind the key
is in the kill ring, and can be yanked into your .emacs file. If the key
binding is global, no changes to the command are required. For example,
(global-set-key (quote [f1]) (quote help-for-help))
can be placed directly into the .emacs file. If the key binding is
local, the command is used in conjunction with the "add-hook" command.
For example, in tex-mode, a local binding might be
(add-hook 'tex-mode-hook
(function (lambda ()
(local-set-key (quote [f1]) (quote help-for-help))))
NOTE: * Control characters in key sequences, in the form yanked from the
kill ring are given in their graphic form -- i.e., CTRL is shown
as `^', TAB as a set of spaces (usually 8), etc. You may want to
convert these into their vector or string forms.
* If some prefix key of the character sequence to be bound is
already bound as a complete key, then you must unbind it before
the new binding. For example, if "ESC {" is previously bound:
(global-unset-key [?\e ?{]) ;; or
(local-unset-key [?\e ?{])
* Aside from commands and "lambda lists," a vector or string also
can be bound to a key and thus treated as a macro. For example:
(global-set-key [f10] [?\C-x?\e?\e?\C-a?\C-k?\C-g]) ;; or
(global-set-key [f10] "\C-x\e\e\C-a\C-k\C-g")
* XEmacs has a completely different syntax for binding keys; don't
follow these directions if you are using XEmacs.