Subject: Re: bug#76108: Call `modify_text' only on the text being replaced in `subst-char-in-region'

From: Stefan Monnier <[email-masked]>
Date: Fri, 07 Feb 2025 11:06:25 -0500

>> The reason is that running the modification hooks N times (to replace
>> N chars) would be expensive.
> What if we called `modify_text' for each contiguous region of FROMCHARs?

AFAIK, in practice most such regions would span a single char anyway, so
I don't think it would make a big difference.

[ Furthermore, IIRC, another reasons we like to call the hooks only once
  is that those hooks would otherwise be called while in the middle of
  `subst-char-in-region`, so we'd need to be more careful with potential
  unexpected changes happening while running the hooks.  Nothing that
  can't be handled, but a known source of corner case bugs.  ]

> Do you know of a way we could benchmark it?

I think there are too many different cases to handle it with a benchmark.

>> The `modification-hooks` text property is weaker than the
>> `modification-hooks` overlay property: if you use an overlay here, then
>> you should be able to get the behavior your test wants by checking in
>> your `hook` the value of the second argument (which indicates if it's
>> the "before change" or the "after change" case): while the "before
>> change" call covers the whole region (actually, IIRC it covers the
>> region between the first substituted chars and the end argument), the
>> "after change" should be more specific and cover only the region between
>> the first and the last chars that were substituted.
>
> And that is the intended and desired behavior?

Yes.

> Personally I find it quite unintuitive to have `modification-hooks' be
> "Hooks that are called when some characters in region _might_ be
> modified".

You have to understand the distinction between the "before" and the
"after" calls (which correspond to the `before-change-functions` and the
`after-change-functions` hooks): the "before" call is there to announce
that some change*s* *may* happen in the specified region.

In the vast majority of cases you should care only about the "after" call.
[ Sadly, for the `modification-hooks` placed on text properties (as
  opposed to overlays), only the "before" call is available.  ]

        Stefan