til / Biome v2 formatting and linting in Neovim
With Biome v1 and Neovim 0.10 I used conform.nvim to run formatting on files and everything worked smoothly. In Biome 2, they’ve changed how stdin, which conform.nvim uses, works (or it has bugs). That, together with Biome’s new monorepo support, and the new LSP in Neovim 0.11 made the old setup not work anymore.
I found that I could use Biome’s LSP directly for formatting instead. This was probably possible before too, but I didn’t bother to look since everything worked.
Using the LSP works great for formatting out-of-the-box, but it doesn’t take care of fixing linter errors automatically. For this, we can add a code action that runs of save.1
-- The configuration assumes that you've installed and
-- enabled the Biome LSP.
-- Whenever an LSP attaches
vim.api.nvim_create_autocmd("LspAttach", {
callback = function(args)
local client = vim.lsp.get_client_by_id(args.data.client_id)
if not client then
return
end
-- When the client is Biome, add an automatic event on
-- save that runs Biome's "source.fixAll.biome" code action.
-- This takes care of things like JSX props sorting and
-- removing unused imports.
if client.name == "biome" then
vim.api.nvim_create_autocmd("BufWritePre", {
group = vim.api.nvim_create_augroup("BiomeFixAll", { clear = true }),
callback = function()
vim.lsp.buf.code_action({
context = {
only = { "source.fixAll.biome" },
diagnostics = {},
},
apply = true,
})
end,
})
end
end,
})
Biome 2 also changed the noUnusedImports rule fix to be “unsafe”.2 To keep using the old behavior, you can mark it as safe.
// biome.json
{
"linter": {
"rules": {
"correctness": {
"noUnusedImports": {
"level": "error",
"fix": "safe"
}
}
}
}
}