Skip to content

Commit

Permalink
feat(nvim): improve lsp format/organize imports
Browse files Browse the repository at this point in the history
  • Loading branch information
caarlos0 committed Sep 29, 2023
1 parent 034e794 commit 4067ea4
Showing 1 changed file with 27 additions and 10 deletions.
37 changes: 27 additions & 10 deletions modules/neovim/config/lua/lsp_autocommands.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,26 @@ local group = vim.api.nvim_create_augroup("LSP", { clear = true })

-- Format code and organize imports (if supported).
--
---@param client lsp.Client Client
---@param bufnr number Buffer number
---@param timeoutms number timeout in ms
local format_and_organize_imports = function(bufnr, timeoutms)
local organize_imports = function(client, bufnr, timeoutms)
local params = vim.lsp.util.make_range_params()
params.context = { only = { "source.organizeImports" } }
-- TODO: PR neovim allowing to filter buf_request_sync
local result = vim.lsp.buf_request_sync(bufnr, "textDocument/codeAction", params, timeoutms)
for cid, res in pairs(result or {}) do
for _, r in pairs(res.result or {}) do
if r.edit then
local enc = (vim.lsp.get_client_by_id(cid) or {}).offset_encoding or "utf-16"
vim.lsp.util.apply_workspace_edit(r.edit, enc)
elseif r.command and r.command.command then
vim.lsp.buf.execute_command(r.command)
if cid == client.id then
for _, r in pairs(res.result or {}) do
if r.edit then
local enc = (vim.lsp.get_client_by_id(cid) or {}).offset_encoding or "utf-16"
vim.lsp.util.apply_workspace_edit(r.edit, enc)
elseif r.command and r.command.command then
vim.lsp.buf.execute_command(r.command)
end
end
end
end
vim.lsp.buf.format({ async = false })
end

--- Checks if the given client is alive.
Expand Down Expand Up @@ -46,12 +49,26 @@ local M = {}
---@param bufnr number
M.on_attach = function(client, bufnr)
-- what are the chances of a lsp supporting code actions but not supporting formatting?
-- client.server_capabilities.codeActionProvider
if client.server_capabilities.codeActionProvider and client.name ~= "lua_ls" then
vim.api.nvim_create_autocmd({ "BufWritePre" }, {
buffer = bufnr,
callback = function()
organize_imports(client, bufnr, 1500)
end,
group = group,
})
end

if client.server_capabilities.documentFormattingProvider then
vim.api.nvim_create_autocmd({ "BufWritePre" }, {
buffer = bufnr,
callback = function()
format_and_organize_imports(bufnr, 1500)
vim.lsp.buf.format({
bufnr = bufnr,
filter = function(cli)
return cli.id == client.id
end,
})
end,
group = group,
})
Expand Down

0 comments on commit 4067ea4

Please sign in to comment.