From 866b4309f291a1fdbafb09d8e43b12aca426242b Mon Sep 17 00:00:00 2001 From: Stefan Monnier Date: Wed, 12 Jun 2024 18:27:15 -0400 Subject: [PATCH] lisp/editorconfig: Don't hook into `read-only-mode-hook` Don't re-set variables just because `read-only-mode` is (de)activated, and with Emacs-30's hooks it would be even less natural to do. Also `buffer-read-only` can change without calling `read-only-mode`, so better test it dynamically when we try to trim whitespace. * lisp/editorconfig.el (editorconfig--delete-trailing-whitespace): New function. (editorconfig-set-trailing-ws): Use it. Use `pcase`. Also prefer `before-save-hook` and use `add/remove-hook` to manipulate hooks, like god intended. Don't test `buffer-read-only` any more. (editorconfig-mode): Don't hook into `read-only-mode-hook` any more. (cherry picked from commit 527a45abc37f1885652b0f29ed5eeabff6db6cda) --- lisp/editorconfig.el | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/lisp/editorconfig.el b/lisp/editorconfig.el index b8eced27807..a0bd0ae3e74 100644 --- a/lisp/editorconfig.el +++ b/lisp/editorconfig.el @@ -349,13 +349,22 @@ to non-nil when FINAL-NEWLINE is true." ("false" ))) +(defun editorconfig--delete-trailing-whitespace () + "Call `delete-trailing-whitespace' unless the buffer is read-only." + (unless buffer-read-only (delete-trailing-whitespace))) + (defun editorconfig-set-trailing-ws (trim-trailing-ws) - (if editorconfig-trim-whitespaces-mode - (funcall editorconfig-trim-whitespaces-mode 1) - ...) - (when editorconfig-trim-whitespaces-mode - (funcall editorconfig-trim-whitespaces-mode 0)) - ...) + (pcase trim-trailing-ws + ("true" + (if editorconfig-trim-whitespaces-mode + (funcall editorconfig-trim-whitespaces-mode 1) + (add-hook 'before-save-hook + #'editorconfig--delete-trailing-whitespace nil t))) + ("false" + (when editorconfig-trim-whitespaces-mode + (funcall editorconfig-trim-whitespaces-mode 0)) + (remove-hook 'before-save-hook + #'editorconfig--delete-trailing-whitespace t)))) (defun editorconfig-set-line-length (length) "Set the max line length (`fill-column') to LENGTH." @@ -521,7 +530,6 @@ F is that function, and FILENAME and ARGS are arguments passed to F." :global t (let ((modehooks '(prog-mode-hook text-mode-hook - read-only-mode-hook ;; Some modes call `kill-all-local-variables' in their init ;; code, which clears some values set by editorconfig. ;; For those modes, editorconfig-apply need to be called -- 2.39.2