From db65a54feb637932b8417600b5ef4a04118b6e31 Mon Sep 17 00:00:00 2001 From: Josh Kingsley Date: Fri, 21 Mar 2025 13:03:20 +0200 Subject: [PATCH] nix-format: support remote buffers Two changes need to be made to support Tramp remote buffers: 1. Pass the second REMOTE arg to `executable-find` to find the executable on the remote host 2. Avoid using `call-process-region`, which doesn't have a Tramp equivalent This change replaces `call-process-region` with `process-file` which supports executing via Tramp. This function requires writing the buffer contents to a temporary file first. Although writing the buffer to a file may have perfomance implications vs. writing from memory to stdin, they are likely to be negligibile. Furthermore, this approach is similar to other formatting libraries like prettier.el: https://github.com/jscheid/prettier.el/blob/master/prettier.el#L1494 I've also found it to be more reliable than `process-send-string`. --- nix-format.el | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/nix-format.el b/nix-format.el index db58002..8e6649b 100644 --- a/nix-format.el +++ b/nix-format.el @@ -16,23 +16,28 @@ (defun nix--replace-buffer-contents (src dst) (if (fboundp 'replace-buffer-contents) (with-current-buffer dst (replace-buffer-contents src)) - (unless (string= (with-current-buffer src (buffer-string)) - (with-current-buffer dst (buffer-string))) + (unless (string= (with-current-buffer src (buffer-string)) + (with-current-buffer dst (buffer-string))) (with-current-buffer src - (copy-to-buffer dst (point-min) (point-max)))))) + (copy-to-buffer dst (point-min) (point-max)))))) (defun nix--format-call (buf nixfmt-bin) - "Format BUF using nixfmt." - (with-current-buffer (get-buffer-create "*nixfmt*") - (erase-buffer) - (insert-buffer-substring buf) - (if (zerop (call-process-region (point-min) (point-max) nixfmt-bin t t nil)) - (nix--replace-buffer-contents (current-buffer) buf) - (error "Nixfmt failed, see *nixfmt* buffer for details")))) + "Format BUF using program NIXFMT-BIN." + (let ((temp-file (make-nearby-temp-file "nixfmt"))) + (unwind-protect + (let ((out-buf (get-buffer-create "*nixfmt*"))) + (with-current-buffer out-buf + (erase-buffer)) + (with-current-buffer buf + (write-region (point-min) (point-max) temp-file nil 'no-visit nil nil)) + (if (zerop (process-file nixfmt-bin temp-file out-buf)) + (nix--replace-buffer-contents out-buf buf) + (error "Nixfmt failed, see *nixfmt* buffer for details"))) + (delete-file temp-file)))) (defun nix--find-nixfmt () "Find the nixfmt binary, or error if it's missing." - (let ((nixfmt-bin (executable-find nix-nixfmt-bin))) + (let ((nixfmt-bin (executable-find nix-nixfmt-bin t))) (unless nixfmt-bin (error "Could not locate executable %S" nix-nixfmt-bin)) nixfmt-bin))