robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
12.3 KiB423 linesraw
1local api = vim.api
2local log = require('vim.lsp.log')
3local nvim_on = require('vim._core.util').nvim_on
4local util = require('vim.lsp.util')
5
6local Capability = require('vim.lsp._capability')
7
8local M = {}
9
10---@class (private) vim.lsp.inlay_hint.LineHints
11---@field hints lsp.InlayHint[]
12---@field applied boolean whether this line's hints have had extmarks applied
13
14---@class (private) vim.lsp.inlay_hint.CurrentResult Info for current result
15---@field version? integer document version associated with this result
16---@field namespace_cleared? boolean whether the namespace was cleared for this result yet
17---@field hints? table<integer, vim.lsp.inlay_hint.LineHints> lnum -> hints
18
19---@class (private) vim.lsp.inlay_hint.ActiveRequest
20---@field request_id? integer the LSP request ID of the most recent request sent to the server
21---@field version? integer the document version associated with the most recent request
22
23---@class (private) vim.lsp.inlay_hint.ClientState Buffer local state for inlay hints
24---@field namespace integer
25---@field active_request vim.lsp.inlay_hint.ActiveRequest
26---@field current_result vim.lsp.inlay_hint.CurrentResult
27
28---@class (private) InlayHints : vim.lsp.Capability
29---@field active table<integer, InlayHints>
30---@field client_state table<integer, vim.lsp.inlay_hint.ClientState?>
31local InlayHint = {
32  name = 'inlay_hint',
33  method = 'textDocument/inlayHint',
34  active = {},
35}
36InlayHint.__index = InlayHint
37setmetatable(InlayHint, Capability)
38Capability.all[InlayHint.name] = InlayHint
39
40---@package
41---@param bufnr integer
42function InlayHint:new(bufnr)
43  self = Capability.new(self, bufnr)
44
45  nvim_on('BufWinEnter', self.augroup, { buf = self.bufnr }, function()
46    for client_id, _ in pairs(self.client_state) do
47      self:refresh(client_id)
48    end
49  end)
50
51  return self
52end
53
54---@package
55---@param client_id integer
56function InlayHint:on_attach(client_id)
57  if not self.client_state[client_id] then
58    self.client_state[client_id] = {
59      namespace = api.nvim_create_namespace('nvim.lsp.inlay_hint:' .. client_id),
60      active_request = {},
61      current_result = {},
62    }
63  end
64  self:refresh(client_id)
65end
66
67---@package
68---@param client_id integer
69function InlayHint:on_detach(client_id)
70  local state = self.client_state[client_id]
71  if state then
72    self:reset(client_id)
73    self.client_state[client_id] = nil
74  end
75end
76
77---@private
78---@param client_id integer
79function InlayHint:on_close(client_id)
80  self:reset(client_id)
81end
82
83---@private
84---@param client_id integer
85function InlayHint:on_change(client_id)
86  self:refresh(client_id)
87end
88
89--- Reset the buffer's inlay hint state and clear the extmarks
90---@package
91---@param client_id integer
92function InlayHint:reset(client_id)
93  local state = assert(self.client_state[client_id])
94  self:cancel_active_request(client_id)
95  api.nvim_buf_clear_namespace(self.bufnr, state.namespace, 0, -1)
96  state.current_result = {}
97end
98
99--- Refresh inlay hints by requesting them from the server
100---
101--- Only sends a request if there is no active request in flight for the current document version.
102--- Otherwise, it cancels any previous in-progress request before sending a new one.
103---
104---@package
105---@param client_id integer
106function InlayHint:refresh(client_id)
107  local version = util.buf_versions[self.bufnr]
108  local state = self.client_state[client_id]
109  local client = vim.lsp.get_client_by_id(client_id)
110
111  if state and client then
112    local current_result = state.current_result
113    local active_request = state.active_request
114
115    -- Only send a request for this client if the current result is out of date and
116    -- there isn't a current a request in flight for this version
117    if current_result.version == version or active_request.version == version then
118      return
119    end
120
121    -- cancel stale in-flight request
122    self:cancel_active_request(client_id)
123
124    ---@type lsp.InlayHintParams
125    local params = {
126      textDocument = util.make_text_document_params(self.bufnr),
127      range = vim
128        .range(self.bufnr, 0, 0, api.nvim_buf_line_count(self.bufnr), 0)
129        :to_lsp(client.offset_encoding),
130    }
131
132    local success, request_id = client:request('textDocument/inlayHint', params, nil, self.bufnr)
133
134    if success then
135      active_request.request_id = request_id
136      active_request.version = version
137    end
138  end
139end
140
141--- |lsp-handler| for the method `textDocument/inlayHint`
142--- Store hints for a specific buffer and client
143---@param err lsp.ResponseError?
144---@param result lsp.InlayHint[]?
145---@param ctx lsp.HandlerContext
146---@internal
147function M.on_inlayhint(err, result, ctx)
148  local bufnr = assert(ctx.bufnr)
149  local provider = InlayHint.active[bufnr]
150  if not provider then
151    return
152  end
153
154  local state = provider.client_state[ctx.client_id]
155  if not state then
156    return
157  end
158
159  if err then
160    log.error('inlay_hint', err)
161    state.active_request = {}
162    return
163  end
164
165  if util.buf_versions[bufnr] ~= ctx.version or not api.nvim_buf_is_loaded(bufnr) then
166    return
167  end
168
169  -- ignore stale responses
170  if state.active_request.request_id and ctx.request_id ~= state.active_request.request_id then
171    return
172  end
173
174  -- If there's no error but the result is nil, clear existing hints.
175  result = result or {}
176
177  local new_lnum_hints = {} ---@type table<integer, vim.lsp.inlay_hint.LineHints>
178  local num_unprocessed = #result
179  if num_unprocessed == 0 then
180    state.active_request = {}
181    state.current_result = {}
182    if vim.fn.win_gettype(vim.fn.bufwinid(bufnr)) == '' then
183      api.nvim__redraw({ buf = bufnr, valid = true, flush = false })
184    end
185    return
186  end
187
188  local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false)
189  local client = assert(vim.lsp.get_client_by_id(ctx.client_id))
190
191  for _, hint in ipairs(result) do
192    local lnum = hint.position.line
193    local line = lines and lines[lnum + 1] or ''
194    hint.position.character =
195      vim.str_byteindex(line, client.offset_encoding, hint.position.character, false)
196    if not new_lnum_hints[lnum] then
197      new_lnum_hints[lnum] = {
198        hints = {},
199        applied = false,
200      }
201    end
202    table.insert(new_lnum_hints[lnum].hints, hint)
203  end
204
205  state.active_request = {}
206  state.current_result = {
207    hints = new_lnum_hints,
208    version = ctx.version,
209    namespace_cleared = false,
210  }
211
212  if vim.fn.win_gettype(vim.fn.bufwinid(bufnr)) == '' then
213    api.nvim__redraw({ buf = bufnr, valid = true, flush = false })
214  end
215end
216
217---@private
218---@param client_id integer
219function InlayHint:cancel_active_request(client_id)
220  local state = assert(self.client_state[client_id])
221  local client = vim.lsp.get_client_by_id(client_id)
222  local active_request = state.active_request
223
224  if client and active_request.request_id then
225    client:cancel_request(active_request.request_id)
226    active_request.request_id = nil
227    active_request.version = nil
228  end
229end
230
231--- |lsp-handler| for the method `workspace/inlayHint/refresh`
232---@param err lsp.ResponseError?
233---@param ctx lsp.HandlerContext
234---@internal
235function M.on_refresh(err, _, ctx)
236  if err then
237    return vim.NIL
238  end
239
240  for bufnr, provider in pairs(InlayHint.active) do
241    if provider.client_state[ctx.client_id] then
242      provider:reset(ctx.client_id)
243
244      if not vim.tbl_isempty(vim.fn.win_findbuf(bufnr)) then
245        provider:refresh(ctx.client_id)
246      end
247    end
248  end
249
250  return vim.NIL
251end
252
253--- Optional filters |kwargs|:
254--- @class vim.lsp.inlay_hint.get.Filter
255--- @inlinedoc
256--- @field bufnr integer?
257--- @field range lsp.Range?
258
259--- @class vim.lsp.inlay_hint.get.ret
260--- @inlinedoc
261--- @field bufnr integer
262--- @field client_id integer
263--- @field inlay_hint lsp.InlayHint
264
265--- Get the list of inlay hints, (optionally) restricted by buffer or range.
266---
267--- Example usage:
268---
269--- ```lua
270--- local hint = vim.lsp.inlay_hint.get({ bufnr = 0 })[1] -- 0 for current buffer
271---
272--- local client = vim.lsp.get_client_by_id(hint.client_id)
273--- local resp = client:request_sync('inlayHint/resolve', hint.inlay_hint, 100, 0)
274--- local resolved_hint = assert(
275---   resp and resp.result,
276---   resp and resp.err and vim.lsp.rpc.format_rpc_error(resp.err) or 'request failed'
277--- )
278--- vim.lsp.util.apply_text_edits(resolved_hint.textEdits, 0, client.encoding)
279---
280--- location = resolved_hint.label[1].location
281--- client:request('textDocument/hover', {
282---   textDocument = { uri = location.uri },
283---   position = location.range.start,
284--- })
285--- ```
286---
287--- @param filter vim.lsp.inlay_hint.get.Filter?
288--- @return vim.lsp.inlay_hint.get.ret[]
289--- @since 12
290function M.get(filter)
291  vim.validate('filter', filter, 'table', true)
292  filter = filter or {}
293
294  local bufnr = filter.bufnr
295  if not bufnr then
296    return vim
297      .iter(api.nvim_list_bufs())
298      :map(function(buf)
299        return M.get(vim.tbl_extend('keep', { bufnr = buf }, filter))
300      end)
301      :flatten()
302      :totable()
303  else
304    bufnr = vim._resolve_bufnr(bufnr)
305  end
306
307  local provider = InlayHint.active[bufnr]
308  if not provider then
309    return {}
310  end
311
312  local range = filter.range
313  if not range then
314    range = {
315      start = { line = 0, character = 0 },
316      ['end'] = { line = api.nvim_buf_line_count(bufnr), character = 0 },
317    }
318  end
319
320  --- @type vim.lsp.inlay_hint.get.ret[]
321  local result = {}
322  for client_id, state in pairs(provider.client_state) do
323    local lnum_hints = state.current_result.hints
324    if lnum_hints then
325      for lnum = range.start.line, range['end'].line do
326        local line_hints = lnum_hints[lnum] or { hints = {}, applied = false }
327        for _, hint in pairs(line_hints.hints) do
328          local line, char = hint.position.line, hint.position.character
329          if
330            (line > range.start.line or char >= range.start.character)
331            and (line < range['end'].line or char <= range['end'].character)
332          then
333            table.insert(result, {
334              bufnr = bufnr,
335              client_id = client_id,
336              inlay_hint = hint,
337            })
338          end
339        end
340      end
341    end
342  end
343  return result
344end
345
346--- on_win handler for the decoration provider (see |nvim_set_decoration_provider|)
347---@package
348---@param topline integer
349---@param botline integer
350function InlayHint:on_win(topline, botline)
351  for _, state in pairs(self.client_state) do
352    local current_result = state.current_result
353    if current_result.version == util.buf_versions[self.bufnr] then
354      if not current_result.namespace_cleared then
355        api.nvim_buf_clear_namespace(self.bufnr, state.namespace, 0, -1)
356        current_result.namespace_cleared = true
357      end
358
359      local hints = assert(current_result.hints)
360
361      for lnum = topline, botline do
362        local hint_virtual_texts = {} --- @type table<integer, [string, string?][]>
363        local line_hints = hints[lnum]
364        if line_hints and not line_hints.applied then
365          line_hints.applied = true
366          for _, hint in pairs(line_hints.hints) do
367            local text = ''
368            local label = hint.label
369            if type(label) == 'string' then
370              text = label
371            else
372              for _, part in ipairs(label) do
373                text = text .. part.value
374              end
375            end
376            local vt = hint_virtual_texts[hint.position.character] or {}
377            if hint.paddingLeft then
378              vt[#vt + 1] = { ' ' }
379            end
380            vt[#vt + 1] = { text, 'LspInlayHint' }
381            if hint.paddingRight then
382              vt[#vt + 1] = { ' ' }
383            end
384            hint_virtual_texts[hint.position.character] = vt
385          end
386        end
387
388        for pos, vt in pairs(hint_virtual_texts) do
389          api.nvim_buf_set_extmark(self.bufnr, state.namespace, lnum, pos, {
390            virt_text_pos = 'inline',
391            ephemeral = false,
392            virt_text = vt,
393          })
394        end
395      end
396    end
397  end
398end
399
400--- Query whether inlay hint is enabled in the {filter}ed scope
401--- @param filter? vim.lsp.capability.enable.Filter
402--- @return boolean
403--- @since 12
404function M.is_enabled(filter)
405  return Capability.is_enabled('inlay_hint', filter)
406end
407
408--- Enables or disables inlay hints for the {filter}ed scope.
409---
410--- To "toggle", pass the inverse of `is_enabled()`:
411---
412--- ```lua
413--- vim.lsp.inlay_hint.enable(not vim.lsp.inlay_hint.is_enabled())
414--- ```
415---
416--- @param enable boolean? true/nil to enable, false to disable
417--- @param filter? vim.lsp.capability.enable.Filter
418--- @since 12
419function M.enable(enable, filter)
420  Capability.enable('inlay_hint', enable, filter)
421end
422
423return M