7

Suppose that I have an Emacs session running, and that I step away from my computer for, say, 20 minutes. Upon returning to my Emacs session, at some point I will press some key while the Emacs window has the focus. This would be an example of the sort of event I'm calling first-keypress-in-a-while 1.

I'm looking for a way to have Emacs automatically run some code whenever such an event happens. IOW, I'm looking for something like a first-keypress-in-a-while-hook.

Looking through Emacs' standard hooks I cannot immediately identify a good candidate, but maybe there is a non-obvious one that could do this job.

Alternatively, is there some other way that I could simulate/approximate such a hook's functionality?


1 Of course, in-a-while refers to some user-settable parameter corresponding to some minimum time interval, say 15 minutes. The event I'm interested in is the first key press after a period of inactivity longer than this interval. By "inactivity" I mean the state where Emacs detects no user interaction: no key-presses, no mouse clicks, etc.

Drew
  • 75,699
  • 9
  • 109
  • 225
kjo
  • 3,145
  • 14
  • 42

2 Answers2

7

You could try:

(defun my-run-fkpiawh ()
  (remove-hook 'pre-command-hook #'my-run-fkpiawh)
  (run-hooks 'first-keypress-in-a-while-hook))
(run-with-idle-timer 1200 t (lambda ()
                              (add-hook 'pre-command-hook
                                        #'my-run-fkpiawh)))

After which you can use add functions to first-keypress-in-a-while-hook.

Stefan
  • 26,154
  • 3
  • 46
  • 84
  • 1
    Should your function also remove itself from `pre-command-hook` after it runs? I think this will add my-run-fkpiawh to every command called after the idle period, instead of just the first? – Tyler Nov 29 '16 at 15:52
6

I guess a solution of your problem is setting a flag with an idle timer, https://www.gnu.org/software/emacs/manual/html_node/elisp/Idle-Timers.html

and checking/unsetting it with post-self-insert-hook or a similar hook of your choice.

The following works for me:

(defvar *my-idle-flag* nil)
(run-with-idle-timer 900 t (lambda () (setq *my-idle-flag* t)))
(add-hook 'post-self-insert-hook
      (lambda()
        (if *my-idle-flag* (message "plong"))
        (setq *my-idle-flag* nil)))
Vera Johanna
  • 873
  • 6
  • 9