Subject: Re: bug#45072: 28.0.50; Emacs switches other buffer back uncontrollably, if other window's buffer is changed by user during minibuffer editing

From: Juri Linkov <[email-masked]>
Date: Sat, 12 Dec 2020 22:49:37 +0200

>> Then maybe the commands that pop up the completions window
>> should clean up their windows after use.  What would be the
>> right place to remove used windows?  Maybe in exit-minibuffer?
>> Or in some unwind-protect in case the user types C-g?
>
> The completion mechanism should clean up its traces as soon as it is
> finished - either a choice has been made or it has been aborted: This
> can mean to clean up windows or frames, size back a minibuffer window or
> remove a pop up menu or a dialogue box.  But I hardly ever use that
> mechanism so I cannot tell how it works (or should work) in practice.
>
> In either case 'exit-minibuffer' is too late.  It must be either the
> caller of completions - just in case it wants to, for example, reuse the
> present window for refining the list of completions - or the called
> which might be more noisy with windows popping up and down.  And I
> suppose that completions are not invoked from minibuffer interactions
> alone ...
>
>> This means that quit-window should be used on the completions window.
>> It should do the right thing: either restore a previous buffer in that window,
>> or close the window if no more buffers were displayed in it.
>
> Yes.  But IMO that should be done _before_ reading from the minibuffer
> interaction finished.

There is an existing function 'minibuffer-hide-completions'.  For example,
it's used in completion-in-region-mode this way:

        (unless (equal "*Completions*" (buffer-name (window-buffer)))
          (minibuffer-hide-completions))

I tried to add it to 'exit-minibuffer', and it seems working fine
with non-nil read-from-minibuffer-restore-windows, and I know no other
place that could call minibuffer-hide-completions:

diff --git a/lisp/minibuffer.el b/lisp/minibuffer.el
index 456193d52e..63b9c9996a 100644
--- a/lisp/minibuffer.el
+++ b/lisp/minibuffer.el
@@ -2114,6 +2114,7 @@ minibuffer-hide-completions
 (defun exit-minibuffer ()
   "Terminate this minibuffer argument."
   (interactive)
+  (minibuffer-hide-completions)
   ;; If the command that uses this has made modifications in the minibuffer,
   ;; we don't want them to cause deactivation of the mark in the original
   ;; buffer.