Silently format buffer

I run an autocmd to format before saving (see below) but when I am in none lsp supported files I get notifications that no formatter is available (using nvim-notify). Is there a way to not make this notification appear?

vim.api.nvim_create_autocmd("BufWritePre", {
    callback = function()
        vim.lsp.buf.format()
    end,
})

You can use the pattern field to specify a list of file extensions that you want your autocmd to apply to.

vim.api.nvim_create_autocmd("BufWritePre", {
  pattern = {"*.py", "*.c"},
  callback = function()
    vim.lsp.buf.format()
  end,
})

Thanks for your answer! I do all my formatting with null-ls so I found this solution:

vim.api.nvim_create_autocmd("BufWritePre", {
	callback = function()
		-- check if null-ls exists
		local check, nullls = pcall(require, "null-ls")
		-- check if a formatting source of null-ls is registered
		if check and nullls.is_registered({ method = nullls.methods.FORMATTING }) then
			vim.lsp.buf.format()
		else
			vim.cmd([[normal gg=G<C-o>]])
		end
	end,
})

Even works if null-ls is being lazyloaded (pcall)

edit: This code actually doesn’t work :(, see more info here How to properly use the `is_registered()` function · Discussion #1309 · jose-elias-alvarez/null-ls.nvim · GitHub

2 Likes