Subject: bug#65451: 30.0.50; `after-change-functions' are not triggered in the same order the changes are made

From: Eli Zaretskii <[email-masked]>
Date: Tue, 22 Aug 2023 15:22:35 +0300

> From: Ihor Radchenko <[email-masked]>
> Date: Tue, 22 Aug 2023 09:30:47 +0000
> 
> The last bit of the messages corresponds to dabbrev expansion of "UTF"
> to "utf-8-unix":
> 
> ⛔ Warning (emacs): Before: 1278 1281
> ⛔ Warning (emacs): Before: 1278 1288
> ⛔ Warning (emacs): After: 1278 1288 delta: 0
> ⛔ Warning (emacs): After: 1278 1288 delta: 7
> 
> Note how "After: 1278 1288 delta: 0" reports a change of "utf-8-unix"
> that did not alter the buffer text size. It is trigerred _before_
> "After: 1278 1288 delta: 7" that corresponds to replacing "UTF" with
> "utf-8-unix".

The inner Before+After is because replace-match also changes the
letter-case of the replaced text (to match the letter-case of the
original).

> The order of after-change notifications thus do not correspond to the
> order of buffer changes. Org mode is relying upon the correct change
> order to update parser cache with buffer modifications.

I think Org mode is relying on something it should not.  This
particular use case aside, Emacs is allowed to call a function that
changes the buffer from a function that itself changes the buffer, and
it is allowed to call that inner function _before_ it did all the
changes it intended to do.  In such cases you will see Before+After
pairs embedded inside an outer Before+After pair, because most
functions which end up calling these hooks try not to call them too
often, so they generally call the before-hook once at the beginning
and the after-hook once near the end.  IOW, we try to report all of
the changes in one go, instead of reporting them one small chunk
(perhaps even one character) at a time.  And that inevitably leads to
situations like this one.  Which is perfectly normal, from my POV, and
not a bug at all.  I'd hate to make our code more complex, let alone
slower, just to satisfy the reliance on the perfect pairing like you
do.

(We've been through this in other discussions: Org uses these hooks
for purposes they were not designed for.  The ELisp manual even warns
about such assumptions.)

> The same recipe using Emacs 27 yields the correct order

AFAIR, Emacs 27 had quite a few bugs in this area, which were fixed in
development since then.  See bug#42424, for example.