|
7 | 7 | ;;; Commentary:
|
8 | 8 |
|
9 | 9 | ;;; Code:
|
10 |
| -(require 'reformatter) |
11 | 10 |
|
12 | 11 | (defcustom nix-nixfmt-bin "nixfmt"
|
13 | 12 | "Path to nixfmt executable."
|
14 | 13 | :group 'nix
|
15 | 14 | :type 'string)
|
16 | 15 |
|
17 |
| -;;;###autoload (autoload 'nixfmt-buffer "nix-format") |
18 |
| -;;;###autoload (autoload 'nixfmt-region "nix-format") |
19 |
| -;;;###autoload (autoload 'nixfmt-on-save-mode "nix-format") |
20 |
| -(reformatter-define nixfmt |
21 |
| - :program nix-nixfmt-bin |
22 |
| - :args (list input-file) |
23 |
| - :stdin nil |
24 |
| - :stdout nil |
25 |
| - :input-file (reformatter-temp-file-in-current-directory) |
26 |
| - :group 'nix) |
| 16 | +(if (fboundp 'replace-buffer-contents) |
| 17 | + (defun nix--replace-buffer-contents (src dst) |
| 18 | + (with-current-buffer dst (replace-buffer-contents src))) |
| 19 | + (defun nix--replace-buffer-contents (src dst) |
| 20 | + (if (not (string= (with-current-buffer src (buffer-string)) |
| 21 | + (with-current-buffer dst (buffer-string)))) |
| 22 | + (with-current-buffer src |
| 23 | + (copy-to-buffer dst (point-min) (point-max)))))) |
| 24 | + |
| 25 | +(defun nix--format-call (buf nixfmt-bin) |
| 26 | + "Format BUF using nixfmt." |
| 27 | + (with-current-buffer (get-buffer-create "*nixfmt*") |
| 28 | + (erase-buffer) |
| 29 | + (insert-buffer-substring buf) |
| 30 | + (if (zerop (call-process-region (point-min) (point-max) nixfmt-bin t t nil)) |
| 31 | + (nix--replace-buffer-contents (current-buffer) buf) |
| 32 | + (error "Nixfmt failed, see *nixfmt* buffer for details")))) |
| 33 | + |
| 34 | +(defun nix--find-nixfmt () |
| 35 | + "Find the nixfmt binary, or error if it's missing." |
| 36 | + (let ((nixfmt-bin (executable-find nix-nixfmt-bin))) |
| 37 | + (unless nixfmt-bin |
| 38 | + (error "Could not locate executable %S" nix-nixfmt-bin)) |
| 39 | + nixfmt-bin)) |
| 40 | + |
| 41 | +(defun nix-format-buffer () |
| 42 | + "Format the current buffer using nixfmt." |
| 43 | + (interactive) |
| 44 | + (nix--format-call (current-buffer) (nix--find-nixfmt)) |
| 45 | + (message "Formatted buffer with nixfmt.")) |
| 46 | + |
| 47 | +;;;###autoload |
| 48 | +(defun nix-format-before-save () |
| 49 | + "Add this to `before-save-hook' to run nixfmt when saving." |
| 50 | + (when (derived-mode-p 'nix-mode) |
| 51 | + (nix-format-buffer))) |
27 | 52 |
|
28 | 53 | (provide 'nix-format)
|
29 | 54 | ;;; nix-format.el ends here
|
0 commit comments