Automagically formatting on save, with Neovim and Language Server Protocol (LSP)

Featured image for sharing metadata for article

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.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #neovim.

Also on:

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.