Neovim Autocmd to Call Lsp Formatting on Save

| posted in: neovim  nerdliness 


Recently I added this autocmd to my Neovim configuration, to format Go language code when the buffer was saved.

acmd({ "BufWritePre" },
     { pattern = "*.go",
       callback = function()
         vim.lsp.buf.format()
       end,
       group = _go})

The vim.lsp.buf.format() call executes the LSP provided formatter for buffer being written. By having it tied to Go language (.go) files I was missing out on formatting of other languages.

Today I moved that autocmd to the general section of my autocmd.lua file, and set the pattern to be *, so that it would work for all languages.

acmd({ "BufWritePre" },
  { pattern = "*",
    callback = function()
      vim.lsp.buf.format()
    end,
    group = _general })

Now when I save a buffer, whether it is Go program, or Rust, or even the Lua code in my Neovim configuration, it gets formatted.

Author's profile picture

Mark H. Nichols

I am a husband, cellist, code prole, nerd, technologist, and all around good guy living and working in fly-over country. You should follow me on Twitter.