Automagically formatting on save, with Neovim and Language Server Protocol (LSP)
Moving to Neovim, one of the really key benefits of the move was the native Language Server Protocol (LSP) support.
After being quite used to the way that I could get my Java projects to autoformat on build, I did, however, want a little more from Neovim's configuration.
The Neovim docs actually highlight this:
autocmd BufWritePre <buffer> lua vim.lsp.buf.format()
" or
autocmd BufWritePre * lua vim.lsp.buf.format()
Or if you're using the Lua configuration:
vim.cmd [[autocmd BufWritePre <buffer> lua vim.lsp.buf.format()]]
-- or
vim.cmd [[autocmd BufWritePre * lua vim.lsp.buf.format()]]
Or if you want to write Lua, but haven't yet fully migrated to a Lua-only configuration, you'll want the following:
lua <<EOF
vim.cmd [[autocmd BufWritePre * lua vim.lsp.buf.format()]]
EOF
Then, every time you save your file(s), they'll attempt to format using the registered LSP, and if none exist, it'll be a no-op.