-- Absorbed from LazyVim -- TODO: review, understand and adapt ---@class rmz.util.lsp local M = {} ---@alias lsp.Client.filter {id?: number, bufnr?: number, name?: string, method?: string, filter?:fun(client: lsp.Client):boolean} M.kind_filter = { default = { "Class", "Constructor", "Enum", "Field", "Function", "Interface", "Method", "Module", "Namespace", "Package", "Property", "Struct", "Trait", }, markdown = false, help = false, -- you can specify a different filter for each filetype lua = { "Class", "Constructor", "Enum", "Field", "Function", "Interface", "Method", "Module", "Namespace", -- "Package", -- remove package since luals uses it for control flow structures "Property", "Struct", "Trait", }, } ---@param opts? lsp.Client.filter function M.get_clients(opts) local ret = {} ---@type vim.lsp.Client[] if vim.lsp.get_clients then ret = vim.lsp.get_clients(opts) else ---@diagnostic disable-next-line: deprecated ret = vim.lsp.get_active_clients(opts) if opts and opts.method then ---@param client vim.lsp.Client ret = vim.tbl_filter(function(client) return client.supports_method(opts.method, { bufnr = opts.bufnr }) end, ret) end end return opts and opts.filter and vim.tbl_filter(opts.filter, ret) or ret end ---@param on_attach fun(client:vim.lsp.Client, buffer) ---@param name? string function M.on_attach(on_attach, name) return vim.api.nvim_create_autocmd("LspAttach", { callback = function(args) local buffer = args.buf ---@type number local client = vim.lsp.get_client_by_id(args.data.client_id) if client and (not name or client.name == name) then return on_attach(client, buffer) end end, }) end function M.setup() local register_capability = vim.lsp.handlers["client/registerCapability"] vim.lsp.handlers["client/registerCapability"] = function(err, res, ctx) ---@diagnostic disable-next-line: no-unknown local ret = register_capability(err, res, ctx) local client = vim.lsp.get_client_by_id(ctx.client_id) if client then for buffer in pairs(client.attached_buffers) do vim.api.nvim_exec_autocmds("User", { pattern = "LspDynamicCapability", data = { client_id = client.id, buffer = buffer }, }) end end return ret end end ---@param fn fun(client:vim.lsp.Client, buffer):boolean? ---@param opts? {group?: integer} function M.on_dynamic_capability(fn, opts) return vim.api.nvim_create_autocmd("User", { pattern = "LspDynamicCapability", group = opts and opts.group or nil, callback = function(args) local client = vim.lsp.get_client_by_id(args.data.client_id) local buffer = args.data.buffer ---@type number if client then return fn(client, buffer) end end, }) end M.action = setmetatable({}, { __index = function(_, action) return function() vim.lsp.buf.code_action({ apply = true, context = { only = { action }, diagnostics = {}, }, }) end end, }) return M