Add auto-formatting for d2.

This commit is contained in:
Tom Alexander
2026-04-02 14:04:04 -04:00
parent e2658412ab
commit 620c12eaa7
3 changed files with 28 additions and 2 deletions

View File

@@ -27,6 +27,29 @@
)
)
(defun run-command-on-buffer-require-output (cmd &rest args)
"Run a command using the current buffer as stdin and replacing its contents if the command succeeds with the stdout from the command. This is useful for code formatters. This version only replaces the buffer contents if the command output some text."
(let (
(stdout-buffer (generate-new-buffer "tmp-stdout" t))
(full-cmd (append '(call-process-region nil nil cmd nil stdout-buffer nil) args))
)
(unwind-protect
(let ((exit-status (eval full-cmd)))
(if (eq exit-status 0)
(if (> (buffer-size stdout-buffer) 0)
(save-excursion
(replace-buffer-contents stdout-buffer)
)
(message "No output from command on buffer %s" (append (list cmd) args))
)
(message "FAILED running command on buffer %s" (append (list cmd) args))
)
)
(kill-buffer stdout-buffer)
)
)
)
(defun run-command-in-directory (dir cmd &rest args)
"Run a command in the specified directory. If the directory is nil, the directory of the file is used. The stdout result is trimmed of whitespace and returned."
(let (

View File

@@ -1,14 +1,14 @@
(defun d2-format-buffer ()
"Run prettier."
(interactive)
(run-command-on-buffer "d2" "fmt" "-")
(run-command-on-buffer-require-output "d2" "fmt" "-")
)
(use-package d2-mode
:commands (d2-mode)
:hook (
(d2-mode . (lambda ()
;; (add-hook 'before-save-hook 'd2-format-buffer nil 'local)
(add-hook 'before-save-hook 'd2-format-buffer nil 'local)
))
)
)