Call apheleia-format-buffer normally when there's no region

This commit is contained in:
Jeremy Dormitzer 2024-08-29 13:25:24 -04:00
parent d5030f749f
commit 47727d73f9

View File

@ -291,47 +291,44 @@
(defun apheleia ()
"Format the region or current buffer using Apheleia."
(interactive)
(let* ((buf (current-buffer))
(name (buffer-file-name))
(temp-file (make-temp-file "apheleia" nil (format ".%s" (file-name-extension name))))
(temp-buffer (find-file-noselect temp-file))
(formatters (apheleia--get-formatters))
(line (line-number-at-pos))
(col (current-column))
start
end)
(if (region-active-p)
(setq start (region-beginning)
end (region-end))
(setq start (point-min)
end (point-max)))
(with-current-buffer temp-buffer
(erase-buffer)
(insert-buffer-substring buf start end)
(write-file temp-file)
(apheleia-format-buffer formatters
(lambda ()
(with-current-buffer buf
(delete-region start end)
(insert (with-current-buffer temp-buffer
(string-trim
(buffer-substring-no-properties (point-min) (point-max)))))
(goto-char (point-min))
(forward-line (1- line))
(move-to-column col)
(delete-file temp-file)
(when (get-buffer temp-buffer)
(with-current-buffer temp-buffer
(set-buffer-modified-p nil))
(kill-buffer temp-buffer))))
:callback (lambda (&rest args)
(when-let ((error (plist-get args :error)))
(delete-file temp-file)
(when (get-buffer temp-buffer)
(with-current-buffer temp-buffer
(set-buffer-modified-p nil))
(kill-buffer temp-buffer))
(error "Formatting failed: %s" error)))))))
(if (not (region-active-p))
(call-interactively #'apheleia-format-buffer)
(let* ((buf (current-buffer))
(name (buffer-file-name))
(temp-file (make-temp-file "apheleia" nil (format ".%s" (file-name-extension name))))
(temp-buffer (find-file-noselect temp-file))
(formatters (apheleia--get-formatters))
(line (line-number-at-pos))
(col (current-column))
(start (region-beginning))
(end (region-end)))
(with-current-buffer temp-buffer
(erase-buffer)
(insert-buffer-substring buf start end)
(write-file temp-file)
(apheleia-format-buffer formatters
(lambda ()
(with-current-buffer buf
(delete-region start end)
(insert (with-current-buffer temp-buffer
(buffer-substring-no-properties (point-min) (point-max))))
(goto-char (point-min))
(forward-line (1- line))
(move-to-column col)
(delete-file temp-file)
(when (get-buffer temp-buffer)
(with-current-buffer temp-buffer
(set-buffer-modified-p nil))
(kill-buffer temp-buffer))))
:callback (lambda (&rest args)
(when-let ((error (plist-get args :error)))
(delete-file temp-file)
(when (get-buffer temp-buffer)
(with-current-buffer temp-buffer
(set-buffer-modified-p nil))
(kill-buffer temp-buffer))
(error "Formatting failed: %s" error)))))))
)
(keymap-set prog-mode-map "C-c f" #'apheleia)