How do I auto-format code on save using conform.nvim?
Answer
:lua require('conform').format()
Explanation
conform.nvim is a lightweight formatter plugin for Neovim that runs external formatters (prettier, black, gofmt, etc.) with proper error handling and fallback chains. It integrates seamlessly with format-on-save workflows.
How it works
require('conform').format()— format the current buffer- Formatters are configured per filetype
- Multiple formatters can be chained (run sequentially)
- Fallback formatters run only if primary ones aren't available
Example
require('conform').setup({
formatters_by_ft = {
python = { 'black' },
javascript = { 'prettier' },
go = { 'gofmt', 'goimports' },
lua = { 'stylua' },
},
format_on_save = {
timeout_ms = 500,
lsp_fallback = true,
},
})
Workflow:
1. Edit Python file
2. Save with :w
3. black runs automatically
4. Buffer is reformatted in-place
Tips
lsp_fallback = trueuses LSP formatting when no formatter is configured- Use
format_after_savefor async formatting that doesn't block the UI :ConformInfoshows which formatters are available for the current bufferstop_after_first = trueruns only the first available formatter in the list