Subject: bug#9609: Excessive transient region highlighting with highlight-nonselected-windows

From: Juri Linkov <[email-masked]>
Date: Thu, 03 Jun 2021 01:02:25 +0300

>> > > emacs -Q --eval '(progn (setq highlight-nonselected-windows t) (transient-mark-mode -1))' -f make-frame
>> > >
>> > > Two frames open showing the *scratch* buffer, once frame has focus.
>> > >
>> > > With the mouse, click on the "n" of "notes" in the focused frame. Do
>> > > not release the mouse. In the other frame, a region starting or ending
>> > > at "n" is now selected.
>> >
>> > I can confirm that this is still present in Emacs 28.
>> >
>> > Pretty weird behaviour.
>>
>> Probably we decided that the mouse was dragged because the coordinates
>> in the other window are different.  Or something like that.
>
> Btw, you don't need another frame to demonstrate the issue.  You could
> do this instead:
>
>   emacs -Q --eval '(progn (setq highlight-nonselected-windows t) (transient-mark-mode -1))'
>   C-x 2
>   Click and hold the mouse button on some character

The problem is that currently the mark is not window-local.
I tried such workaround, that fixes the above problem, but it has
other issues.  A proper fix needs to be in some low-level function.

#+begin_src emacs-lisp
;; Make the mark buffer-and-window-local.

(defvar-local mark-active-window nil)

(add-hook 'activate-mark-hook (lambda () (setq mark-active-window (selected-window))))
(advice-add 'activate-mark :after
            (lambda (&rest _args)
              (setq mark-active-window (selected-window)))
            '((name . mark-active-window)))

;; Can't use deactivate-mark-hook because when clicking mouse in another window
;; with the same buffer it calls both activate-mark and deactivate-mark,
;; but deactivate-mark checks if the region is active (region-active-p),
;; and doesn't advance further because mark-active was set to nil in the redisplay
;; hook below.  OTOH, the advice is used unconditionally.
(add-hook 'deactivate-mark-hook (lambda () (setq mark-active-window nil)))
(advice-add 'deactivate-mark :after
            (lambda (&rest _args)
              (setq mark-active-window nil))
            '((name . mark-active-window)))

(defun redisplay--update-mark-active-window (window)
  (when mark-active-window
    (setq mark-active (eq mark-active-window window))))

;; Problem: when compiled without optimization CFLAGS='-O0' then
;; quick region selection experiences lags that results in wrong selection.
;; Another problem is that in ‘follow-mode’ ‘set-mark-command’ messes up windows.
(add-hook 'pre-redisplay-functions #'redisplay--update-mark-active-window)
#+end_src