Subject: Re: bug#56682: locked narrowing

From: Eli Zaretskii <[email-masked]>
Date: Wed, 30 Nov 2022 17:31:59 +0200

> Date: Wed, 30 Nov 2022 14:40:36 +0000
> From: Gregory Heytings <[email-masked]>
> cc: [email-masked], [email-masked], [email-masked]
> 
> > I don't think I understand why it should be problematic or unsafe to 
> > limit the same loop we have to a smaller region of the buffer.
> >
> 
> I see that you already changed the loop to scan from BEG to Z to only scan 
> from BEGV to ZV; somehow I missed that change.  I don't think even that is 
> correct: a command could insert text in the buffer outside of BEGV/ZV. 

It could (although that would be an unusual thing to do), but that's
immaterial: the display engine will never look outside of the restriction,
and so searching beyond that is not useful.  Moreover, safe code in Emacs
cannot look beyond BEGV..ZV without calling 'widen', because various
primitives and subroutines don't expect that and will barf sooner or later;
that's why I made that change in the loop.

> While limiting the loop to a smaller region of the buffer looks like a 
> reasonable thing to do, the question is: how can we determine that region? 
> And I don't see how this can be done, because the detection code is called 
> only when a buffer is about to be displayed, and at that moment we cannot 
> know where characters were inserted in the buffer.  What the code does now 
> is "if enough characters have been inserted in the buffer since last 
> redisplay, check again whether the buffer contains long lines".

If we are going to narrow the buffer to PT ± N characters, then searching
inside slightly more than this region (say, twice more or 5 times more)
should be enough, I think.  It might fail in some borderline cases, but most
files with very long lines have almost all of their lines long, so I see no
problem here.

OTOH, "punishing" large buffers that have no long lines at all doesn't
strike me as a good balance.  Your proposed patch will solve a particular
use case, but it cannot solve all of them.  When modiff becomes large
enough, we will search again, and the threshold of 8 is not so large to
prevent it from happening frequently enough to be an annoyance.  That
annoyance will be for no good reason in buffers that have no long lines.

If you are still unhappy with such a simple heuristics, we could go with
something slightly more complex, like change the threshold of modiff
dynamically based on the buffer size and perhaps the number of times we
already searched without finding long lines -- the larger these two are, the
higher we could bump the threshold.  But I wonder whether this is justified.
I'd say let's find a fixed value that works in all the examples we know
about (we have about a dozen, I think), and leave it at that until someone
reports a real-life problem with it.