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