Given an emacs command name, how would you find key-bindings ? (and vice versa)

Viewed 29907

If I know an emacs command name, says, "goto-line"; what if I want to query whether if there are any key-sequences bound to this command ?

And vice versa, given a key sequence, how can I find its command name ?

5 Answers

To just find key bindings for a command, you can use emacs help's "where-is" feature

C-h w command-name

If multiple bindings are set for the command they will all be listed.

For the inverse, given a key sequence, you can type

C-h k key-sequence

To get the command that would run.

You can get detailed information about a command, also any non-interactive function defined, by typing

C-h f function-name

Which will give you detailed information about a function, including any key bindings for it, and

C-h v variable-name

will give you information about any (bound) variable. Key-maps are kept in variables, however the key codes are stored in a raw format. Try C-h v isearch-mode-map for an example.

For more help on getting help, you can type

C-h ?

The lookup-key function works well, but there's no function for finding the key binding programmatically from a command AFAIK. The following does that and is based on the slime-cheat-sheet command.

(defun lookup-function (keymap func)
  (let ((all-bindings (where-is-internal (if (symbolp func)
                                             func
                                           (cl-first func))
                                         keymap))
        keys key-bindings)
    (dolist (binding all-bindings)
      (when (and (vectorp binding)
                 (integerp (aref binding 0)))
        (push binding key-bindings)))
    (push (mapconcat #'key-description key-bindings " or ") keys)
    (car keys)))

(lookup-key (current-global-map) (kbd "C-x C-b"))    ; => list-buffers
(lookup-function (current-global-map) 'list-buffers) ; => "C-x C-b"

Interactively, as @ShreevatsaR suggested, you can use C-h w <function name> (where-is) and C-h c <key sequence> (describe-key-briefly). See here for more information.

Related