I have some code that runs in a hook that I want to change to only execute only if the left mouse button is not currently held down. I don't see any obvious functions or variables that let me directly query the mouse button state. What's the easiest way to do this?
This seems to do what you want:
(defun mouse-button-pressed-p () "Return non-nil if last event is a mouse-button down event." (run-hooks 'mouse-leave-buffer-hook) (and (consp last-input-event) (string-match-p "down-mouse-" (format "%s" (car last-input-event)))))
You can test it using
M-x bar. That will give you 2 seconds to perform an action that issues an event and then call
mouse-button-pressed-p to test whether the last event was a mouse-button down event. After 2 seconds it tells you whether at the time
mouse-button-pressed-p was called a mouse-button was depressed (held down).
(defun bar () (interactive) (run-with-timer 2 nil 'foo)) (defun foo () (message (if (mouse-button-pressed-p) "Button is pressed now" "No button is pressed now")))
See the Elisp manual, node Button-Down Events.