Neovim format-on-save nix intergration

Hey I just revisited this plugin and I wanted to see if I could get it to work with any nix formater, nixfmt is just the one I’m trying to use.

I noticed my nil LSP just started working, so something must be happening in the nix world. Here’s the issue with the config.

2 Likes

For people using null-ns, this is a similar config but using treefmt rather than nixfmt directly:

local augroup = vim.api.nvim_create_augroup("LspFormatting", {})
local null_ls = require("null-ls")

null_ls.setup({
  sources = {
    null_ls.builtins.code_actions.statix,
    null_ls.builtins.diagnostics.statix,
    null_ls.builtins.diagnostics.deadnix,
    null_ls.builtins.formatting.treefmt.with({
      condition = function(utils)
        return utils.root_has_file("treefmt.toml") or utils.root_has_file(".treefmt.toml")
      end,
      extra_args = function()
        local client = require("null-ls.client").get_client()
        return { "--tree-root", client.config.root_dir }
      end,
    }),
  },
  -- you can reuse a shared lspconfig on_attach callback here
  on_attach = function(client, bufnr)
      if client.supports_method("textDocument/formatting") then
          vim.api.nvim_clear_autocmds({ group = augroup, buffer = bufnr })
          vim.api.nvim_create_autocmd("BufWritePre", {
              group = augroup,
              buffer = bufnr,
              callback = function()
                  vim.lsp.buf.format({ async = false })
              end,
          })
      end
  end,
})
3 Likes

I’m using conform.nvim and it works nicely for everything I use.

Minimal Config
require("conform").setup({
  --  for users who want auto-save conform + lazyloading!
  event = 'BufWritePre',
  format_on_save = {
    -- These options will be passed to conform.format()
    timeout_ms = 500,
    lsp_fallback = true,
  },
  formatters_by_ft = {
    lua = { 'stylua' },

    nix = { 'nixpkgs_fmt' },

    -- Fix common misspellings in source code on all filetypes
    ['*'] = { 'codespell' },
  },
})

You can also add autocmds to enable/disable format-on-save per buffer.

2 Likes