What should I put in my init.vim to run the following command every time I save a Python file?
:!black %
Obviously this should only run if file type is .py.
"Automatic exeuction" in Vim/Neovim is related to the concept of auto-commands. TJ DeVries (the author of Lua Autocmds in Neovim) has some great videos on his YouTube channel, specifically the Autocmd Intro, Autocmd Groups and Autocmd Patterns videos.
For a Neovim/Lua version of the auto-command that does what you are wanting to do (and ensuring that one properly assigns the auto-command to an auto-command group to prevent it from being loaded repeatedly every time a file is re-sourced):
local autocmd_group = vim.api.nvim_create_augroup(
"Custom auto-commands",
{clear = true})
vim.api.nvim_create_autocmd({"BufWritePost"},
{
pattern = {"*.py"},
desc = "Auto-format Python files after saving",
callback = function()
local file_name = vim.api.nvim_buf_get_name(0) -- Get file name of file in current buffer
vim.cmd(":!black --preview -q " .. file_name)
-- vim.cmd(":!isort --profile black --float-to-top -q " .. file_name)
-- vim.cmd(":!docformatter --in-place --black " .. file_name)
end,
group = autocmd_group,
})
I'd recommend installing isort and docformatter as well. You can then uncomment the two lines above so that imports and docstrings are formatted and organised consistently.