robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
33.3 KiB1020 linesraw
1local api = vim.api
2local nvim_on = require('vim._core.util').nvim_on
3local bit = require('bit')
4local util = require('vim.lsp.util')
5local Range = require('vim.treesitter._range')
6local uv = vim.uv
7
8local Capability = require('vim.lsp._capability')
9
10local M = {}
11
12--- @class (private) STTokenRange
13--- @field line integer line number 0-based
14--- @field start_col integer start column 0-based
15--- @field end_line integer end line number 0-based
16--- @field end_col integer end column 0-based
17--- @field type string token type as string
18--- @field modifiers table<string,boolean> token modifiers as a set. E.g., { static = true, readonly = true }
19--- @field marked boolean whether this token has had extmarks applied
20
21--- @class (private) STCurrentResult
22--- @field version? integer document version associated with this result
23--- @field result_id? string resultId from the server; used with delta requests
24--- @field highlights? STTokenRange[] cache of highlight ranges for this document version
25--- @field tokens? uinteger[] raw token array as received by the server. used for calculating delta responses
26--- @field namespace_cleared? boolean whether the namespace was cleared for this result yet
27
28--- @class (private) STActiveRequest
29--- @field request_id? integer the LSP request ID of the most recent request sent to the server
30--- @field version? integer the document version associated with the most recent request
31
32--- @class (private) STClientState
33--- @field namespace integer
34--- @field supports_range boolean
35--- @field supports_delta boolean
36--- @field active_request STActiveRequest
37--- @field active_range_request STActiveRequest
38--- @field current_result STCurrentResult
39--- @field timer uv.uv_timer_t? uv_timer for debouncing requests for new tokens
40--- @field has_full_result boolean
41
42---@class (private) STHighlighter : vim.lsp.Capability
43---@field active table<integer, STHighlighter>
44---@field debounce integer milliseconds to debounce requests for new tokens
45---@field client_state table<integer, STClientState?>
46local STHighlighter = {
47  name = 'semantic_tokens',
48  method = 'textDocument/semanticTokens',
49  debounce = 200,
50  active = {},
51}
52STHighlighter.__index = STHighlighter
53setmetatable(STHighlighter, Capability)
54Capability.all[STHighlighter.name] = STHighlighter
55
56--- Extracts modifier strings from the encoded number in the token array
57---
58---@param x integer
59---@param modifiers_table table<integer,string>
60---@return table<string, boolean>
61local function modifiers_from_number(x, modifiers_table)
62  local modifiers = {} ---@type table<string,boolean>
63  local idx = 1
64  while x > 0 do
65    if bit.band(x, 1) == 1 then
66      modifiers[modifiers_table[idx]] = true
67    end
68    x = bit.rshift(x, 1)
69    idx = idx + 1
70  end
71
72  return modifiers
73end
74
75--- Converts a raw token list to a list of highlight ranges used by the on_win callback
76---
77---@async
78---@param data integer[]
79---@param bufnr integer
80---@param client vim.lsp.Client
81---@param request STActiveRequest
82---@param ranges STTokenRange[]
83---@return STTokenRange[]
84local function tokens_to_ranges(data, bufnr, client, request, ranges)
85  local legend = assert(client.server_capabilities.semanticTokensProvider).legend
86  local token_types = legend.tokenTypes
87  local token_modifiers = legend.tokenModifiers
88  local encoding = client.offset_encoding
89  local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false)
90  -- For all encodings, \r\n takes up two code points, and \n (or \r) takes up one.
91  local eol_offset = vim.bo[bufnr].fileformat == 'dos' and 2 or 1
92  local version = request.version
93  local request_id = request.request_id
94  local last_insert_idx = 1
95
96  local start = uv.hrtime()
97  local ms_to_ns = 1e6
98  local yield_interval_ns = 5 * ms_to_ns
99  local co, is_main = coroutine.running()
100
101  local line ---@type integer?
102  local start_char = 0
103  for i = 1, #data, 5 do
104    -- if this function is called from the main coroutine, let it run to completion with no yield
105    if not is_main then
106      local elapsed_ns = uv.hrtime() - start
107
108      if elapsed_ns > yield_interval_ns then
109        vim.schedule(function()
110          -- Ensure the request hasn't become stale since the last time the coroutine ran.
111          -- If it's stale, we don't resume the coroutine so it'll be garbage collected.
112          if
113            version == util.buf_versions[bufnr]
114            ---@diagnostic disable-next-line: preferred-local-alias
115            and request_id == request.request_id
116            and api.nvim_buf_is_valid(bufnr)
117          then
118            coroutine.resume(co)
119          end
120        end)
121
122        coroutine.yield()
123        start = uv.hrtime()
124      end
125    end
126
127    -- The protocol encodes each token as five integers.
128    local delta_line = data[i]
129    line = line and line + delta_line or delta_line
130    local delta_start = assert(data[i + 1])
131    start_char = delta_line == 0 and start_char + delta_start or delta_start
132
133    -- data[i+3] +1 because Lua tables are 1-indexed
134    local token_type = token_types[assert(data[i + 3]) + 1]
135
136    if token_type then
137      local modifiers = modifiers_from_number(assert(data[i + 4]), token_modifiers)
138      local end_char = start_char + assert(data[i + 2])
139      local buf_line = lines[line + 1] or ''
140      local end_line = line ---@type integer
141      local start_col = vim.str_byteindex(buf_line, encoding, start_char, false)
142
143      ---@type integer LuaLS bug, type must be marked explicitly here
144      local new_end_char = end_char - vim.str_utfindex(buf_line, encoding) - eol_offset
145      -- While end_char goes past the given line, extend the token range to the next line
146      while new_end_char > 0 and end_line < #lines - 1 do
147        end_char = new_end_char
148        end_line = end_line + 1
149        buf_line = lines[end_line + 1] or ''
150        new_end_char = new_end_char - vim.str_utfindex(buf_line, encoding) - eol_offset
151      end
152
153      local end_col = vim.str_byteindex(buf_line, encoding, end_char, false)
154
155      ---@type STTokenRange
156      local range = {
157        line = line,
158        end_line = end_line,
159        start_col = start_col,
160        end_col = end_col,
161        type = token_type,
162        modifiers = modifiers,
163        marked = false,
164      }
165
166      if last_insert_idx < #ranges then
167        local needs_insert = true
168        local idx = vim.list.bisect(ranges, range, {
169          lo = last_insert_idx,
170          key = function(highlight)
171            return highlight.line
172          end,
173        })
174        while idx <= #ranges do
175          local token = assert(ranges[idx])
176
177          if
178            token.line > range.line
179            or (token.line == range.line and token.start_col > range.start_col)
180          then
181            break
182          end
183
184          if
185            range.line == token.line
186            and range.start_col == token.start_col
187            and range.end_line == token.end_line
188            and range.end_col == token.end_col
189            and range.type == token.type
190          then
191            needs_insert = false
192            break
193          end
194
195          idx = idx + 1
196        end
197
198        last_insert_idx = idx
199        if needs_insert then
200          table.insert(ranges, last_insert_idx, range)
201        end
202      else
203        last_insert_idx = #ranges + 1
204        ranges[last_insert_idx] = range
205      end
206    end
207  end
208
209  return ranges
210end
211
212---@package
213---@param bufnr integer
214function STHighlighter:new(bufnr)
215  self = Capability.new(self, bufnr)
216
217  nvim_on('BufWinEnter', self.augroup, { buf = self.bufnr }, function()
218    for client_id, _ in pairs(self.client_state) do
219      self:send_request(client_id)
220    end
221  end)
222
223  nvim_on('WinScrolled', self.augroup, { buf = self.bufnr }, function()
224    for client_id, state in pairs(self.client_state) do
225      if state.supports_range then
226        self:debounce_request(client_id)
227      end
228    end
229  end)
230
231  return self
232end
233
234---@package
235---@param client_id integer
236function STHighlighter:on_attach(client_id)
237  local client = vim.lsp.get_client_by_id(client_id)
238  local state = self.client_state[client_id]
239  if not state then
240    state = {
241      namespace = api.nvim_create_namespace('nvim.lsp.semantic_tokens:' .. client_id),
242      supports_range = client
243          and client:supports_method('textDocument/semanticTokens/range', self.bufnr)
244        or false,
245      supports_delta = client
246          and client:supports_method('textDocument/semanticTokens/full/delta', self.bufnr)
247        or false,
248      active_request = {},
249      active_range_request = {},
250      current_result = {},
251      has_full_result = false,
252    }
253    self.client_state[client_id] = state
254  end
255
256  self:send_request(client_id)
257end
258
259---@package
260---@param client_id integer
261function STHighlighter:on_detach(client_id)
262  local state = self.client_state[client_id]
263  if state then
264    --TODO: delete namespace if/when that becomes possible
265    api.nvim_buf_clear_namespace(self.bufnr, state.namespace, 0, -1)
266    self:reset_timer(state)
267    self.client_state[client_id] = nil
268  end
269end
270
271---@private
272---@param client_id integer
273function STHighlighter:on_close(client_id)
274  self:reset(client_id)
275end
276
277---@private
278---@param client_id integer
279function STHighlighter:on_change(client_id)
280  self:send_request(client_id)
281end
282
283--- This is the entry point for getting all the tokens in a buffer.
284---
285--- For the given client, this sends semantic token requests to ask for semantic tokens. If the
286--- server supports range requests and a full result has not been processed yet, it will send a
287--- range request for the current visible range. Additionally, if a result for the current document
288--- version hasn't been processed yet, it sends either a full or delta request, depending on what
289--- the server supports and whether there's a current full result for the previous document version.
290---
291--- This function will skip full/delta requests on servers where there is an already an active
292--- full/delta request in flight for the same version. If there is a stale request in flight, that
293--- is cancelled prior to sending a new one.
294---
295--- Finally, for successful requests, the requestId (full/delta) and document version are saved to
296--- facilitate document synchronization in the response.
297---
298---@package
299---@param client_id integer
300function STHighlighter:send_request(client_id)
301  local client = vim.lsp.get_client_by_id(client_id)
302  local state = self.client_state[client_id]
303
304  if client and state then
305    self:reset_timer(state)
306
307    local version = util.buf_versions[self.bufnr]
308
309    -- If the server supports range and there's no full result yet, then start with a range
310    -- request
311    if state.supports_range and not state.has_full_result then
312      self:send_range_request(client, state, version)
313    end
314
315    if
316      (not state.has_full_result or state.current_result.version ~= version)
317      and state.active_request.version ~= version
318    then
319      self:send_full_delta_request(client, state, version)
320    end
321  end
322end
323
324--- Send a range request for the visible area
325---
326---@private
327---@param client vim.lsp.Client
328---@param state STClientState
329---@param version integer
330function STHighlighter:send_range_request(client, state, version)
331  local active_request = state.active_range_request
332
333  -- cancel stale in-flight request
334  if active_request and active_request.request_id then
335    client:cancel_request(active_request.request_id)
336    active_request.request_id = nil
337    active_request.version = nil
338  end
339
340  ---@type lsp.SemanticTokensRangeParams
341  local params = {
342    textDocument = util.make_text_document_params(self.bufnr),
343    range = self:get_overscan_range(),
344  }
345
346  ---@type vim.lsp.protocol.Method.ClientToServer.Request
347  local method = 'textDocument/semanticTokens/range'
348
349  ---@param response? lsp.SemanticTokens
350  local success, request_id = client:request(method, params, function(err, response, ctx)
351    local bufnr = assert(ctx.bufnr)
352    local highlighter = STHighlighter.active[bufnr]
353    if not highlighter then
354      return
355    end
356
357    -- Only process range response if we got a valid response and don't have a full result yet
358    if err or not response or state.has_full_result then
359      if err then
360        vim.lsp.log.error('semantic_tokens', err)
361      end
362      active_request.request_id = nil
363      active_request.version = nil
364      return
365    end
366
367    coroutine.wrap(STHighlighter.process_response)(
368      highlighter,
369      response,
370      client,
371      ctx.request_id,
372      version,
373      true
374    )
375  end, self.bufnr)
376
377  if success then
378    active_request.request_id = request_id
379    active_request.version = version
380  end
381end
382
383--- Send a full or delta request
384---
385---@private
386---@param client vim.lsp.Client
387---@param state STClientState
388---@param version integer
389function STHighlighter:send_full_delta_request(client, state, version)
390  local current_result = state.current_result
391  local active_request = state.active_request
392
393  -- cancel stale in-flight request
394  if active_request.request_id then
395    client:cancel_request(active_request.request_id)
396    active_request.request_id = nil
397    active_request.version = nil
398  end
399
400  ---@type lsp.SemanticTokensParams|lsp.SemanticTokensDeltaParams
401  local params = { textDocument = util.make_text_document_params(self.bufnr) }
402
403  ---@type vim.lsp.protocol.Method.ClientToServer.Request
404  local method = 'textDocument/semanticTokens/full'
405
406  if state.supports_delta and current_result.result_id then
407    method = 'textDocument/semanticTokens/full/delta'
408    params.previousResultId = current_result.result_id
409  end
410
411  ---@param response? lsp.SemanticTokens|lsp.SemanticTokensDelta
412  local success, request_id = client:request(method, params, function(err, response, ctx)
413    local bufnr = assert(ctx.bufnr)
414    local highlighter = STHighlighter.active[bufnr]
415    if not highlighter then
416      return
417    end
418
419    if err or not response then
420      if err then
421        vim.lsp.log.error('semantic_tokens', err)
422      end
423      active_request.request_id = nil
424      active_request.version = nil
425      return
426    end
427
428    coroutine.wrap(STHighlighter.process_response)(
429      highlighter,
430      response,
431      client,
432      ctx.request_id,
433      version,
434      false
435    )
436  end, self.bufnr)
437
438  if success then
439    active_request.request_id = request_id
440    active_request.version = version
441  end
442end
443
444---@private
445---@param client_id integer
446function STHighlighter:cancel_active_request(client_id)
447  local state = assert(self.client_state[client_id])
448  local client = vim.lsp.get_client_by_id(client_id)
449
450  ---@param request STActiveRequest
451  local function clear(request)
452    if client and request.request_id then
453      client:cancel_request(request.request_id)
454      request.request_id = nil
455      request.version = nil
456    end
457  end
458
459  clear(state.active_range_request)
460  clear(state.active_request)
461end
462
463--- Gets a range that encompasses all visible lines plus overscan across all windows
464--- @private
465--- @return lsp.Range
466function STHighlighter:get_overscan_range()
467  local wins = vim.fn.win_findbuf(self.bufnr)
468  local num_lines = api.nvim_buf_line_count(self.bufnr)
469  local min_start, max_end = nil, nil
470
471  for _, win in ipairs(wins) do
472    local wininfo = vim.fn.getwininfo(win)[1]
473    if wininfo then
474      -- Overscan the token request by the height of the window on each side
475      -- to prevent flickering when navigating up and down.
476      local start_line = math.max(0, wininfo.topline - 1 - wininfo.height)
477      local end_line = math.min(num_lines, wininfo.botline + wininfo.height)
478      if not min_start or start_line < min_start then
479        min_start = start_line
480      end
481      if not max_end or end_line > max_end then
482        max_end = end_line
483      end
484    end
485  end
486
487  ---@type lsp.Range
488  return {
489    ['start'] = { line = min_start or 0, character = 0 },
490    ['end'] = { line = max_end or 0, character = 0 },
491  }
492end
493
494--- This function will parse the semantic token responses and set up the cache
495--- (current_result). It also performs document synchronization by checking the
496--- version of the document associated with the resulting request_id and only
497--- performing work if the response is not out-of-date.
498---
499--- Delta edits are applied if necessary, and new highlight ranges are calculated
500--- and stored in the buffer state.
501---
502--- Finally, a redraw command is issued to force nvim to redraw the screen to
503--- pick up changed highlight tokens.
504---
505---@async
506---@param response lsp.SemanticTokens|lsp.SemanticTokensDelta
507---@param client vim.lsp.Client
508---@param request_id integer
509---@param version integer
510---@param is_range_request boolean
511---@private
512function STHighlighter:process_response(response, client, request_id, version, is_range_request)
513  local state = self.client_state[client.id]
514  if not state then
515    return
516  end
517
518  ---@type STActiveRequest
519  local active_request
520  if is_range_request then
521    active_request = state.active_range_request
522  else
523    active_request = state.active_request
524  end
525
526  -- ignore stale responses
527  if active_request.request_id and request_id ~= active_request.request_id then
528    return
529  end
530
531  if not api.nvim_buf_is_valid(self.bufnr) then
532    return
533  end
534
535  -- if we have a response to a delta request, update the state of our tokens
536  -- appropriately. if it's a full response, just use that
537  local tokens ---@type integer[]
538  if response.edits then
539    local token_edits = response.edits
540    table.sort(token_edits, function(a, b)
541      return a.start < b.start
542    end)
543
544    tokens = {} --- @type integer[]
545    local old_tokens = assert(state.current_result.tokens)
546    local idx = 1
547    for _, token_edit in ipairs(token_edits) do
548      vim.list_extend(tokens, old_tokens, idx, token_edit.start)
549      if token_edit.data then
550        vim.list_extend(tokens, token_edit.data)
551      end
552      idx = token_edit.start + token_edit.deleteCount + 1
553    end
554    vim.list_extend(tokens, old_tokens, idx)
555  else
556    tokens = response.data
557  end
558
559  local current_result = state.current_result
560  local version_changed = version ~= current_result.version
561  local highlights = not version_changed and current_result.highlights or {}
562
563  -- convert token list to highlight ranges
564  -- this could yield and run over multiple event loop iterations
565  highlights = tokens_to_ranges(tokens, self.bufnr, client, active_request, highlights)
566
567  -- if this was a full result, mark the state as having processed it
568  if not is_range_request then
569    state.has_full_result = true
570  end
571
572  -- reset active request
573  active_request.request_id = nil
574  active_request.version = nil
575
576  -- update the state with the new results
577  current_result.version = version
578  current_result.result_id = not is_range_request and response.resultId or nil
579  current_result.tokens = tokens
580  current_result.highlights = highlights
581  if version_changed then
582    current_result.namespace_cleared = false
583  end
584
585  -- redraw all windows displaying buffer
586  if vim.fn.win_gettype(vim.fn.bufwinid(self.bufnr)) == '' then
587    api.nvim__redraw({ buf = self.bufnr, valid = true })
588  end
589end
590
591--- @param bufnr integer
592--- @param ns integer
593--- @param token STTokenRange
594--- @param hl_group string
595--- @param priority integer
596local function set_mark(bufnr, ns, token, hl_group, priority)
597  api.nvim_buf_set_extmark(bufnr, ns, token.line, token.start_col, {
598    hl_group = hl_group,
599    end_line = token.end_line,
600    end_col = token.end_col,
601    priority = priority,
602    strict = false,
603  })
604end
605
606--- @param lnum integer
607--- @param foldend integer?
608--- @return boolean, integer?
609local function check_fold(lnum, foldend)
610  if foldend and lnum <= foldend then
611    return true, foldend
612  end
613
614  local folded = vim.fn.foldclosed(lnum)
615
616  if folded == -1 then
617    return false, nil
618  end
619
620  return folded ~= lnum, vim.fn.foldclosedend(lnum)
621end
622
623--- on_win handler for the decoration provider (see |nvim_set_decoration_provider|)
624---
625--- If there is a current result for the buffer and the version matches the
626--- current document version, then the tokens are valid and can be applied. As
627--- the buffer is drawn, this function will add extmark highlights for every
628--- token in the range of visible lines. Once a highlight has been added, it
629--- sticks around until the document changes and there's a new set of matching
630--- highlight tokens available.
631---
632--- If this is the first time a buffer is being drawn with a new set of
633--- highlights for the current document version, the namespace is cleared to
634--- remove extmarks from the last version. It's done here instead of the response
635--- handler to avoid the "blink" that occurs due to the timing between the
636--- response handler and the actual redraw.
637---
638---@package
639---@param topline integer
640---@param botline integer
641function STHighlighter:on_win(topline, botline)
642  for client_id, state in pairs(self.client_state) do
643    local current_result = state.current_result
644    if current_result.version == util.buf_versions[self.bufnr] then
645      if not current_result.namespace_cleared then
646        api.nvim_buf_clear_namespace(self.bufnr, state.namespace, 0, -1)
647        current_result.namespace_cleared = true
648      end
649
650      -- We can't use ephemeral extmarks because the buffer updates are not in
651      -- sync with the list of semantic tokens. There's a delay between the
652      -- buffer changing and when the LSP server can respond with updated
653      -- tokens, and we don't want to "blink" the token highlights while
654      -- updates are in flight, and we don't want to use stale tokens because
655      -- they likely won't line up right with the actual buffer.
656      --
657      -- Instead, we have to use normal extmarks that can attach to locations
658      -- in the buffer and are persisted between redraws.
659      --
660      -- `strict = false` is necessary here for the 1% of cases where the
661      -- current result doesn't actually match the buffer contents. Some
662      -- LSP servers can respond with stale tokens on requests if they are
663      -- still processing changes from a didChange notification.
664      --
665      -- LSP servers that do this _should_ follow up known stale responses
666      -- with a refresh notification once they've finished processing the
667      -- didChange notification, which would re-synchronize the tokens from
668      -- our end.
669      --
670      -- The server I know of that does this is clangd when the preamble of
671      -- a file changes and the token request is processed with a stale
672      -- preamble while the new one is still being built. Once the preamble
673      -- finishes, clangd sends a refresh request which lets the client
674      -- re-synchronize the tokens.
675
676      --- @param token STTokenRange
677      --- @param hl_group string
678      --- @param delta integer
679      local function set_mark0(token, hl_group, delta)
680        set_mark(
681          self.bufnr,
682          state.namespace,
683          token,
684          hl_group,
685          vim.hl.priorities.semantic_tokens + delta
686        )
687      end
688
689      local ft = vim.bo[self.bufnr].filetype
690      local highlights = assert(current_result.highlights)
691      local first = vim.list.bisect(highlights, { end_line = topline }, {
692        key = function(highlight)
693          return highlight.end_line
694        end,
695      })
696      local last = vim.list.bisect(highlights, { line = botline }, {
697        lo = first,
698        bound = 'upper',
699        key = function(highlight)
700          return highlight.line
701        end,
702      }) - 1
703
704      --- @type boolean?, integer?
705      local is_folded, foldend
706
707      for i = first, last do
708        local token = assert(highlights[i])
709
710        is_folded, foldend = check_fold(token.line + 1, foldend)
711
712        if not is_folded and not token.marked then
713          set_mark0(token, string.format('@lsp.type.%s.%s', token.type, ft), 0)
714          for modifier in pairs(token.modifiers) do
715            set_mark0(token, string.format('@lsp.mod.%s.%s', modifier, ft), 1)
716            set_mark0(token, string.format('@lsp.typemod.%s.%s.%s', token.type, modifier, ft), 2)
717          end
718          token.marked = true
719
720          api.nvim_exec_autocmds('LspTokenUpdate', {
721            buf = self.bufnr,
722            modeline = false,
723            data = {
724              token = token,
725              client_id = client_id,
726            },
727          })
728        end
729      end
730    end
731  end
732end
733
734--- Reset the buffer's highlighting state and clears the extmark highlights.
735---
736---@package
737---@param client_id integer
738function STHighlighter:reset(client_id)
739  local state = assert(self.client_state[client_id])
740  self:cancel_active_request(client_id)
741  api.nvim_buf_clear_namespace(self.bufnr, state.namespace, 0, -1)
742  state.current_result = {}
743  state.has_full_result = false
744end
745
746--- Mark a client's results as dirty. This method will cancel any active
747--- requests to the server and pause new highlights from being added
748--- in the on_win callback. The rest of the current results are saved
749--- in case the server supports delta requests.
750---
751---@package
752---@param client_id integer
753function STHighlighter:mark_dirty(client_id)
754  local state = assert(self.client_state[client_id])
755
756  -- if we clear the version from current_result, it'll cause the next
757  -- full/delta request to be sent and will also pause new highlights
758  -- from being added in on_win until a new result comes from the server
759  if state.current_result then
760    state.current_result.version = nil
761  end
762
763  -- clearing this flag will also allow range requests to fire to
764  -- potentially get a faster result
765  state.has_full_result = false
766
767  self:cancel_active_request(client_id)
768end
769
770---@package
771---@param client_id integer
772function STHighlighter:debounce_request(client_id)
773  local state = assert(self.client_state[client_id])
774  self:reset_timer(state)
775  if self.debounce > 0 then
776    state.timer = vim.defer_fn(function()
777      self:send_request(client_id)
778    end, self.debounce)
779  else
780    self:send_request(client_id)
781  end
782end
783
784---@private
785---@param state STClientState
786function STHighlighter.reset_timer(_, state)
787  local timer = state.timer
788  if timer then
789    state.timer = nil
790    if not timer:is_closing() then
791      timer:stop()
792      timer:close()
793    end
794  end
795end
796
797--- Start the semantic token highlighting engine for the given buffer with the
798--- given client. The client must already be attached to the buffer.
799---
800--- NOTE: This is currently called automatically by |vim.lsp.buf_attach_client()|. To
801--- opt-out of semantic highlighting with a server that supports it, you can
802--- delete the semanticTokensProvider table from the {server_capabilities} of
803--- your client in your |LspAttach| callback or your configuration's
804--- `on_attach` callback:
805---
806--- ```lua
807--- client.server_capabilities.semanticTokensProvider = nil
808--- ```
809---
810---@deprecated
811---@param bufnr (integer) Buffer number, or `0` for current buffer
812---@param client_id (integer) The ID of the |vim.lsp.Client|
813---@param opts? (table) Optional keyword arguments
814---  - debounce (integer, default: 200): Debounce token requests
815---        to the server by the given number in milliseconds
816function M.start(bufnr, client_id, opts)
817  vim.deprecate('vim.lsp.semantic_tokens.start', 'vim.lsp.semantic_tokens.enable(true)', '0.13.0')
818  vim.validate('bufnr', bufnr, 'number')
819  vim.validate('client_id', client_id, 'number')
820
821  M.enable(true, { bufnr = bufnr, client_id = client_id })
822
823  if opts and opts.debounce and STHighlighter.active[bufnr] then
824    local highlighter = STHighlighter.active[bufnr]
825    local prev = rawget(highlighter, 'debounce')
826    highlighter.debounce = prev and math.max(prev, opts.debounce) or opts.debounce
827  end
828end
829
830--- Stop the semantic token highlighting engine for the given buffer with the
831--- given client.
832---
833---@deprecated
834---@param bufnr (integer) Buffer number, or `0` for current buffer
835---@param client_id (integer) The ID of the |vim.lsp.Client|
836function M.stop(bufnr, client_id)
837  vim.deprecate('vim.lsp.semantic_tokens.stop', 'vim.lsp.semantic_tokens.enable(false)', '0.13.0')
838  M.enable(false, { bufnr = bufnr, client_id = client_id })
839end
840
841--- Query whether semantic tokens is enabled in the {filter}ed scope
842---@param filter? vim.lsp.capability.enable.Filter
843function M.is_enabled(filter)
844  return vim.lsp._capability.is_enabled('semantic_tokens', filter)
845end
846
847--- Enables or disables semantic tokens for the {filter}ed scope.
848---
849--- To "toggle", pass the inverse of `is_enabled()`:
850---
851--- ```lua
852--- vim.lsp.semantic_tokens.enable(not vim.lsp.semantic_tokens.is_enabled())
853--- ```
854---
855---@param enable? boolean true/nil to enable, false to disable
856---@param filter? vim.lsp.capability.enable.Filter
857function M.enable(enable, filter)
858  vim.lsp._capability.enable('semantic_tokens', enable, filter)
859end
860
861--- @nodoc
862--- @class STTokenRangeInspect : STTokenRange
863--- @field client_id integer
864
865--- Return the semantic token(s) at the given position.
866--- If called without arguments, returns the token under the cursor.
867---
868---@param bufnr integer|nil Buffer number (0 for current buffer, default)
869---@param row integer|nil Position row (default cursor position)
870---@param col integer|nil Position column (default cursor position)
871---
872---@return STTokenRangeInspect[]|nil (table|nil) List of tokens at position. Each token has
873---        the following fields:
874---        - line (integer) line number, 0-based
875---        - start_col (integer) start column, 0-based
876---        - end_line (integer) end line number, 0-based
877---        - end_col (integer) end column, 0-based
878---        - type (string) token type as string, e.g. "variable"
879---        - modifiers (table) token modifiers as a set. E.g., { static = true, readonly = true }
880---        - client_id (integer)
881function M.get_at_pos(bufnr, row, col)
882  bufnr = vim._resolve_bufnr(bufnr)
883
884  local highlighter = STHighlighter.active[bufnr]
885  if not highlighter then
886    return
887  end
888
889  if row == nil or col == nil then
890    local cursor = api.nvim_win_get_cursor(0)
891    row, col = cursor[1] - 1, cursor[2]
892  end
893
894  local position = { row, col, row, col }
895
896  local tokens = {} --- @type STTokenRangeInspect[]
897  for client_id, client in pairs(highlighter.client_state) do
898    local highlights = client.current_result.highlights
899    if highlights then
900      local idx = vim.list.bisect(highlights, { end_line = row }, {
901        key = function(highlight)
902          return highlight.end_line
903        end,
904      })
905      for i = idx, #highlights do
906        local token = highlights[i]
907        --- @cast token STTokenRangeInspect
908
909        if token.line > row then
910          break
911        end
912
913        if
914          Range.contains({ token.line, token.start_col, token.end_line, token.end_col }, position)
915        then
916          token.client_id = client_id
917          tokens[#tokens + 1] = token
918        end
919      end
920    end
921  end
922  return tokens
923end
924
925--- Force a refresh of all semantic tokens
926---
927--- Only has an effect if the buffer is currently active for semantic token
928--- highlighting (|vim.lsp.semantic_tokens.enable()| has been called for it)
929---
930---@param bufnr (integer|nil) filter by buffer. All buffers if nil, current
931---       buffer if 0
932function M.force_refresh(bufnr)
933  vim.validate('bufnr', bufnr, 'number', true)
934
935  local buffers = bufnr == nil and vim.tbl_keys(STHighlighter.active)
936    or { vim._resolve_bufnr(bufnr) }
937
938  for _, buffer in ipairs(buffers) do
939    local highlighter = STHighlighter.active[buffer]
940    if highlighter then
941      for client_id, _ in pairs(highlighter.client_state) do
942        highlighter:reset(client_id)
943        highlighter:send_request(client_id)
944      end
945    end
946  end
947end
948
949--- @class vim.lsp.semantic_tokens.highlight_token.Opts
950--- @inlinedoc
951---
952--- Priority for the applied extmark.
953--- (Default: `vim.hl.priorities.semantic_tokens + 3`)
954--- @field priority? integer
955
956--- Highlight a semantic token.
957---
958--- Apply an extmark with a given highlight group for a semantic token. The
959--- mark will be deleted by the semantic token engine when appropriate; for
960--- example, when the LSP sends updated tokens. This function is intended for
961--- use inside |LspTokenUpdate| callbacks.
962---@param token (table) Semantic token, provided as `ev.data.token` in |LspTokenUpdate|
963---@param bufnr (integer) Buffer to highlight, or `0` for current buffer.
964---@param client_id (integer) ID of the |vim.lsp.Client|
965---@param hl_group (string) Highlight group name
966---@param opts? vim.lsp.semantic_tokens.highlight_token.Opts  Optional parameters:
967function M.highlight_token(token, bufnr, client_id, hl_group, opts)
968  bufnr = vim._resolve_bufnr(bufnr)
969  local highlighter = STHighlighter.active[bufnr]
970  if not highlighter then
971    return
972  end
973
974  local state = highlighter.client_state[client_id]
975  if not state then
976    return
977  end
978
979  local priority = opts and opts.priority or vim.hl.priorities.semantic_tokens + 3
980
981  set_mark(bufnr, state.namespace, token, hl_group, priority)
982end
983
984--- |lsp-handler| for the method `workspace/semanticTokens/refresh`
985---
986--- Refresh requests are sent by the server to indicate a project-wide change
987--- that requires all tokens to be re-requested by the client. This handler will
988--- invalidate the current results of all buffers and automatically kick off a
989--- new request for buffers that are displayed in a window. For those that aren't,
990--- the BufWinEnter event should take care of it next time it's displayed.
991---@param err lsp.ResponseError?
992---@param ctx lsp.HandlerContext
993function M._refresh(err, _, ctx)
994  if err then
995    return vim.NIL
996  end
997
998  for bufnr, highlighter in pairs(STHighlighter.active) do
999    if highlighter.client_state[ctx.client_id] then
1000      highlighter:mark_dirty(ctx.client_id)
1001
1002      if not vim.tbl_isempty(vim.fn.win_findbuf(bufnr)) then
1003        -- some LSPs send rapid fire refresh notifications, so we'll debounce them with debounce_request()
1004        highlighter:debounce_request(ctx.client_id)
1005      end
1006    end
1007  end
1008
1009  return vim.NIL
1010end
1011
1012-- Semantic tokens is enabled by default
1013M.enable(true)
1014
1015--- for testing only! there is no guarantee of API stability with this!
1016---
1017---@private
1018M.__STHighlighter = STHighlighter
1019
1020return M