I have added a watcher function to watch the last-command variable.

(defun my-watch (symbol newval op where)
  (message "Hello"))

(add-variable-watcher 'last-command #'my-watch)

The function my-watch does not get invoked at all. How to watch for a variable?


[Please pose a separate question for what you're really trying to do (your first paragraph, which I've removed): how to highlight all the words in the buffer that match the word under cursor, when the cursor is moved. This question should just be about add-variable-watcher (the rest of your post).]

The variable watcher actually works. But last-command is apparently not being set.

To see that it works:

(defun my-watch (symbol newval op where)
  (message "SYM: %S, VAL: %S, OP: %S, WHERE: %S" symbol newval op where))

(add-variable-watcher 'last-command #'my-watch)

(setq last-command 'foobar)

That shows this in the echo area (and buffer *Messages*):

SYM: last-command, VAL: foobar, OP: set, WHERE: nil

But note the limitations documented in node Watching Variables of the Elisp manual:

There are a couple of ways in which a variable could be modified (or at least appear to be modified) without triggering a watchpoint.

Since watchpoints are attached to symbols, modification to the objects contained within variables (e.g., by a list modification function see Modifying Lists) is not caught by this mechanism.

Additionally, C code can modify the value of variables directly, bypassing the watchpoint mechanism.

A minor limitation of this feature, again because it targets symbols, is that only variables of dynamic scope may be watched. This poses little difficulty, since modifications to lexical variables can be discovered easily by inspecting the code within the scope of the variable (unlike dynamic variables, which can be modified by any code at all, see Variable Scoping).

  • Then i must assume the last-command is updated from c code. Because it gets updated every time when a new command is executed but only not able to watch it. Is there a way to confirm this. [1] gnu.org/software/emacs/manual/html_node/eintr/… Jun 19 at 23:26
  • last-command is a variable defined in ‘C source code’. is a pretty strong hint.
    – phils
    Jun 19 at 23:38
  • 2
    I believe the code you're looking for is the calls to kset_last_command in command_loop_1 and call-interactively.
    – phils
    Jun 19 at 23:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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