From b7ddd0f2fd08c9dca0b75493e9e809bb5dab40d9 Mon Sep 17 00:00:00 2001 From: Lars Ingebrigtsen Date: Tue, 3 May 2022 22:04:39 +0200 Subject: [PATCH] Make with-buffer-unmodified-if-unchanged more resilient * lisp/emacs-lisp/subr-x.el (with-buffer-unmodified-if-unchanged): Make more resilient. --- lisp/emacs-lisp/subr-x.el | 18 ++++++++++-------- test/lisp/sort-tests.el | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/lisp/emacs-lisp/subr-x.el b/lisp/emacs-lisp/subr-x.el index 8e763b613ee..a416059df62 100644 --- a/lisp/emacs-lisp/subr-x.el +++ b/lisp/emacs-lisp/subr-x.el @@ -426,22 +426,24 @@ modification status: (with-buffer-unmodified-if-unchanged (insert \"a\") - (delete-char -1)) - -BODY must preserve the current buffer." + (delete-char -1))." (declare (debug t) (indent 0)) - (let ((hash (gensym))) + (let ((hash (gensym)) + (buffer (gensym))) `(let ((,hash (and (not (buffer-modified-p)) - (buffer-hash)))) + (buffer-hash))) + (,buffer (current-buffer))) (prog1 (progn ,@body) ;; If we didn't change anything in the buffer (and the buffer ;; was previously unmodified), then flip the modification status ;; back to "unchanged". - (when (and ,hash (buffer-modified-p) - (equal ,hash (buffer-hash))) - (restore-buffer-modified-p nil)))))) + (when (buffer-live-p ,buffer) + (with-current-buffer ,buffer + (when (and ,hash (buffer-modified-p) + (equal ,hash (buffer-hash))) + (restore-buffer-modified-p nil)))))))) (provide 'subr-x) diff --git a/test/lisp/sort-tests.el b/test/lisp/sort-tests.el index 7f49cc38d1b..5fcae308d6a 100644 --- a/test/lisp/sort-tests.el +++ b/test/lisp/sort-tests.el @@ -106,5 +106,38 @@ reversing the sort." :generator (lambda (n) (concat (sort-tests-random-word n) " " (sort-tests-random-word n))) :less-pred (lambda (a b) (string< (field-n a 2) (field-n b 2)))))) +(defun test-with-buffer-unmodified-if-unchanged () + (with-temp-buffer + (with-buffer-unmodified-if-unchanged + (insert "t")) + (should (buffer-modified-p))) + + (with-temp-buffer + (with-buffer-unmodified-if-unchanged + (insert "t") + (delete-char -1)) + (should (not (buffer-modified-p)))) + + ;; Shouldn't error. + (should + (with-temp-buffer + (let ((inner (current-buffer))) + (with-buffer-unmodified-if-unchanged + (insert "t") + (delete-char -1) + (kill-buffer (current-buffer)) + t)))) + + (with-temp-buffer + (let ((outer (current-buffer))) + (with-temp-buffer + (let ((inner (current-buffer))) + (with-buffer-unmodified-if-unchanged + (insert "t") + (delete-char -1) + (set-buffer outer)) + (with-current-buffer inner + (should (not (buffer-modified-p))))))))) + (provide 'sort-tests) ;;; sort-tests.el ends here -- 2.39.2