Subject: bug#56008: 29.0.50; image-mode buffer scrolled down automatically

From: Eli Zaretskii <[email-masked]>
Date: Thu, 16 Jun 2022 20:11:09 +0300

> From: Visuwesh <[email-masked]>
> Cc: [email-masked],  [email-masked]
> Date: Thu, 16 Jun 2022 22:25:05 +0530
> 
> [வியாழன் ஜூன் 16, 2022 18:49] Eli Zaretskii wrote:
> 
> > What do you mean by "it was `save-window-excursion'"? what is "it" in
> > this case?
> 
> I thought the source of the random, unwarranted scrolling could be
> `save-window-excursion' since it did come with the following warning,
> 
>     BEWARE: Most uses of this macro introduce bugs.
>     E.g. it should not be used to try and prevent some code from opening
>     a new window, since that window may sometimes appear in another frame,
>     in which case ‘save-window-excursion’ cannot help.

We don't create new windows in this case, so that warning is not
relevant.

But save-window-excursion is indeed part of the puzzle, see below.

> >  And how did you see that this is not the case?
> 
> Sorry, but it is close to a year since I looked at the source code.  All
> I remember is being annoyed by the bug despite removing the
> `save-window-excursion' bit willy-nilly.
> 
> [ This was all in ement.el's source code if I wasn't clear, BTW.  ]

I don't know what ement.el does and whether this is related, but
here's what was happening in this case:

  . we invoke eww to fetch some URL
  . before it finishes to fetch the URL, we switch to another window
  . eww finishes fetching the URL and calls shr.el to render it
  . shr.el uses the selected window for rendering, and as part of
    that, it calls set-window-buffer to temporarily make the buffer in
    which it renders be the buffer of the selected window
  . set-window-buffer resets the window's hscroll and vscroll values
  . shr.el calls set-window-buffer inside save-window-excursion, but
    save-window-excursion didn't preserve the value of vscroll, and in
    addition shr.el called set-window-hscroll in one place that wasn't
    inside save-window-excursion
  . so both vscroll and hscroll of the window showing the image ended
    up with zero hscroll and vscroll
  . since image-mode overrides the usual definition of M-> with a
    command that works by setting the window's hscroll and vscroll,
    resetting these two makes the (mistaken) impression that the
    window was scrolled
  . the reason M-x and M-: appeared to "fix" the problem is that
    image-mode defines a window-configuration-change-hook that forces
    the display back to what it was -- this looked to us as if the
    problem was caused by some redisplay bug, something that took me
    some time to realize its being completely wrong