summary refs log tree commit diff stats
path: root/lisp/+apheleia.el
blob: 51cf1454fa54622de8c905502a0ce1f534c2b33c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
;;; +apheleia.el -*- lexical-binding: t; -*-

;;; Code:

(require 'cl-lib)
(require 'el-patch)
(require 'user-save)

;; https://github.com/raxod502/apheleia/pull/63#issue-1077529623
(cl-defun +apheleia-indent-region (&key buffer scratch formatter callback &allow-other-keys)
  (with-current-buffer scratch
    (setq-local indent-line-function
                (buffer-local-value 'indent-line-function buffer))
    (indent-region (point-min)
                   (point-max))
    (funcall callback)))

;;; Why does the original function have to check for `apheleia-mode' ?
(el-patch-defun apheleia--format-after-save ()
  "Run code formatter for current buffer if any configured, then save."
  (unless apheleia--format-after-save-in-progress
    (when (el-patch-swap apheleia-mode
                         (or apheleia-mode
                             +apheleia/user-save-mode))
      (when-let ((formatters (apheleia--get-formatters)))
        (apheleia-format-buffer
         formatters
         (lambda ()
           (with-demoted-errors "Apheleia: %s"
             (when buffer-file-name
               (let ((apheleia--format-after-save-in-progress t))
                 (apheleia--save-buffer-silently)))
             (run-hooks 'apheleia-post-format-hook))))))))


(define-minor-mode +apheleia/user-save-mode
  "Minor mode for reformatting code on `user-save'.
Customize with `apheleia-mode-alist' and `apheleia-formatters'."
  :lighter " Apheleia/US"
  (if +apheleia/user-save-mode
      (add-hook 'user-save-after-save-hook #'apheleia--format-after-save nil 'local)
    (remove-hook 'user-save-after-save-hook #'apheleia--format-after-save 'local)))

(define-globalized-minor-mode +apheleia/user-save-global-mode
  +apheleia/user-save-mode  +apheleia/user-save-mode)

(put '+apheleia/user-save-mode 'safe-local-variable #'booleanp)

(provide '+apheleia)
;;; +apheleia.el ends here