How would I go about getting the key binding for a function in elisp?

I'd like to know which key is used to quit. e.g. keyboard-quit.

I tried using the function used by help functionality but it's not working.

(require 'help-fns)
(message "%S" (help-fns--key-bindings (quote keyboard-quit)))

However I get the error Symbol’s value as variable is void: keyboard-quit

2 Answers 2


Try this:

(defun foo (function &optional descriptionp)
  (unless (commandp function) (error "Not a command: %s" function))
  (let* ((key   (car (where-is-internal
                      (or (command-remapping function) function)
                      overriding-local-map nil nil)))
         (desc  (and descriptionp  (key-description key))))
    (or desc  key)))

(foo 'keyboard-quit)   ; [7]
(foo 'keyboard-quit t) ; "C-g"

Function help-fns--key-bindings is intended to be used in a particular context, which is not available or relevant here.

  • This returns "" when descriptionp is t and the key is not found, returning nil in this case is probably more convenient.
    – ideasman42
    Sep 18, 2022 at 13:00

You can use substitute-command-keys, e.g.,

(substitute-command-keys "\\[keyboard-quit]")
;; => "C-g"

though if there are multiple key bindings, it returns only one of them (the "first" one), for example,

(substitute-command-keys "\\[kmacro-start-macro]")
;; => "C-x ("

see also it's docstring and (elisp) Keys in Documentation.

  • Works well, ended up using this answer however the other answer more closely matches the question since it takes a function.
    – ideasman42
    Dec 9, 2019 at 20:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.