Subject: Re: bug#7381: 24.0.50; Provide a hook run when a window is selected

From: martin rudalics <[email-masked]>
Date: Sat, 12 Jan 2019 10:15:24 +0100

;; fixed 7381 27.1
;; quit

 > The subject line says it all: could we get a `window-selected-hook' or
 > `window-selected-functions' or something?
 >
 > Use case: I wanted to make myself a command to select the last selected
 > window (i.e., repeating the command would toggle between two windows).
 >
 > After some head-scratching, the best I could come up with is this:
 >
 > (defun .goto-mru-window ()
 >    (interactive)
 >    (select-window (frame-parameter nil '.last-selected-window)))
 >
 > (defadvice select-window (before .save-selected-window activate)
 >    (set-frame-parameter nil '.last-selected-window (selected-window)))
 >
 > ...which seems to work most of the time, but using an advice doesn't
 > feel that great, esp. with C functions.

Current master now provides a hook run when redisplay detects that the
selected window has changed wrt last redisplay.  The hook is called
'window-selection-change-functions' and is described in detail in the
Elisp manual.  Below I sketch how that hook could be used to provide
the behavior you asked for.

martin

(defvar .old-selected-window (selected-window))

(defun .update-old-selected-window (frame)
   (unless (eq .update-old-selected-window old-selected-window)
     (setq .old-selected-window (old-selected-window))))

(add-hook 'window-selection-change-functions '.update-old-selected-window)

(defun .goto-mru-window ()
   (interactive)
   (select-window .old-selected-window))

(global-set-key [(control .)] '.goto-mru-window)