Emacs: Use function keys for custom keyboard shortcuts

Quick tip since it was an aha! moment for some people on the #emacs IRC channel.

You can define keyboard shortcuts that are sequences of keys. This is how Emacs can have keyboard shortcuts like C-c C-c. The function keys are great for this, because (a) they often don’t have assigned functions (or have ones that you don’t mind losing), and (b) you don’t have to press two or more keys to start your shortcut sequence, like you would do with C-c.

I like using F8 or F9 because I’m right-handed and my keyboard groups function keys together. On my keyboard, there’s a slight gap separating F5-F8 and F9-F12, which means it’s easy to distinguish F8 from F9 by feel if I happen to land on the edge.

Define those keyboard shortcuts as sequences so that you can add more shortcuts easily without having to rejig your muscle memory.

(global-set-key (kbd "<f9> <f9>") 'org-agenda-list)
(global-set-key (kbd "<f9> <f8>") (lambda () (interactive) (org-capture nil "r")))

If you want to rebind something that was previously bound to a non-prefix map, you can unbind it first:

(global-unset-key (kbd "<f9>"))
  • zeltak

    hya

    i get this error when i try the above commands:

    global-set-key: Key sequence starts with non-prefix key

    any idea?

    thx alot for your blog, its great for a neewb like me!

    Z

    • http://sachachua.com sachac

      If it’s already bound, you need to unbind it with something like (global-unset-key (kbd “”)) . Hope that helps!

  • http://swt.encyclomundi.org/ shackra sislock

    nice, thank you! :D

    what about key combinatios like “C-c p” or so, are they written like ” p” or not?

    • http://sachachua.com sachac

      (kbd “C-c p”) should be fine.