Skip to content

How do I bind keys (including function keys) to commands?

Keys can be bound to commands either interactively or in your init file (see How do I set up an init file properly?). 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 GNU Emacs Manual.

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 init file. If the key binding is global, no changes to the command are required. For example,

emacs-lisp
(global-set-key [f1] 'help-for-help)

can be placed directly into your init 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

emacs-lisp
(add-hook 'tex-mode-hook
  (lambda ()
   (local-set-key [f1] 'help-for-help)))
  • 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 a 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:
    emacs-lisp
    (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:
    emacs-lisp
    (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")