Subject: bug#56662: 29.0.50; Funny region highlights when highlight-nonselected-windows is t

From: Juri Linkov <[email-masked]>
Date: Wed, 20 Jul 2022 21:05:04 +0300

> If two windows show a single buffer, then the region highlighting is
> strange in the non-selected window.  It is not hard to reproduce,
>
>     1. emacs -Q
>     2. Visit a longish file.
>     3. C-x 3 and scroll up in any of the window.
>     4. M-: (setq highlight-nonselected-windows t) RET.
>     5. Create an active region and compare the highlighting.

This is a long-standing problem.  I used to use a workaround:
https://lists.gnu.org/archive/html/emacs-devel/2018-09/msg00716.html
But it doesn't work correctly anymore.  Then tried to use advice since
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.

#+begin_src emacs-lisp
(defvar-local mark-active-window nil)

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

(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))))

(add-hook 'pre-redisplay-functions #'redisplay--update-mark-active-window)
#+end_src

But still a 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.