Subject: Re: bug#67124: 26.3; query-replace Arg out of range with comma option (at end-buffer)

From: Stefan Monnier <[email-masked]>
Date: Thu, 16 Nov 2023 10:35:26 -0500

> Which makes me wonder why we don't change `replace-match` so it's also
> careful to preserve the match beginning just like it preserves the match
> end.
[...]
> So, I tried the patch below, which makes sense to my superficial
> understanding of the problem, but it apparently doesn't fix the problem
> in the OP's recipe, so I'm clearly missing something.

Hmm... not sure what happened, because I just tried it again and it does
seem to fix the OP's problem.

So I suggest the patch below (adjusted to the new code on `master`).

        Stefan

diff --git a/lisp/replace.el b/lisp/replace.el
index 7fec54ecb27..acf6b8a4652 100644
--- a/lisp/replace.el
+++ b/lisp/replace.el
@@ -2642,16 +2642,9 @@ replace-match-maybe-edit
 	    noedit nil)))
   (set-match-data match-data)
   (replace-match newtext fixedcase literal)
-  ;; `query-replace' undo feature needs the beginning of the match position,
-  ;; but `replace-match' may change it, for instance, with a regexp like "^".
-  ;; Ensure that this function preserves the beginning of the match position
-  ;; (bug#31492).  But we need to avoid clobbering the end of the match with
-  ;; the original match-end position, since `replace-match' could have made
-  ;; that incorrect or even invalid (bug#67124).
-  (set-match-data (list (car match-data) (nth 1 (match-data))))
   ;; `replace-match' leaves point at the end of the replacement text,
   ;; so move point to the beginning when replacing backward.
-  (when backward (goto-char (nth 0 match-data)))
+  (when backward (goto-char (match-beginning 0)))
   noedit)
 
 (defvar replace-update-post-hook nil
diff --git a/src/search.c b/src/search.c
index 692d8488049..177bb720641 100644
--- a/src/search.c
+++ b/src/search.c
@@ -3142,9 +3142,16 @@ update_search_regs (ptrdiff_t oldstart, ptrdiff_t oldend, ptrdiff_t newend)
 
   for (i = 0; i < search_regs.num_regs; i++)
     {
-      if (search_regs.start[i] >= oldend)
+      if (search_regs.start[i] <= oldstart)
+        /* If the subgroup that `replace-match` is modifying encloses the
+           subgroup `i`, then its `start` position should stay unchanged.
+           That's always true for subgroup 0.
+           For other subgroups it depends on details we don't have, so
+           we optimistically assume that it also holds for them.  */
+        ;
+      else if (search_regs.start[i] >= oldend)
         search_regs.start[i] += change;
-      else if (search_regs.start[i] > oldstart)
+      else
         search_regs.start[i] = oldstart;
       if (search_regs.end[i] >= oldend)
         search_regs.end[i] += change;