]> git.eshelyaron.com Git - emacs.git/commitdiff
lisp/editorconfig: Don't hook into `read-only-mode-hook`
authorStefan Monnier <monnier@iro.umontreal.ca>
Wed, 12 Jun 2024 22:27:15 +0000 (18:27 -0400)
committerEshel Yaron <me@eshelyaron.com>
Fri, 21 Jun 2024 19:00:03 +0000 (21:00 +0200)
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

index b8eced278074189160f5f125fb930da31ba44c66..a0bd0ae3e749b57cad45a71cc98c8138ab7832c4 100644 (file)
@@ -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