Jack's blog

Neovim autofix ruff errors on save

I was aware this was possible from my experience trying out other editors. Organising imports is something really tedious I hate having to explicitly trigger a code action for.

Today I finally figured out how to configure this in Neovim.

local lspconfig = require('lspconfig')
lspconfig.ruff.setup{}

vim.api.nvim_create_autocmd("BufWritePre", {
  pattern = "*.py",
  callback = function()
    vim.lsp.buf.code_action({
      context = {
        only = {
          "source.fixAll.ruff"
        },
      },
      apply = true,
    })
    vim.lsp.buf.format({ async = false })
  end,
})