diff --git a/lisp/replace.el b/lisp/replace.el index 6b06e48c384..7fec54ecb27 100644 --- a/lisp/replace.el +++ b/lisp/replace.el @@ -2644,8 +2644,11 @@ passed in. If LITERAL is set, no checking is done, anyway." (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 match data (Bug#31492). - (set-match-data match-data) + ;; 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)))