Subject: [PATCH] ; Hide completion preview when switching windows

From: Eshel Yaron <[email-masked]>
Date: Tue, 05 Dec 2023 21:26:27 +0100

Tags: patch

This patch ensures that we dismiss the completion preview when users
switch to another window.  Previously, the completion preview would
remain in a window after switching to another window showing another
buffer, since the `post-command-hook` that Completion Preview mode sets
up locally doesn't run after a command switches to another buffer.

Thanks,

Eshel

>From 1edb324d5c47fab96eb8131393b1fd38f7dee7ce Mon Sep 17 00:00:00 2001
From: Eshel Yaron <[email-masked]>
Date: Tue, 5 Dec 2023 21:04:43 +0100
Subject: [PATCH] ; Hide completion preview when switching windows

* lisp/completion-preview.el
(completion-preview--window-selection-change): New function.
(completion-preview-mode): Add it to
'window-selection-change-functions'.
---
 lisp/completion-preview.el | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)

diff --git a/lisp/completion-preview.el b/lisp/completion-preview.el
index 1d5f1253702..b4f35d436b3 100644
--- a/lisp/completion-preview.el
+++ b/lisp/completion-preview.el
@@ -377,6 +377,15 @@ completion-preview--active-p
                completion-preview-next-candidate))
   (put cmd 'completion-predicate #'completion-preview--active-p))
 
+(defun completion-preview--window-selection-change (window)
+  "Hide completion preview in WINDOW after switching to another window.
+Completion Preview mode adds this function to
+`window-selection-change-functions', which see."
+  (unless (or (eq window (selected-window))
+              (eq window (minibuffer-selected-window)))
+    (with-current-buffer (window-buffer window)
+      (completion-preview-active-mode -1))))
+
 ;;;###autoload
 (define-minor-mode completion-preview-mode
   "Show in-buffer completion suggestions in a preview as you type.
@@ -391,8 +400,13 @@ completion-preview-mode
 cycles backward."
   :lighter " CP"
   (if completion-preview-mode
-      (add-hook 'post-command-hook #'completion-preview--post-command nil t)
+      (progn
+        (add-hook 'post-command-hook #'completion-preview--post-command nil t)
+        (add-hook 'window-selection-change-functions
+                  #'completion-preview--window-selection-change nil t))
     (remove-hook 'post-command-hook #'completion-preview--post-command t)
+    (remove-hook 'window-selection-change-functions
+                 #'completion-preview--window-selection-change t)
     (completion-preview-active-mode -1)))
 
 (provide 'completion-preview)
-- 
2.42.0