Emacs: function that writes down an elisp code that adds a keybinding specified by the user

elisp, emacs, keyboard-shortcuts

Solution

This seems to work:

(defun insert-key (key)
  (interactive (list (read-key-sequence "Key: ")))
  (insert "(global-set-key (kbd \"" (key-description key) "\") 'hello)\n"))

Problem

How can I make an interactive function that interactively read a key from the user (like when you press C-h k) and then writes some line like this: ``` (global-set-key (kbd "C-x C-s") 'hello) ``` where the "C-x C-s" part is replaced appropriately with the read key. Some beginning users have problem making keybindings and in fact I get confused about it too, so I thought let's just automate it.

Original source

Related problems