robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
8.9 KiB291 linesraw
1local api = vim.api
2local nvim_on = require('vim._core.util').nvim_on
3
4---@alias vim.lsp.capability.Name
5---| 'codelens'
6---| 'diagnostics'
7---| 'document_color'
8---| 'folding_range'
9---| 'inlay_hint'
10---| 'inline_completion'
11---| 'linked_editing_range'
12---| 'semantic_tokens'
13
14--- Tracks all supported capabilities, all of which derive from `vim.lsp.Capability`.
15--- Returns capability *prototypes*, not their instances.
16---@type table<vim.lsp.capability.Name, vim.lsp.Capability>
17local all_capabilities = {}
18
19--- Track each capability instance created per buffer
20---@type table<integer, vim.lsp.Capability[]> buffer -> list of active capability instances
21local buf_capabilities = {}
22
23-- Abstract base class (not instantiable directly).
24-- For each buffer that has at least one supported client attached,
25-- exactly one instance of each concrete subclass is created.
26-- That instance is destroyed once all supporting clients detach from the buffer.
27---@class vim.lsp.Capability
28---
29--- Static field as the identifier of the LSP capability it supports.
30---@field name vim.lsp.capability.Name
31---
32--- Static field records the method this capability requires.
33---@field method vim.lsp.protocol.Method.ClientToServer | vim.lsp.protocol.Method.Registration
34---
35--- Static field for retrieving the instance associated with a specific `bufnr`.
36---
37--- Index in the form of `bufnr` -> `capability`
38---@field active table<integer, vim.lsp.Capability?>
39---
40--- Buffer number the capability instance is associated with.
41---@field bufnr integer
42---
43--- The augroup owned by this instance, which will be cleared upon destruction.
44---@field augroup integer
45---
46--- Per-client state data, scoped to the lifetime of the attached client.
47---@field client_state table<integer, table?>
48local M = {}
49M.__index = M
50
51---@generic T: vim.lsp.Capability
52---@param self T
53---@param bufnr integer
54---@return T
55function M.new(self, bufnr)
56  -- `self` in the `new()` function refers to the concrete type (i.e., the metatable).
57  -- `Class` may be a subtype of `Capability`, as it supports inheritance.
58  ---@type vim.lsp.Capability
59  local Class = self
60  if M == Class then
61    error('Do not instantiate the abstract class')
62  elseif all_capabilities[Class.name] and all_capabilities[Class.name] ~= Class then
63    error('Duplicated capability name')
64  else
65    all_capabilities[Class.name] = Class
66  end
67
68  ---@type T
69  self = setmetatable({}, Class)
70  self.bufnr = bufnr
71  self.augroup = api.nvim_create_augroup(string.format('nvim.lsp.%s:%s', self.name, bufnr), {
72    clear = true,
73  })
74  self.client_state = {}
75
76  if not buf_capabilities[bufnr] then
77    buf_capabilities[bufnr] = {}
78  end
79
80  table.insert(buf_capabilities[bufnr], self)
81
82  Class.active[bufnr] = self
83  return self
84end
85
86function M:destroy()
87  -- In case the function is called before all the clients detached.
88  for client_id, _ in pairs(self.client_state) do
89    self:on_detach(client_id)
90  end
91
92  api.nvim_del_augroup_by_id(self.augroup)
93  self.active[self.bufnr] = nil
94
95  buf_capabilities[self.bufnr] = vim.tbl_filter(function(cap)
96    return cap ~= self
97  end, buf_capabilities[self.bufnr])
98
99  if not next(buf_capabilities[self.bufnr]) then
100    buf_capabilities[self.bufnr] = nil
101  end
102end
103
104--- Callback invoked when an LSP client attaches.
105--- Use it to initialize per-client state (empty table, new namespaces, etc.),
106--- or issue requests as needed.
107---@param client_id integer
108function M:on_attach(client_id)
109  self.client_state[client_id] = {}
110end
111
112--- Callback invoked when an LSP client detaches.
113--- Use it to clear per-client state (cached data, extmarks, etc.).
114---@param client_id integer
115function M:on_detach(client_id)
116  self.client_state[client_id] = nil
117end
118
119--- Callback invoked when textDocument/didClose is sent for a client.
120---@param client_id integer
121---@diagnostic disable-next-line: unused
122function M:on_close(client_id) end
123
124--- Callback invoked when textDocument/didChange or textDocument/didOpen is sent for a client.
125---@param client_id integer
126---@diagnostic disable-next-line: unused
127function M:on_change(client_id) end
128
129--- Callback invoked on every redraw.
130---@param topline integer
131---@param botline integer
132---@diagnostic disable-next-line: unused
133function M:on_win(topline, botline) end
134
135---@param name vim.lsp.capability.Name
136local function make_enable_var(name)
137  return ('_lsp_enabled_%s'):format(name)
138end
139
140--- Optional filters |kwargs|,
141---@class vim.lsp.capability.enable.Filter
142---@inlinedoc
143---
144--- Buffer number, or 0 for current buffer, or nil for all.
145--- (default: all)
146---@field bufnr? integer
147---
148--- Client ID, or nil for all.
149--- (default: all)
150---@field client_id? integer
151
152---@param name vim.lsp.capability.Name
153---@param enable? boolean
154---@param filter? vim.lsp.capability.enable.Filter
155function M.enable(name, enable, filter)
156  vim.validate('name', name, 'string')
157  vim.validate('enable', enable, 'boolean', true)
158  vim.validate('filter', filter, 'table', true)
159
160  enable = enable == nil or enable
161  filter = filter or {}
162  local bufnr = filter.bufnr and vim._resolve_bufnr(filter.bufnr)
163  local client_id = filter.client_id
164
165  local var = make_enable_var(name)
166  local client = client_id and vim.lsp.get_client_by_id(client_id)
167
168  -- Attach or detach the client and its capability
169  -- based on the user’s latest marker value.
170  for _, it_client in ipairs(client and { client } or vim.lsp.get_clients()) do
171    for _, it_bufnr in
172      ipairs(
173        bufnr and { it_client.attached_buffers[bufnr] and bufnr }
174          or vim.tbl_keys(it_client.attached_buffers)
175          or {}
176      )
177    do
178      if enable ~= M.is_enabled(name, { bufnr = it_bufnr, client_id = it_client.id }) then
179        local Capability = all_capabilities[name]
180
181        if enable then
182          if it_client:supports_method(Capability.method) then
183            local capability = Capability.active[it_bufnr] or Capability:new(it_bufnr)
184            if not capability.client_state[it_client.id] then
185              capability:on_attach(it_client.id)
186            end
187          end
188        else
189          local capability = Capability.active[it_bufnr]
190          if capability then
191            capability:on_detach(it_client.id)
192            if not next(capability.client_state) then
193              capability:destroy()
194            end
195          end
196        end
197      end
198    end
199  end
200
201  -- Updates the marker value.
202  -- If local marker matches the global marker, set it to nil
203  -- so that `is_enable` falls back to the global marker.
204  if client then
205    if enable == vim.g[var] then
206      client._enabled_capabilities[name] = nil
207    else
208      client._enabled_capabilities[name] = enable
209    end
210  elseif bufnr then
211    if enable == vim.g[var] then
212      vim.b[bufnr][var] = nil
213    else
214      vim.b[bufnr][var] = enable
215    end
216  else
217    vim.g[var] = enable
218    for _, it_bufnr in ipairs(api.nvim_list_bufs()) do
219      if api.nvim_buf_is_loaded(it_bufnr) and vim.b[it_bufnr][var] == enable then
220        vim.b[it_bufnr][var] = nil
221      end
222    end
223    for _, it_client in ipairs(vim.lsp.get_clients()) do
224      if it_client._enabled_capabilities[name] == enable then
225        it_client._enabled_capabilities[name] = nil
226      end
227    end
228  end
229end
230
231---@param name vim.lsp.capability.Name
232---@param filter? vim.lsp.capability.enable.Filter
233function M.is_enabled(name, filter)
234  vim.validate('name', name, 'string')
235  vim.validate('filter', filter, 'table', true)
236
237  filter = filter or {}
238  local bufnr = filter.bufnr and vim._resolve_bufnr(filter.bufnr)
239  local client_id = filter.client_id
240
241  local var = make_enable_var(name)
242  local client = client_id and vim.lsp.get_client_by_id(client_id)
243
244  -- As a fallback when not explicitly enabled or disabled:
245  -- Clients are treated as "enabled" since their capabilities can control behavior.
246  -- Buffers are treated as "disabled" to allow users to enable them as needed.
247  return vim.nonnil(client and client._enabled_capabilities[name], vim.g[var], true)
248    and vim.nonnil(bufnr and vim.b[bufnr][var], vim.g[var], false)
249end
250
251M.all = all_capabilities
252
253local augroup = api.nvim_create_augroup('nvim.lsp.capability', {
254  clear = true,
255})
256
257nvim_on('LspNotify', augroup, function(ev)
258  local client_id = ev.data.client_id ---@type integer
259  local bufnr = ev.buf
260
261  if not buf_capabilities[bufnr] then
262    return
263  end
264
265  for _, provider in ipairs(buf_capabilities[bufnr]) do
266    if provider.client_state[client_id] then
267      if ev.data.method == 'textDocument/didClose' then
268        provider:on_close(client_id)
269      end
270
271      if ev.data.method == 'textDocument/didChange' or ev.data.method == 'textDocument/didOpen' then
272        provider:on_change(client_id)
273      end
274    end
275  end
276end)
277
278local namespace = api.nvim_create_namespace('nvim.lsp.capability')
279api.nvim_set_decoration_provider(namespace, {
280  on_win = function(_, _, bufnr, topline, botline)
281    if not buf_capabilities[bufnr] then
282      return
283    end
284
285    for _, provider in ipairs(buf_capabilities[bufnr]) do
286      provider:on_win(topline, botline)
287    end
288  end,
289})
290
291return M