Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically format on save

Tags:

neovim

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.

like image 806
Dave Mulford Avatar asked Oct 11 '25 16:10

Dave Mulford


1 Answers

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.

like image 60
Dave Mulford Avatar answered Oct 16 '25 05:10

Dave Mulford