I'm trying to setup auto-format on save with neovim. I do not want to use an lsp plugin to do this.
The example below is my attempt at calling the black formatter for python files.
vim.api.nvim_create_augroup("AutoFormat", {})
vim.api.nvim_create_autocmd(
"BufWritePre",
{
pattern = "*.py",
group = "AutoFormat",
callback = function()
vim.cmd("!black --quiet %")
-- vim.cmd("write!")
end,
}
)
The callback function runs as expected, but the code isn't formatted. Here is what I see in the nvim output area.
:!black --quiet test.py
"test.py" 5L, 86B written
Press ENTER or type command to continue
I've also tried adding the extra vim.cmd("write!")
which is commented in the example above because it seemed to have no affect.
When I manually the command with !black --quiet %
the buffer is formatted, so I think I have the correct command.
What I'd like to have happen is I write to the file with :w
, the code is formatted and saved. Is this possible?
Note: I plan on adding other languages (Go, Rust, SQL), so I plan to add more autocmds to the script.
Spent some more time on this and figured out how to get the functionality I want.
vim.api.nvim_create_augroup("AutoFormat", {})
vim.api.nvim_create_autocmd(
"BufWritePost",
{
pattern = "*.py",
group = "AutoFormat",
callback = function()
vim.cmd("silent !black --quiet %")
vim.cmd("edit")
end,
}
)
Switching to BufWritePost
to make sure the file had been saved first, then allowing black to format the file and reloading with the :edit
command seems to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With