I have a usecase for this-command and last-command, because I'd like a double invocation of a command to behave differently (it's an indenter, FWIW).

Some manual interactive experiments suggest that invoking commands manually with M-x or key combinations set the this-command and cycle last-command, which can sometimes get confusing if the command has any kill-* behaviour in it. This is as expected.

However, when called from my ert tests, even if I invoke functions with run-interactively, this-command remains nil.

How can I make my scripted ert tests invoke commands so that this-command / last-command behave the same as when the user is entering those commands?

  • 1
    Perhaps start by readling (elisp) [Command Loop Info], if you haven't already.
    – Drew
    Apr 8, 2019 at 19:36

1 Answer 1


It's not perfect, but ert-simulate-command from ert-x works fairly well.

ert-simulate-command is a compiled Lisp function in ‘ert-x.el’.

(ert-simulate-command COMMAND)

Simulate calling COMMAND the way the Emacs command loop would call it.

This effectively executes

(apply (car COMMAND) (cdr COMMAND))

and returns the same value, but additionally runs hooks like ‘pre-command-hook’ and ‘post-command-hook’, and sets variables like ‘this-command’ and ‘last-command’.

COMMAND should be a list where the car is the command symbol and the rest are arguments to the command.

NOTE: Since the command is not called by ‘call-interactively’ test for ‘called-interactively’ in the command will fail.

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.