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

From: Stefan Monnier <[email-masked]>
Date: Sun, 16 Feb 2025 21:45:03 -0500

>> I'm not sure it'd be a good idea, tho: `replace-region-contents` is
>> a "heavy" operation, involving narrowing and another buffer, whereas
>> `replace-region` is meant to be a low-level operation (if we implement
>> it in C, we could arguably use it as *the* low-level operation and
>> define `insert` and `delete-region` on top of it).
>
> On the downside, we already have 2 APIs for this, so having a 3rd one
> will only make the confusion more prominent.

We could start by merging `replace-region-contents` and
`replace-buffer-contents`.
[ We should also improve their docstrings to give some hint about what
  kind of "diff" they're able to find.  E.g. do they use char/word/line
  granularity?  ]

> Who, apart of you and maybe me, will know or remember that those two
> are "heavy" whereas the 3rd one isn't,

Indeed, their name should be upfront about it.
I'd have expected a name like `replace-region-carefully`.

> And how to apply that knowledge to any concrete use case?

Apparently current callers don't have much difficulty choosing between
insert+delete-region and `replace-region-contents`, so I'm not
too worried.
I think the complexity of the API described in the docstring does the
trick to make sure people use the more expensive ones only when they
care enough about the difference.

> Also, if someone wants a "simple" implementation that doesn't care
> about being destructive and clobbering markers, properties, etc., why
> can't they indeed do the delete-region + insert dance?

They can.  But using the new `replace-region` is simpler for them, with
the side benefit that it will behave (slightly) better.
That's kind of the point of `replace-region`: to be a no-brainer
replacement for insert+delete-region.

        Stefan