sam boosalis
sam boosalis

Reputation: 1977

an Emacs cursor movement hook, like the JavaScript mousemove event

I want to track the "current word" in the current buffer. which another (networked) application will be aware of.

I could do this by sending a request every time the cursor moves, whether from clicking or scrolling or arrowing or etc. i.e. any time the cursor's position in the buffer changes.

e.g.

(add-hook 'cursor-move-hook 'post-request-with-current-word)

Upvotes: 4

Views: 1541

Answers (1)

Jordon Biondo
Jordon Biondo

Reputation: 4029

Use a post-command-hook this will run after every command, including movement commands.

Obviously this will fire more often than you want, so in your hook, you could do something like keep track of the last position you were at when the hook was run and only fire the network request if the current point differs from the last like so:

(defvar last-post-command-position 0
  "Holds the cursor position from the last run of post-command-hooks.")

(make-variable-buffer-local 'last-post-command-position)

(defun do-stuff-if-moved-post-command ()
  (unless (equal (point) last-post-command-position)
    (let ((my-current-word (thing-at-point 'word)))
      ;; replace (message ...) with your code
      (message "%s" my-current-word)))
  (setq last-post-command-position (point)))

(add-to-list 'post-command-hook #'do-stuff-if-moved-post-command)

Upvotes: 7

Related Questions