@@ -2,23 +2,26 @@ local group = vim.api.nvim_create_augroup("LSP", { clear = true })
22
33-- Format code and organize imports (if supported).
44--
5+ --- @param client lsp.Client Client
56--- @param bufnr number Buffer number
67--- @param timeoutms number timeout in ms
7- local format_and_organize_imports = function (bufnr , timeoutms )
8+ local organize_imports = function (client , bufnr , timeoutms )
89 local params = vim .lsp .util .make_range_params ()
910 params .context = { only = { " source.organizeImports" } }
11+ -- TODO: PR neovim allowing to filter buf_request_sync
1012 local result = vim .lsp .buf_request_sync (bufnr , " textDocument/codeAction" , params , timeoutms )
1113 for cid , res in pairs (result or {}) do
12- for _ , r in pairs (res .result or {}) do
13- if r .edit then
14- local enc = (vim .lsp .get_client_by_id (cid ) or {}).offset_encoding or " utf-16"
15- vim .lsp .util .apply_workspace_edit (r .edit , enc )
16- elseif r .command and r .command .command then
17- vim .lsp .buf .execute_command (r .command )
14+ if cid == client .id then
15+ for _ , r in pairs (res .result or {}) do
16+ if r .edit then
17+ local enc = (vim .lsp .get_client_by_id (cid ) or {}).offset_encoding or " utf-16"
18+ vim .lsp .util .apply_workspace_edit (r .edit , enc )
19+ elseif r .command and r .command .command then
20+ vim .lsp .buf .execute_command (r .command )
21+ end
1822 end
1923 end
2024 end
21- vim .lsp .buf .format ({ async = false })
2225end
2326
2427--- Checks if the given client is alive.
@@ -46,12 +49,26 @@ local M = {}
4649--- @param bufnr number
4750M .on_attach = function (client , bufnr )
4851 -- what are the chances of a lsp supporting code actions but not supporting formatting?
49- -- client.server_capabilities.codeActionProvider
52+ if client .server_capabilities .codeActionProvider and client .name ~= " lua_ls" then
53+ vim .api .nvim_create_autocmd ({ " BufWritePre" }, {
54+ buffer = bufnr ,
55+ callback = function ()
56+ organize_imports (client , bufnr , 1500 )
57+ end ,
58+ group = group ,
59+ })
60+ end
61+
5062 if client .server_capabilities .documentFormattingProvider then
5163 vim .api .nvim_create_autocmd ({ " BufWritePre" }, {
5264 buffer = bufnr ,
5365 callback = function ()
54- format_and_organize_imports (bufnr , 1500 )
66+ vim .lsp .buf .format ({
67+ bufnr = bufnr ,
68+ filter = function (cli )
69+ return cli .id == client .id
70+ end ,
71+ })
5572 end ,
5673 group = group ,
5774 })
0 commit comments