I like @Tobias's solution. I will add that I use third-party package counsel, which overrides M-x with its own counsel-M-x
function, so advising execute-extended-command
would not work for me.
Here's a barely-tested alternative that tests whether the keys reported by this-command-keys
are bound to a given command, where "a given command" is typically the caller itself (i.e. some-example-command
in the example below).
(defun called-via-key-binding (cmd)
"Returns non-nil if `this-command-keys' is bound to CMD."
(eq (key-binding (this-command-keys)) cmd))
(defun some-example-command ()
(interactive)
(cond
((not (called-interactively-p 'any))
(message "Not called interactively"))
((called-via-key-binding #'some-example-command)
(message "Called via key binding and not M-x"))
(t
(message "Not called via key binding, so maybe called via M-x"))))
(The call to called-interactively-p
should arguably be moved into called-via-key-binding
.)
emacs -Q
version 25.3.1 outputs the keysequence for commands input perM-x
by default in the echo area. – Tobias Feb 1 '18 at 9:03execute-extended-command
. Note thatexecute-extended-command
is bound toM-x
. You can also determine that byC-h k M-x
. Emacs is open source and self-documenting. Since the info about the binding is part of the command bound toM-x
they don't need to identify whether the command is called viaM-x
or via another key sequence. – Tobias Feb 1 '18 at 9:37execute-extended-command
knows as an axiom how the command was invoked so it does not have to determine if a key binding was used. Too bad for me. It would be great if one could use(if (called-interactively-p 'extended-command) ...
or something similar. BTW, I know emacs is open source (it includes elisp code I contributed 30 years ago). – phs Feb 1 '18 at 9:55