-
Notifications
You must be signed in to change notification settings - Fork 82
/
apheleia.el
298 lines (265 loc) · 12.1 KB
/
apheleia.el
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
;;; apheleia.el --- Reformat buffer stably -*- lexical-binding: t -*-
;; Copyright (C) 2019-2022 Radian LLC and contributors
;; Author: Radian LLC <[email protected]>
;; Created: 7 Jul 2019
;; Homepage: https://github.com/radian-software/apheleia
;; Keywords: tools
;; Package-Requires: ((emacs "27"))
;; SPDX-License-Identifier: MIT
;; Version: 4.3
;;; Commentary:
;; Apheleia is an Emacs Lisp package which allows you to reformat a
;; buffer without moving point. This solves the usual problem of
;; running a tool like Prettier or Black on `before-save-hook', namely
;; that it resets point to the beginning of the buffer. Apheleia
;; maintains the position of point relative to its surrounding text
;; even if the buffer is modified by the reformatting.
;; Please see https://github.com/radian-software/apheleia for more information.
;;; Code:
(require 'apheleia-formatters)
(require 'apheleia-log)
(require 'apheleia-rcs)
(defgroup apheleia nil
"Reformat buffer without moving point."
:group 'external
:link '(url-link :tag "GitHub" "https://github.com/radian-software/apheleia")
:link '(emacs-commentary-link :tag "Commentary" "apheleia"))
(defcustom apheleia-mode-lighter " Apheleia"
"Lighter for `apheleia-mode'."
:type '(choice :tag "Lighter" (const :tag "No lighter" nil) string)
:risky t
:group 'apheleia)
(defun apheleia--buffer-hash ()
"Compute hash of current buffer."
(if (fboundp 'buffer-hash)
(buffer-hash)
(md5 (current-buffer))))
(defcustom apheleia-skip-functions nil
"List of functions that prevent Apheleia from running when enabled.
These are invoked every time Apheleia wants to format a buffer,
and the formatting operation is skipped if any of them return
non-nil. See also `apheleia-inhibit-functions' for functions that
prevent `apheleia-mode' from being turned on in the first place."
:type '(repeat function)
:group 'apheleia)
(defun apheleia--disallowed-p ()
"Return an error message if Apheleia cannot be run, else nil."
(cond
((and buffer-file-name
(file-remote-p (or buffer-file-name
default-directory))
(eq apheleia-remote-algorithm 'cancel))
"Apheleia refused to run formatter due to `apheleia-remote-algorithm'")
((run-hook-with-args-until-success
'apheleia-skip-functions)
"Apheleia skipped running formatter due to `apheleia-skip-functions'")))
(defmacro apheleia--with-on-error (on-error &rest body)
"Call ON-ERROR with an error if BODY throws an error.
Return the error in that case, instead of throwing it. If
ON-ERROR is nil, instead act just like `progn'."
(declare (indent 1))
(let ((err-sym (make-symbol "err"))
(on-error-sym (make-symbol "on-error")))
`(let ((,on-error-sym ,on-error))
(if ,on-error-sym
(condition-case-unless-debug ,err-sym
(progn ,@body)
(error (funcall ,on-error-sym ,err-sym)))
(progn ,@body)))))
;;;###autoload
(cl-defun apheleia-format-buffer
(formatter &optional success-callback &key callback)
"Run code formatter asynchronously on current buffer, preserving point.
FORMATTER is a symbol appearing as a key in
`apheleia-formatters', or a list of them to run multiple
formatters in a chain. If called interactively, run the currently
configured formatters (see `apheleia-formatter' and
`apheleia-mode-alist'), or prompt from `apheleia-formatters' if
there is none configured for the current buffer. With a prefix
argument, prompt always.
After the formatters finish running, the diff utility is invoked to
determine what changes it made. That diff is then used to apply the
formatter's changes to the current buffer without moving point or
changing the scroll position in any window displaying the buffer. If
the buffer has been modified since the formatter started running,
however, the operation is aborted.
If the formatter actually finishes running and the buffer is
successfully updated (even if the formatter has not made any
changes), SUCCESS-CALLBACK, if provided, is invoked with no
arguments.
If provided, CALLBACK is invoked unconditionally (unless there is
a synchronous nonlocal exit) with a plist. Callback function must
accept unknown keywords. At present only `:error' is included,
this is either an error or nil."
(interactive (progn
(when-let ((err (apheleia--disallowed-p)))
(user-error err))
(list (apheleia--get-formatters
(if current-prefix-arg
'prompt
'interactive)))))
(let ((callback
(lambda (err)
(unless (listp err)
(setq err (cons 'error err)))
(unless err
(when success-callback
(funcall success-callback)))
(when callback
(funcall callback :error err)))))
(apheleia--log
'format-buffer
"Invoking apheleia-format-buffer on %S with formatter %S"
(current-buffer)
formatter)
(let ((formatters (apheleia--ensure-list formatter)))
;; Check for this error ahead of time so we don't have to deal
;; with it anywhere in the internal machinery of Apheleia.
(dolist (formatter formatters)
(unless (alist-get formatter apheleia-formatters)
(user-error
"No such formatter defined in `apheleia-formatters': %S"
formatter)))
;; Fail silently if disallowed, since we don't want to throw an
;; error on `post-command-hook'. We already took care of throwing
;; `user-error' on interactive usage above.
(if-let ((err (apheleia--disallowed-p)))
(progn
(apheleia--log
'format-buffer
"Aborting in %S due to apheleia--disallowed-p: %s"
(buffer-name (current-buffer))
err)
(when callback
(funcall callback err)))
;; It's important to store the saved buffer hash in a lexical
;; variable rather than a dynamic (global) one, else multiple
;; concurrent invocations of `apheleia-format-buffer' can
;; overwrite each other, and get the wrong results about whether
;; the buffer was actually modified since the formatting
;; operation started, leading to data loss.
;;
;; https://github.com/radian-software/apheleia/issues/226
(let ((saved-buffer-hash (apheleia--buffer-hash)))
(let ((cur-buffer (current-buffer))
(remote (file-remote-p (or buffer-file-name
default-directory))))
(apheleia--run-formatters
formatters
cur-buffer
remote
(lambda (err formatted-buffer)
(if err
(funcall callback err)
(apheleia--with-on-error callback
(if (not (buffer-live-p cur-buffer))
(progn
(apheleia--log
'format-buffer
"Aborting in %S because buffer has died"
(buffer-name cur-buffer))
(funcall callback "Buffer has died"))
(with-current-buffer cur-buffer
;; Short-circuit.
(if (not (equal
saved-buffer-hash (apheleia--buffer-hash)))
(progn
(apheleia--log
'format-buffer
"Aborting in %S because contents have changed"
(buffer-name cur-buffer))
(funcall callback "Contents have changed"))
(apheleia--create-rcs-patch
cur-buffer formatted-buffer remote
(lambda (err patch-buffer)
(if err
(funcall callback err)
(apheleia--with-on-error callback
(when (buffer-live-p cur-buffer)
(with-current-buffer cur-buffer
(if (not (equal
saved-buffer-hash
(apheleia--buffer-hash)))
(progn
(apheleia--log
'format-buffer
(concat
"Aborting in %S because "
"contents have changed")
(buffer-name cur-buffer))
(funcall
callback "Contents have changed"))
(apheleia--apply-rcs-patch
(current-buffer) patch-buffer)
(funcall
callback nil)))))))))))))))))))))
(defcustom apheleia-post-format-hook nil
"Normal hook run after Apheleia formats a buffer successfully."
:type 'hook
:group 'apheleia)
(defcustom apheleia-inhibit-functions nil
"List of functions that prevent Apheleia from turning on automatically.
If one of these returns non-nil then `apheleia-mode' is not
enabled in a buffer, even if `apheleia-global-mode' is on. You
can still manually enable `apheleia-mode' in such a buffer.
See also `apheleia-inhibit' for another way to accomplish a
similar task. See also `apheleia-skip-functions' for functions
that prevent Apheleia from running even when the mode is enabled."
:type '(repeat function)
:group 'apheleia)
;; Handle recursive references.
(defvar apheleia-mode)
;; Prevent infinite loop.
(defvar apheleia-format-after-save-in-progress nil
"Prevent `apheleia-format-after-save' from being called recursively.
This will be locally bound to t while `apheleia-format-after-save' is
operating, to prevent an infinite loop.")
;; Autoload because the user may enable `apheleia-mode' without
;; loading Apheleia; thus this function may be invoked as an autoload.
;;;###autoload
(defun apheleia-format-after-save ()
"Run code formatter for current buffer if any configured, then save."
(unless apheleia-format-after-save-in-progress
(when (and apheleia-mode (not (buffer-narrowed-p)))
(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))))))))
;; Use `progn' to force the entire minor mode definition to be copied
;; into the autoloads file, so that the minor mode can be enabled
;; without pulling in all of Apheleia during init.
;;;###autoload
(progn
(define-minor-mode apheleia-mode
"Minor mode for reformatting code on save without moving point.
It is customized by means of the variables `apheleia-mode-alist'
and `apheleia-formatters'."
:lighter apheleia-mode-lighter
(if apheleia-mode
(add-hook 'after-save-hook #'apheleia-format-after-save nil 'local)
(remove-hook 'after-save-hook #'apheleia-format-after-save 'local)))
(defvar-local apheleia-inhibit nil
"Do not enable `apheleia-mode' automatically if non-nil.
This is designed for use in .dir-locals.el.
See also `apheleia-inhibit-functions'.")
(put 'apheleia-inhibit 'safe-local-variable #'booleanp)
(defun apheleia-mode-maybe ()
"Enable `apheleia-mode' if allowed by user configuration.
This checks `apheleia-inhibit-functions' and `apheleia-inhibit'
to see if it is allowed."
(unless (or
apheleia-inhibit
(run-hook-with-args-until-success
'apheleia-inhibit-functions))
(apheleia-mode)))
(define-globalized-minor-mode apheleia-global-mode
apheleia-mode apheleia-mode-maybe
:group 'apheleia)
(put 'apheleia-mode 'safe-local-variable #'booleanp))
(provide 'apheleia)
;;; apheleia.el ends here