Subject: bug#33341: 27.0.50; Undo log merging and change groups

From: Stefan Monnier <[email-masked]>
Date: Fri, 27 Nov 2020 09:44:27 -0500

> (defun my-test-change-groups ()
>   (interactive)
>   (insert "0\n")
>   ;; (undo-boundary)
>   (let ((g (prepare-change-group)))
>     (activate-change-group g)
>     (insert "b\n")
>     (insert "c\n")
>     (cancel-change-group g)))

I see it's a bug indeed: the problem is that `insert` optimizes the undo
entries by reusing a previous undo entry is that was
a consecutive insertion, so when you get to `cancel-change-group` the
`buffer-undo-list` only has a single entry that represent the
combination of all 3 insertions.

I just pushed the patch below which should fix it.

        Stefan

diff --git a/lisp/subr.el b/lisp/subr.el
index e009dcc2b9..1cf3a49fe4 100644
--- a/lisp/subr.el
+++ b/lisp/subr.el
@@ -3036,7 +3036,10 @@ activate-change-group
   (dolist (elt handle)
     (with-current-buffer (car elt)
       (if (eq buffer-undo-list t)
-	  (setq buffer-undo-list nil)))))
+	  (setq buffer-undo-list nil)
+	;; Add a boundary to make sure the upcoming changes won't be
+	;; merged with any previous changes (bug#33341).
+	(undo-boundary)))))
 
 (defun accept-change-group (handle)
   "Finish a change group made with `prepare-change-group' (which see).
diff --git a/test/lisp/subr-tests.el b/test/lisp/subr-tests.el
index 67f7fc9749..e3f798d11c 100644
--- a/test/lisp/subr-tests.el
+++ b/test/lisp/subr-tests.el
@@ -551,5 +551,17 @@ subr-replace-regexp-in-string
   (should (equal (replace-regexp-in-string "\\`\\|x" "z" "--xx--")
                  "z--zz--")))
 
+(ert-deftest subr-tests--change-group-33341 ()
+  (with-temp-buffer
+    (buffer-enable-undo)
+    (insert "0\n")
+    ;; (undo-boundary)
+    (let ((g (prepare-change-group)))
+      (activate-change-group g)
+      (insert "b\n")
+      (insert "c\n")
+      (cancel-change-group g))
+    (should (equal (buffer-string) "0\n"))))
+
 (provide 'subr-tests)
 ;;; subr-tests.el ends here