Re: Cancel minibuffer when clicking another window

Joost Kremers <[email protected]>
Newsgroups gmane.emacs.help
Message-ID <[email protected]>
On Wed, Mar 04 2026, Stephen Berman wrote:
> On Wed, 04 Mar 2026 12:47:15 +0100 Joost Kremers <[email protected]> wrote:
>
>> Hi list,
>>
>> When Emacs reads input in the minibuffer (i.e., with `read-from-minibuffer`
>> or `completing-read`, etc.) and you click some other window with the mouse,
>> that window is selected, but the minibuffer input isn't cancelled.
>>
>> Is there a way to automatically cancel the minibuffer input when clicking
>> another window?
>
> Maybe this does what you want:
>
> (defun my-exit-minibuffer ()
>   (let ((miniwin (active-minibuffer-window)))
>     (when (and miniwin (not (eq miniwin (selected-window)))
> 	       (mouse-event-p last-command-event)
>       (exit-minibuffer)))))
>
> (add-hook 'post-command-hook #'my-exit-minibuffer)

Thanks! Though with `exit-minibuffer`, the item that's selected is chosen
and the action that the minibuffer was started for is executed with that
value, which is not what I want. (So when I'm doing `switch-to-buffer`, the
window I click on actually switches to the buffer that is highlighted in
the minibuffer; using vertico, that is.)

But this variant seems to work:

```
(defun my-exit-minibuffer ()
  (let ((miniwin (active-minibuffer-window)))
    (when (and miniwin (not (eq miniwin (selected-window)))
	       (mouse-event-p last-command-event)
               (throw 'exit (lambda () (signal 'minibuffer-quit nil)))))))
```


-- 
Joost Kremers
Life has its moments
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.