Subject: Re: bug#56393: Actually fix the long lines display bug

From: Eli Zaretskii <[email-masked]>
Date: Fri, 08 Jul 2022 09:55:34 +0300

> From: Gerd Möllmann <[email-masked]>
> Date: Fri, 8 Jul 2022 07:49:30 +0200
> Cc: [email-masked],
>  [email-masked],
>  [email-masked]
> 
>  Yes, this should test window_end_valid before using window_end_pos.
>  An alternative could be window-start point plus some estimation of the
>  window's text, perhaps?
> 
>  Actually, we could be more accurate: we could use move_it_to,
>  similarly to what pos_visible_p does when passed -1 as the position.
> 
> That's a possibility, indeed.

I installed the below on the feature branch.  Testing it, I see that
window_end_valid is false quite a lot in this spot, and in those cases
using window_end_pos yields (a usually small, like 100 - 200 bytes,
but occasionally very large) inaccuracy.

This is very old code (I see it in Emacs 21), with a FIXME comment
since those days, which AFAIU was written with exactly this issue in
mind.  If there are no problems with the fix below, I think it should
be moved to master.

diff --git a/src/xdisp.c b/src/xdisp.c
index 7821c12..a583e10 100644
--- a/src/xdisp.c
+++ b/src/xdisp.c
@@ -18872,19 +18872,32 @@ set_vertical_scroll_bar (struct window *w)
 	  && NILP (echo_area_buffer[0])))
     {
       struct buffer *buf = XBUFFER (w->contents);
+      ptrdiff_t window_end_pos = w->window_end_pos;
+
+      /* If w->window_end_pos cannot be trusted, recompute it "the
+	 hard way".  */
+      if (!w->window_end_valid)
+	{
+	  struct it it;
+	  struct text_pos start_pos;
+
+	  SET_TEXT_POS_FROM_MARKER (start_pos, w->start);
+	  start_display (&it, w, start_pos);
+	  move_it_to (&it, -1, it.last_visible_x, window_box_height (w), -1,
+		      MOVE_TO_X | MOVE_TO_Y);
+	  window_end_pos = BUF_Z (buf) - IT_CHARPOS (it);
+	}
       if (! BUFFER_AUTO_NARROWED_P (buf))
 	{
 	  whole = BUF_ZV (buf) - BUF_BEGV (buf);
 	  start = marker_position (w->start) - BUF_BEGV (buf);
-	  /* I don't think this is guaranteed to be right.  For the
-	     moment, we'll pretend it is.  */
-	  end = BUF_Z (buf) - w->window_end_pos - BUF_BEGV (buf);
+	  end = BUF_Z (buf) - window_end_pos - BUF_BEGV (buf);
 	}
       else
 	{
 	  whole = BUF_Z (buf) - BUF_BEG (buf);
 	  start = marker_position (w->start) - BUF_BEG (buf);
-	  end = BUF_Z (buf) - w->window_end_pos - BUF_BEG (buf);
+	  end = BUF_Z (buf) - window_end_pos - BUF_BEG (buf);
 	}
 
       if (end < start)