From af5e7ab1e01d289e789edcf481aa96d03009616b Mon Sep 17 00:00:00 2001 From: Jeremy Dormitzer Date: Thu, 22 Aug 2024 11:13:57 -0400 Subject: [PATCH] Add custom `apheleia` function for formatting regions Implemented a custom `apheleia` function to format selected regions or entire buffer using Apheleia, handling temp files and regions. Updated keybinding for `C-c f` to use this new function. --- emacs/.emacs.d/config/init-ide.el | 50 +++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/emacs/.emacs.d/config/init-ide.el b/emacs/.emacs.d/config/init-ide.el index 794f94c..2d57446 100644 --- a/emacs/.emacs.d/config/init-ide.el +++ b/emacs/.emacs.d/config/init-ide.el @@ -282,10 +282,56 @@ ;; Code formatting library (use-package apheleia :straight (apheleia :host github :repo "raxod502/apheleia") + :commands apheleia-format-buffer + :autoload apheleia--get-formatters :config (add-to-list 'apheleia-mode-alist '(ruby-mode . (rubocop))) - :general - (prog-mode-map "C-c f" #'apheleia-format-buffer)) + (add-to-list 'apheleia-mode-alist '(ruby-ts-mode . (rubocop)))) + +(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-buffer-substring temp-buffer) + (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) ;; AI assistance (use-package copilot