Subject: Re: bug#76313: New function `replace-region`

From: Stefan Kangas <[email-masked]>
Date: Wed, 19 Feb 2025 18:22:39 +0000

Stefan Monnier via "Bug reports for GNU Emacs, the Swiss army knife of
text editors" <[email-masked]> writes:

>> It's up to you, but I still think that by a relatively simple and
>> backward-compatible change to the API of replace-region-contents we
>> could have a new mode of that function which would do what you wanted.
>> I still don't understand why you rejected that, the reasons you gave
>> sounded minor to me, certainly not important enough to throw in the
>> towel.
>
> The benefits of supporting the `replace-region-contents` API are much
> smaller than the "sounded minor" annoyances we'd have to pay for the
> rest of Emacs's future.

AFAIU, the `replace-buffer-contents` API exists because:

> There are many tools (e.g. auto-formatters) that take buffer contents,
> reformat them, and write the reformatted output somewhere.  However,
> there is no good way how to apply the modified output to the source
> buffer.  The naive way (erasing and re-inserting the buffer contents)
> loses point and markers.  Therefore there should be a function
> (e.g. `replace-buffer-contents') that calculates a minimal diff between
> the old and the new contents and uses editing operations (insert,
> delete, etc.) to apply the diff.  Ideally this would be done without any
> external tools (e.g. 'diff').
  https://debbugs.gnu.org/cgi/bugreport.cgi?bug=25355

This sounds quite specialized to my mind, and the API is also quite
complicated.  I think it's a fine addition for this use case, but I'd
suggest renaming it to something that highlights its specialized nature.

The `replace-region-contents' function builds on that, and similarly has
a complicated calling convention.  I think it should similarly be
renamed to highlight its specialized nature.

Meanwhile, according to what we have learned in Bug#71370, many users
are currently using this:

    (setf (buffer-substring START END) "foo")

I think this shows the need for a more low-level operation, and
`replace-region` seems to fit this use case exactly.  So I would be in
favor of installing it.