Search code examples
elisp

How to write a function that will define a keyboard shortcut


I'm trying to write a function that will set a shortcut programmatically, as in the MRE below:

(defun my/shortcut-definer (keypress end-message)
  (interactive)
  (global-set-key
   (kbd keypress)
   '(lambda () (interactive) (message end-message))))

  (my/shortcut-definer "C-x x x" "Hello!")

I am tantalisingly close, but when I enter the chosen keyboard shortcut, I get the error:

Symbol’s value as variable is void: end-message

I think the problem is when defining the shortcut I wanted it to evaluate end-message but instead it included the symbol. How can I make it evaluate end-message in the lambda? (Assuming that is the error).


Solution

  • Looking at this link I found a solution to this problem as follows:

    (defun my/shortcut-definer (keypress end-message)
      (interactive)
      (global-set-key
       (kbd keypress)
       `(lambda () (interactive) (message ,end-message))))