3

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.

2 Answers 2

3

This can be achieved using an autocmd:

autocmd BufWritePost *.py !black %

It will run the your command after a file with the extension .py has been written to file. For more information see :h autocmd.

Sign up to request clarification or add additional context in comments.

Comments

1

"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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.