Nixfmt beta release

Hey everyone,

We just released v0.2 of nixfmt with important changes: We introduced atomic writes to make sure your code is not lost when nixfmt gets interrupted. We made sure nixfmt agrees with itself and won’t change the formatting of code that’s already formatted with it before. And last but not least: We improved the indentation algorithm by a lot.

We believe nixfmt is now pretty usable: There are still many corner cases that can be improved, but most of the formatting should now be clear and consistent. We want to invite you to start using nixfmt on your own code and report any issues. We’re also hoping to see some contributions soon.

To see what it looks like, you can try nixfmt in the browser or look at nixpkgs formatted with nixfmt or you can start using it with:

cachix use nixfmt # Recommended, to get a cached build
nix-env -i -f https://github.com/serokell/nixfmt/archive/v0.2.tar.gz
nixfmt some.nix files.nix

edit: Changed links to refer to v0.2 branch which tracks some minor patches.

20 Likes

This is great! Would you recommend that we pass through commits in the formatter before submitting a PR? And is this the “official” formatter?

nixfmt is not official yet, for that, it first needs to become somewhat popular and a little more polished. I don’t recommend formatting an entire file with it for a PR of a few lines, but I see no reason not to use it for new files or files that are mostly rewritten.

Is there already an emacs plugin?

I’m not aware of one, but it’s pretty easy to get started yourself:

(defvar peter-nix-format-on-save t
  "Format nix buffers on save")

(defun peter//run-command-on-file-in-place (cmd)
  "Run CMD on the current file and replace its contents"
  (call-process-shell-command
    (format "%s %s" cmd (buffer-file-name)) nil 0)
  (revert-buffer t t t))

(defun peter/maybe-format-nix-in-place ()
  "Run nixpkgs-fmt on the current file and replace its contents"
  (interactive)
  (when peter-nix-format-on-save
    (peter//run-command-on-file-in-place "nixpkgs-fmt")))
1 Like

And it works fine for most things in nixpkgs (just don’t let it loose on something like python-packages.nix).