Emacs: Use function keys for custom keyboard shortcuts

Posted: - Modified: | emacs

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>"))
You can view 6 comments or e-mail me at sacha@sachachua.com.

6 comments

hya

i get this error when i try the above commands:

global-set-key: Key sequence <f9> <f9> starts with non-prefix key <f9>

any idea?

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

Z

If it's already bound, you need to unbind it with something like (global-unset-key (kbd "<f9>")) . Hope that helps!

Shackra Seaslug

2013-05-25T19:04:37Z

nice, thank you! :D

what about key combinatios like "C-c p" or so, are they written like "<c-c> p" or not?

(kbd "C-c p") should be fine.

hi,
is there any possibility to bind to non-prefix map key.
I'm trying to replace the yank binding, so double yank will call,
popup-kill-ring and single yank will do the normal function.

P.S.: sorry any inconvenience, posting into the 3 years post.

I kinda solve, no problem now :D