KeyBindingNotation

There are a gazillion ways* to write keys. My favorite notation tries to be as close to the output of C-h k as possible. It uses the ‘kbd’ function to parse a string describing the key.

    (local-set-key (kbd "C-c C-t") 'sgml-tag)

All you need to do is:

Use C-h k to find out how Emacs describes the key sequence, and copy & paste that into your kbd string. Done.

The only catch is with old versions of Emacs and keys with symbolic names. These keys need to come in angle brackets (e.g. (kbd "<f3>"), and apparently older versions of Emacs did not show the angle brackets in their C-h k output. This is not a problem in any recent version of Emacs.

To make things even simpler, one can define a macro like the one bellow:

   (defmacro global-defkey (key def)
     "*Bind KEY globally to DEF.
   KEY should be a string in the format used for saving keyboard
   macros (cf. `insert-kbd-macro')."
     `(global-set-key (read-kbd-macro ,key) ,def))

Now you can simply write:

   (global-defkey "<f3>" 'comment-dwim)

Just remember MissingKeys and ShiftedKeys if you are having trouble identifying the keys you want to assign.

(*) For the remaining gazillion-1 ways to write keys, consult the KeybindingGuide.

See MouseBindingNotation for how to program mouse buttons.


CategoryKeys