Defining keybindings on the fly in Emacs


This is not a trick nor a hidden capability in Emacs, but it's something I never thought of using until about a mont ago.

In our Emacs configuration, we can define keybindings either global (for use everywhere) or local (for use inside the current buffer) and we do it using global-set-key. I've mentioned this multiple times in this blog.

Here's an example of how you'd use it

  (global-set-key (kbd "H-s") 'save-buffer)

But I recently came to the realization that global-set-key is an interactive function, which means that you can invoke it as any command in Emacs, via M-x (or similar).

So I went meta and assigned global-set-key to H-k (k for key or keybinding).

  (global-set-key (kbd "H-k")  'global-set-key)

Now if I find myself calling a command regularly or if I want to try a particular keybinding, I just need to hit H-k, press the desired keys and insert the command name and I'm all set to go.

Saluti.