Next: , Up: Key bindings

9.1 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.

To make the process of binding keys interactively easier, 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’ function. For example, in TeX mode, a local binding might be

     (add-hook 'tex-mode-hook
       (lambda ()
        (local-set-key (quote [f1]) (quote help-for-help))))