lukas-reineke / lsp-format.nvim

A wrapper around Neovims native LSP formatting.
559 stars 27 forks source link

My BufWritePost/BufWritePre are being triggered twice #60

Closed alanoliveira closed 1 year ago

alanoliveira commented 1 year ago

One by my own save, and again after formatting save. Could you add a option to ignore these events on formatting save? Something like

https://github.com/lukas-reineke/lsp-format.nvim/blob/b611bd6cea82ccc127cf8fd781a1cb784b0d6d3c/lua/lsp-format/init.lua#L185-L187

vim.b.format_saving = true
local noautocmd = M.format_options.noautocmd and "noautocmd " or ""
vim.cmd(noautocmd .. "update")
vim.b.format_saving = false
lukas-reineke commented 1 year ago

I don't think that would be a good idea. If you don't send autocommands after formatting, plugins and the buffer state will get out of sync. For example, if formatting removes the first line in the buffer, all LSP errors will be shifted down one line.

If you really need this, you'd have to do it the other way around. Make a custom save function that will not trigger autocommands, then call lsp-format directly, which will trigger them. Then you get 1 BufWritePost/BufWritePre after everything is done. But that is a bit hacky, and not something I want to add here.

Note, if you want to build this, you'll also have to manually attach the buffer in lsp-format. Basically what is happening here https://github.com/lukas-reineke/lsp-format.nvim/blob/891aefcd0814a12e77675acba82731cdbc75a217/lua/lsp-format/init.lua#L129-L133

Or you have to clear the Format autogroup after you attach a client. (nvim_create_augroup will clear existing groups)

vim.api.nvim_create_augroup("Format")