Modern Format on Save in Neovim
Formatting on save is a popular workflow and is built into many text editors and IDEs.
In Neovim, you must create this manually, but it is very easy using autocmds.
-- 1
vim.api.nvim_create_autocmd("LspAttach", {
  group = vim.api.nvim_create_augroup("lsp", { clear = true }),
  callback = function(args)
    -- 2
    vim.api.nvim_create_autocmd("BufWritePre", {
      -- 3
      buffer = args.buf,
      callback = function()
        -- 4 + 5
        vim.lsp.buf.format {async = false, id = args.data.client_id }
      end,
    })
  end
})
- We create a new autocmdthat fires on theLspAttachevent. This event is fired when an LSP client attaches to a buffer. In thisautocmd, you can easily set configuration that is specific to that buffer and LSP client.
- We create another autcmdinside theLspAttachcallback, this time for theBufWritePreevent. This fires when you save the buffer but before it flushes anything to disk. This gives you a chance to manipulate the buffer first.
- We configure this autocmdto only execute for the current buffer. This is a little more straight forward rather than setting anautocmdthat executes for any range of file types.
- In the callback, we run vim.lsp.buf.formatto format the buffer, with the flagasync = false. This ensures that the formatting request will block until it completes, so that it completely finishes formatting before flushing the file to disk.
- We also set the id = args.data.clientflag so that the formatting request is only sent to the LSP client that is related to the outerLspAttachrequest. This ensures that we aren't running the formatting request multiple times in case the buffer is attached to multiple LSPs.
And there we have it, modern format on save for those who want it.