'How to find the location, where an an Emacs Lisp function is bound to a key?

I'm trying to figure out where M-m is bound to back-to-indentation function. When I issue C-h k M-m (describe-key), I get the following output

M-m runs the command back-to-indentation, which is an interactive compiled Lisp function in `simple.el'.

It is bound to M-m.

(back-to-indentation)

Move point to the first non-whitespace character on this line.

When I look at simple.el, I'm seeing only the definition of function back-to-indentation. I searched throughout the file and I didn't see any keybinding done for that function using define-key. I'm assuming that it happens elsewhere.

How can I identify the location where the function is bound to M-m key?

Emacs version: GNU Emacs 24.2.1 (x86_64-apple-darwin12.2.0, NS apple-appkit-1187.34)



Solution 1:[1]

Adding this at the beginning of my .emacs did the trick for me:

(let ((old-func (symbol-function 'define-key))
      (bindings-buffer (get-buffer-create "*Bindings*")))
  (defun define-key (keymap key def)
    (with-current-buffer bindings-buffer
      (insert (format "%s -> %s\n" key def))
      (mapbacktrace (lambda (evald func args flags)
                      (insert (format "* %s\n" (cons func args))))))
    (funcall old-func keymap key def)))

The idea is that I redefine the define-key function (which is used to bind key within keymap to def) to first log its arguments to a buffer *Bindings*, together with the stacktrace of where it's being called from. After that it calls the old version of the function.

This creates a closure to store the old value of define-key, so it depends of lexical-bindings being t. In retrospect, I think it would have been possible to use function advising instead; but using a closure felt simpler.

Since I had this at the beginning of my .emacs, this recorded all calls to define-key during initialization. So I just had to switch to that buffer once initialization finished, find the call where the particular key was bound, and then inspect the backtrace to find the site from which that happened.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1