Subject: Selecting buffer automatically

From: Juri Linkov <[email-masked]>
Date: Sat, 23 Dec 2023 19:51:10 +0200

[From emacs-devel]
>>> I believe this should be customizable with something like
>>> 
>>>  (setopt display-buffer-alist
>>>   '(("\\*Compile-Log\\*" nil (select-window . t))))
>>
>> Thank you for the advice, but I tried this and it didn't work.
>> *Compile-log* buffer isn't selected.
>
> This feature was discussed in bug#33258 and bug#46034,
> but not yet implemented.  It should be easy to implement
> exactly the same way as 'windmove-display-in-direction'
> selects the old or new window in 'post-command-hook'.
> Ok, I will post a patch to bug-gnu-emacs.

Here is the patch that allows using (select-window . t) in display-buffer-alist
to select the displayed window, and (select-window . nil) to deselect windows
selected by such functions as pop-to-buffer:

diff --git a/lisp/window.el b/lisp/window.el
index 40070a4d929..fad95601a55 100644
--- a/lisp/window.el
+++ b/lisp/window.el
@@ -7851,6 +7856,16 @@ display-buffer
       (while (and functions (not window))
         (setq window (funcall (car functions) buffer alist)
               functions (cdr functions)))
+      (when-let ((select-window (assq 'select-window alist)))
+        (letrec ((postfun
+                  (lambda ()
+                    (if (cdr select-window)
+                        (when (window-live-p window)
+                          (select-window window))
+                      (when (window-live-p (old-selected-window))
+                        (select-window (old-selected-window))))
+                    (remove-hook 'post-command-hook postfun))))
+          (add-hook 'post-command-hook postfun)))
       (and (windowp window) window))))
 
 (defun display-buffer-other-frame (buffer)