I’m using EFM + prettier for formatting my files. When I save multiple files at once :wa
and use async formatting, the content of those buffers will get replaced with the wrong buffer. E.g. line 5 from buffer X will go into line 5 of buffer Y, while line 20 of buffer Y will go into line 20 of buffer X. This doesn’t happen when I use sync formatting. Any idea why this is happening?
Here is the relevant config for reference
-- lets us use efm formatting instead of other servers like tsserver
local prioritize_efm_formatting
function custom_formatting()
if not prioritize_efm_formatting then
local clients = vim.lsp.buf_get_clients(0)
if #clients > 1 then
-- check if multiple clients, and if efm is setup
for _,c1 in pairs(clients) do
if c1.name == "efm" then
-- if efm then disable others
for _,c2 in pairs(clients) do
if c2.name ~= "efm" then c2.resolved_capabilities.document_formatting = false end
end
-- no need to contunue first loop
break
end
end
end
end
-- no need to do above check again
prioritize_efm_formatting = true
-- seems like async mode will mess up the content if multiple buffers are saved at once
vim.lsp.buf.formatting()
end
-- Use an on_attach function to only map the following keys after the language server attaches to the current buffer
local on_attach = function(client, bufnr)
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end
--Enable completion triggered by <c-x><c-o>
buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc')
-- reference highlighting
require 'illuminate'.on_attach(client)
-- Mappings.
local opts = { noremap=true, silent=true }
-- See `:help vim.lsp.*` for documentation on any of the below functions
buf_set_keymap('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<cr>', opts)
buf_set_keymap('n', 'gD', '<cmd>lua vim.lsp.buf.type_definition()<cr>', opts)opts)
buf_set_keymap('n', '<leader>D', '<cmd>lua vim.lsp.diagnostic.set_loclist()<cr>', opts)
buf_set_keymap('n', 'g=', '<cmd>lua custom_formatting()<cr>', opts)
buf_set_keymap('n', '<leader>oi', '<cmd>lua organize_imports()<cr>', opts)print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<cr>', opts)
-- auto format
if client.resolved_capabilities.document_formatting then
vim.cmd [[augroup AutoFormat]]
vim.cmd [[autocmd! * <buffer>]]
vim.cmd [[autocmd BufWritePre <buffer> lua custom_formatting()]]
vim.cmd [[augroup END]]
end
end