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

From: Stefan Monnier <[email-masked]>
Date: Sat, 30 Mar 2024 23:02:14 -0400

> I suspect the best option in the above case is to inhibit the inner
> calls to before/after (assuming we're sure they change only the "new
> text"), so we'd be down to:
>
>     ⛔ Warning (emacs): Before: 1278 1281
>     ⛔ Warning (emacs): After: 1278 1288 delta: 7

A simpler option is the patch below.

        Stefan

diff --git a/src/search.c b/src/search.c
index 2ad565fadde..83ff7120e43 100644
--- a/src/search.c
+++ b/src/search.c
@@ -2769,6 +2769,8 @@ DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
   /* Replace the old text with the new in the cleanest possible way.  */
   replace_range (sub_start, sub_end, newtext, 1, 0, 1, true, true);
 
+  signal_after_change (sub_start, sub_end - sub_start, SCHARS (newtext));
+
   if (case_action == all_caps)
     Fupcase_region (make_fixnum (search_regs.start[sub]),
 		    make_fixnum (newpoint),
@@ -2792,7 +2794,6 @@ DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
   /* Now move point "officially" to the end of the inserted replacement.  */
   move_if_not_intangible (newpoint);
 
-  signal_after_change (sub_start, sub_end - sub_start, SCHARS (newtext));
   update_compositions (sub_start, newpoint, CHECK_BORDER);
 
   return Qnil;