robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
46.3 KiB1436 linesraw
1--- @brief
2--- The `vim.lsp.completion` module enables insert-mode completion driven by an LSP server. Call
3--- `enable()` to make it available through Nvim builtin completion (via the |CompleteDone| event).
4--- Specify `autotrigger=true` to activate "auto-completion" when you type any of the server-defined
5--- `triggerCharacters`. Use CTRL-Y to select an item from the completion menu. |complete_CTRL-Y|
6---
7--- Example: activate LSP-driven auto-completion:
8--- ```lua
9--- -- Works best if 'completeopt' has "noselect".
10--- -- Use CTRL-Y to select an item. |complete_CTRL-Y|
11--- vim.cmd[[set completeopt+=menuone,noselect,popup]]
12--- vim.lsp.start({
13---   name = 'ts_ls',
14---   cmd = …,
15---   on_attach = function(client, bufnr)
16---     vim.lsp.completion.enable(true, client.id, bufnr, {
17---       autotrigger = true,
18---       convert = function(item)
19---         return { abbr = item.label:gsub('%b()', '') }
20---       end,
21---     })
22---   end,
23--- })
24--- ```
25---
26--- [lsp-autocompletion]()
27---
28--- The LSP `triggerCharacters` field decides when to trigger autocompletion. If you want to trigger
29--- on EVERY keypress you can either:
30--- - Extend `client.server_capabilities.completionProvider.triggerCharacters` on `LspAttach`,
31---   before you call `vim.lsp.completion.enable(… {autotrigger=true})`. See the |lsp-attach| example.
32--- - Call `vim.lsp.completion.get()` from an |InsertCharPre| autocommand.
33---
34--- If the server provides `commitCharacters` for a completion item, typing one
35--- of those characters while the item is selected accepts the completion and
36--- then inserts the character. To disable this:
37---
38--- ```lua
39--- vim.lsp.completion.enable(true, client_id, bufnr, { commit_characters = false })
40--- ```
41
42local M = {}
43
44local api = vim.api
45local nvim_on = require('vim._core.util').nvim_on
46local lsp = vim.lsp
47local protocol = lsp.protocol
48
49local rtt_ms = 50.0
50local ns_to_ms = 0.000001
51
52--- @alias vim.lsp.CompletionResult lsp.CompletionList | lsp.CompletionItem[]
53
54-- TODO(mariasolos): Remove this declaration once we figure out a better way to handle
55-- literal/anonymous types (see https://github.com/neovim/neovim/pull/27542/files#r1495259331).
56--- @nodoc
57--- @class lsp.ItemDefaults
58--- @field commitCharacters string[]?
59--- @field editRange lsp.Range | { insert: lsp.Range, replace: lsp.Range } | nil
60--- @field insertTextFormat lsp.InsertTextFormat?
61--- @field insertTextMode lsp.InsertTextMode?
62--- @field data any
63
64--- @nodoc
65--- @class vim.lsp.completion.BufHandle
66--- @field clients table<integer, vim.lsp.Client>
67--- @field triggers table<string, vim.lsp.Client[]>
68--- @field convert? fun(item: lsp.CompletionItem): table
69
70--- @type table<integer, vim.lsp.completion.BufHandle>
71local buf_handles = {}
72
73--- @nodoc
74--- @class vim.lsp.completion.Context
75local Context = {
76  cursor = nil, --- @type [integer, integer]?
77  last_request_time = nil, --- @type integer?
78  pending_requests = {}, --- @type function[]
79  isIncomplete = false,
80  -- Handles "completionItem/resolve".
81  resolve_handler = nil, --- @type CompletionResolver?
82}
83
84--- @nodoc
85function Context:cancel_pending()
86  for _, cancel in ipairs(self.pending_requests) do
87    cancel()
88  end
89
90  self.pending_requests = {}
91end
92
93--- @nodoc
94function Context:reset()
95  -- Note that the cursor isn't reset here, it needs to survive a `CompleteDone` event.
96  self.isIncomplete = false
97  self.last_request_time = nil
98  self:cancel_pending()
99  if self.resolve_handler then
100    self.resolve_handler:cleanup()
101    self.resolve_handler = nil
102  end
103end
104
105--- @type uv.uv_timer_t?
106local completion_timer = nil
107
108--- @return uv.uv_timer_t
109local function new_timer()
110  return (assert(vim.uv.new_timer()))
111end
112
113local function reset_timer()
114  if completion_timer then
115    completion_timer:stop()
116    completion_timer:close()
117  end
118
119  completion_timer = nil
120end
121
122--- @param window integer
123--- @param warmup integer
124--- @return fun(sample: number): number
125local function exp_avg(window, warmup)
126  local count = 0
127  local sum = 0
128  local value = 0.0
129
130  return function(sample)
131    if count < warmup then
132      count = count + 1
133      sum = sum + sample
134      value = sum / count
135    else
136      local factor = 2.0 / (window + 1)
137      value = value * (1 - factor) + sample * factor
138    end
139    return value
140  end
141end
142local compute_new_average = exp_avg(10, 10)
143
144--- Calculates the adaptive debounce time based on the elapsed time since the last request.
145---
146--- @param last_request_time integer?
147--- @param current_rtt_ms number
148--- @return number
149local function adaptive_debounce(last_request_time, current_rtt_ms)
150  if not last_request_time then
151    return current_rtt_ms
152  end
153  local ms_since_request = (vim.uv.hrtime() - last_request_time) * ns_to_ms
154  return math.max((ms_since_request - current_rtt_ms) * -1, 0)
155end
156
157--- @param flag string
158--- @return boolean
159local function has_completeopt(flag)
160  return vim.list_contains(vim.opt.completeopt:get() --[[@as string[] ]], flag)
161end
162
163--- @param s string?
164--- @return string?
165local function nonempty(s)
166  return s ~= '' and s or nil
167end
168
169--- @param input string Unparsed snippet
170--- @return string # Parsed snippet if successful, else returns its input
171local function parse_snippet(input)
172  local ok, parsed = pcall(function()
173    return lsp._snippet_grammar.parse(input)
174  end)
175  return ok and tostring(parsed) or input
176end
177
178--- @param item lsp.CompletionItem
179local function apply_snippet(item)
180  if item.textEdit then
181    vim.snippet.expand(item.textEdit.newText)
182  elseif item.insertText then
183    vim.snippet.expand(item.insertText)
184  end
185end
186
187--- @param item lsp.CompletionItem
188--- @param word string
189--- @param prefix string
190--- @param match fun(word: string, prefix: string): boolean
191local function fallback_filtertext(item, word, prefix, match)
192  if item.filterText and not match(word, prefix) and match(item.filterText, prefix) then
193    return item.filterText
194  end
195  return word
196end
197
198--- Returns text that should be inserted when a selecting completion item. The
199--- precedence is as follows: textEdit.newText > insertText > label
200---
201--- See https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion
202---
203--- @param item lsp.CompletionItem
204--- @param prefix string
205--- @param match fun(text: string, prefix: string):boolean
206--- @return string
207local function get_completion_word(item, prefix, match)
208  if item.insertTextFormat == protocol.InsertTextFormat.Snippet then
209    if item.textEdit or (item.insertText and item.insertText ~= '') then
210      -- Use label instead of text if text has different starting characters.
211      -- label is used as abbr (=displayed), but word is used for filtering
212      -- This is required for things like postfix completion.
213      -- E.g. in lua:
214      --
215      --    local f = {}
216      --    f@|
217      --      ▲
218      --      └─ cursor
219      --
220      --    item.textEdit.newText: table.insert(f, $0)
221      --    label: insert
222      --
223      -- Typing `i` would remove the candidate because newText starts with `t`.
224      local text = parse_snippet(nonempty(item.insertText) or assert(item.textEdit).newText)
225      local filter_text = nonempty(item.filterText)
226      local word = #text < #item.label and vim.fn.matchstr(text, '\\k*')
227        or (filter_text and vim.fn.match(item.label, '^\\k') == -1 and filter_text or item.label)
228      return fallback_filtertext(item, word, prefix, match)
229    else
230      return item.label
231    end
232  elseif item.textEdit then
233    local word = item.textEdit.newText
234    word = string.gsub(word, '\r\n?', '\n')
235    word = word:match('([^\n]*)') or word
236    return fallback_filtertext(item, word, prefix, match)
237  elseif item.insertText and item.insertText ~= '' then
238    local word = string.gsub(item.insertText, '\r\n?', '\n')
239    word = word:match('([^\n]*)') or word
240    return fallback_filtertext(item, word, prefix, match)
241  end
242  return item.label
243end
244
245--- Applies the given defaults to the completion item, modifying it in place.
246---
247--- @param item lsp.CompletionItem
248--- @param defaults lsp.ItemDefaults?
249--- @param apply_kind lsp.CompletionItemApplyKinds?
250local function apply_defaults(item, defaults, apply_kind)
251  if not defaults then
252    return
253  end
254
255  -- Unset means Replace for every field.
256  apply_kind = apply_kind or {}
257
258  local merge = apply_kind.commitCharacters == protocol.ApplyKind.Merge
259    and defaults.commitCharacters
260
261  item.commitCharacters = merge
262      -- No dedup, it ends up as a flat string anyway.
263      and vim.list_extend(item.commitCharacters or {}, merge)
264    -- An empty list means no commit chars, not use the defaults.
265    or (item.commitCharacters or defaults.commitCharacters)
266
267  item.insertTextFormat = item.insertTextFormat or defaults.insertTextFormat
268  item.insertTextMode = item.insertTextMode or defaults.insertTextMode
269
270  item.data = apply_kind.data == protocol.ApplyKind.Merge
271      and type(defaults.data) == 'table'
272      and type(item.data) == 'table'
273      and vim.tbl_extend('force', defaults.data, item.data)
274    or vim.nonnil(item.data, defaults.data)
275
276  if defaults.editRange then
277    local textEdit = item.textEdit or {}
278    item.textEdit = textEdit --[[@as lsp.TextEdit|lsp.InsertReplaceEdit]]
279    textEdit.newText = textEdit.newText
280      or item.textEditText
281      or nonempty(item.insertText)
282      or item.label
283    if defaults.editRange.start then
284      textEdit.range = textEdit.range or defaults.editRange
285    elseif defaults.editRange.insert then
286      textEdit.insert = defaults.editRange.insert
287      textEdit.replace = defaults.editRange.replace
288    end
289  end
290end
291
292--- @param result vim.lsp.CompletionResult
293--- @return lsp.CompletionItem[]
294local function get_items(result)
295  if result.items then
296    -- When we have a list, apply the defaults and return an array of items.
297    for _, item in ipairs(result.items) do
298      ---@diagnostic disable-next-line: param-type-mismatch
299      apply_defaults(item, result.itemDefaults, result.applyKind)
300    end
301    result.itemDefaults = nil
302    return result.items
303  else
304    -- Else just return the items as they are.
305    ---@cast result lsp.CompletionItem[]
306    return result
307  end
308end
309
310---Returns an item's documentation value and its markup kind.
311---@param item lsp.CompletionItem
312---@return string
313---@return lsp.MarkupKind
314local function get_doc(item)
315  local doc = item.documentation
316  local default_kind = protocol.MarkupKind.Markdown
317  if not doc then
318    return '', default_kind
319  end
320  if type(doc) == 'string' then
321    return doc, default_kind
322  end
323  if type(doc) == 'table' and type(doc.value) == 'string' then
324    return doc.value, doc.kind
325  end
326
327  vim.notify('invalid documentation value: ' .. vim.inspect(doc), vim.log.levels.WARN)
328  return '', default_kind
329end
330
331---@return fun(value: string, prefix: string): boolean, integer?
332local function item_matcher()
333  local fuzzy = has_completeopt('fuzzy')
334  local ignorecase, smartcase = vim.o.ignorecase, vim.o.smartcase
335  return function(value, prefix)
336    if prefix == '' then
337      return true, nil
338    end
339    if fuzzy then
340      local score = vim.fn.matchfuzzypos({ value }, prefix)[3] ---@type table
341      return #score > 0, score[1]
342    end
343
344    if ignorecase and (not smartcase or not prefix:find('%u')) then
345      return vim.startswith(value:lower(), prefix:lower()), nil
346    end
347    return vim.startswith(value, prefix), nil
348  end
349end
350
351--- Generate kind text for completion color items
352--- Parse color from doc and return colored symbol ■
353---
354---@param item table completion item with kind and documentation
355---@return string? kind text or "■" for colors
356---@return string? highlight group for colors
357local function generate_kind(item)
358  if not protocol.CompletionItemKind[item.kind] then
359    return 'Unknown'
360  end
361  if item.kind ~= protocol.CompletionItemKind.Color then
362    return protocol.CompletionItemKind[item.kind] --[[@as string]]
363  end
364  local doc = get_doc(item)
365  if #doc == 0 then
366    return
367  end
368
369  -- extract hex from RGB format
370  local r, g, b = doc:match('rgb%((%d+)%s*,?%s*(%d+)%s*,?%s*(%d+)%)')
371  local hex = r
372      and string.format(
373        '%02x%02x%02x',
374        vim._assert_integer(r),
375        vim._assert_integer(g),
376        vim._assert_integer(b)
377      )
378    or doc:match('#?([%da-fA-F]+)')
379
380  if not hex then
381    return
382  end
383
384  -- expand 3-digit hex to 6-digit
385  if #hex == 3 then
386    hex = hex:gsub('.', '%1%1')
387  end
388
389  if #hex ~= 6 then
390    return
391  end
392
393  hex = hex:lower()
394  local group = ('@lsp.color.%s'):format(hex)
395  if next(api.nvim_get_hl(0, { name = group })) == nil then
396    api.nvim_set_hl(0, group, { fg = '#' .. hex })
397  end
398
399  return '■', group
400end
401
402---Returns the [complete-items] info for an LSP completion item, its markup kind, and whether the
403---info is complete.
404---The info is complete when all of the fields of the item required to build it are present. If the
405---info is not complete, resolving the item (via completionItem/resolve) may populate the missing
406---fields.
407---@param item lsp.CompletionItem
408---@param popup boolean 'completeopt' has "popup"
409---@return string
410---@return lsp.MarkupKind
411---@return boolean complete
412local function complete_item_info(item, popup)
413  local info, kind = get_doc(item)
414
415  if item.detail and item.detail ~= '' then
416    local detail_block = ('```%s\n%s\n```'):format(vim.bo.filetype, item.detail)
417    if info == '' then
418      info = detail_block
419    elseif not info:find(item.detail, 1, true) then
420      info = detail_block .. '\n' .. info
421    end
422  end
423
424  if info == '' and popup and item.insertTextFormat == protocol.InsertTextFormat.Snippet then
425    local text = item.insertText or (item.textEdit and item.textEdit.newText)
426    if text then
427      local snippet = parse_snippet(text)
428      info = ('```%s\n%s\n```'):format(vim.bo.filetype, snippet)
429    end
430  end
431
432  local complete = item.detail ~= nil and item.documentation ~= nil
433  return info, kind, complete
434end
435
436--- Flatten commitCharacters array to a string; keep only the first codepoint
437--- of each entry.
438---
439--- @param chars string[]
440--- @return string
441local function commit_chars_str(chars)
442  if type(chars) ~= 'table' then
443    return ''
444  end
445  local result = {} --- @type string[]
446  for _, ch in ipairs(chars) do
447    -- commit characters "should have `length=1`" and superfluous
448    -- characters are ignored.  Keep the first codepoint.
449    local b = type(ch) == 'string' and ch:byte(1)
450    if b and b ~= 0 then
451      local n = vim.str_utf_end(ch, 1)
452      -- Only whole characters: multibyte fragments pair up across entries, NUL truncates.
453      if b < 0x80 or n > 0 then
454        result[#result + 1] = ch:sub(1, 1 + n)
455      end
456    end
457  end
458  return table.concat(result)
459end
460
461--- @param item lsp.CompletionItem
462--- @param lnum integer
463--- @return integer?
464local function edit_start_char(item, lnum)
465  local edit = item.textEdit
466  if not edit then
467    return nil
468  elseif edit.range and edit.range.start.line == lnum then
469    return edit.range.start.character
470  elseif edit.insert and edit.insert.start.line == lnum then
471    return edit.insert.start.character
472  end
473end
474
475--- Completion options for a buffer, fields from a dynamic registration.
476---
477--- @param client vim.lsp.Client
478--- @param bufnr integer
479--- @return lsp.CompletionOptions
480local function completion_options(client, bufnr)
481  local static = client.server_capabilities.completionProvider or {}
482  for _, reg in ipairs(client:_get_registrations('completionProvider', bufnr) or {}) do
483    local opts = reg.registerOptions
484    if type(opts) == 'table' then
485      return vim.tbl_extend('keep', opts, static)
486    end
487  end
488  return static
489end
490
491--- Turns the result of a `textDocument/completion` request into vim-compatible
492--- |complete-items|.
493---
494--- @param result vim.lsp.CompletionResult Result of `textDocument/completion`
495--- @param prefix string prefix to filter the completion items
496--- @param client_id integer? Client ID
497--- @param server_start_boundary integer? server start boundary
498--- @param line string? current line content
499--- @param lnum integer? 0-indexed line number
500--- @param encoding? 'utf-8'|'utf-16'|'utf-32' encoding
501--- @param default_start_byte integer? 0-indexed start byte for items without an edit range
502--- @return table[]
503--- @see complete-items
504function M._lsp_to_complete_items(
505  result,
506  prefix,
507  client_id,
508  server_start_boundary,
509  line,
510  lnum,
511  encoding,
512  default_start_byte
513)
514  local items = get_items(result)
515  if vim.tbl_isempty(items) then
516    return {}
517  end
518
519  local match_item_by_value = item_matcher()
520  local popup = has_completeopt('popup')
521  ---@type fun(item: lsp.CompletionItem, item_prefix: string): boolean, integer?
522  local matches
523  if not prefix:find('%w') then
524    matches = function(_, _)
525      return true
526    end
527  else
528    ---@param item lsp.CompletionItem
529    ---@param item_prefix string text the item replaces, up to the cursor
530    matches = function(item, item_prefix)
531      local filter_text = nonempty(item.filterText)
532      if filter_text then
533        return match_item_by_value(filter_text, item_prefix)
534      end
535
536      if item.textEdit and not item.textEdit.newText then
537        -- server took care of filtering
538        return true
539      end
540
541      return match_item_by_value(item.label, item_prefix)
542    end
543  end
544
545  local candidates = {}
546  local bufnr = api.nvim_get_current_buf()
547  local user_convert = vim.tbl_get(buf_handles, bufnr, 'convert')
548  local user_cmp = vim.tbl_get(buf_handles, bufnr, 'cmp')
549  local client = client_id and lsp.get_client_by_id(client_id)
550  local server_supports_resolve = client
551    and completion_options(client, bufnr).resolveProvider == true
552  local use_commit = vim.tbl_get(buf_handles, bufnr, 'commit_characters') ~= false
553  local commit_support = client
554    and vim.tbl_get(
555      client.capabilities,
556      'textDocument',
557      'completion',
558      'completionItem',
559      'commitCharactersSupport'
560    )
561
562  local all_commit_chars = client and completion_options(client, bufnr).allCommitCharacters
563  local all_commit_str = all_commit_chars and commit_chars_str(all_commit_chars) or nil
564
565  for _, item in ipairs(items) do
566    local pad, item_prefix = '', prefix
567    if server_start_boundary and line and lnum and encoding then
568      local start_char = edit_start_char(item, lnum)
569      local start_byte = start_char and vim.str_byteindex(line, encoding, start_char, false)
570        or default_start_byte
571      if start_byte and start_byte > server_start_boundary then
572        pad = line:sub(server_start_boundary + 1, start_byte)
573        item_prefix = prefix:sub(#pad + 1)
574      end
575    end
576
577    local match, score = matches(item, item_prefix)
578    if match then
579      local word = pad .. get_completion_word(item, item_prefix, match_item_by_value)
580
581      local hl_group = ''
582      if
583        ---@diagnostic disable-next-line: deprecated
584        item.deprecated
585        or vim.list_contains((item.tags or {}), protocol.CompletionTag.Deprecated)
586      then
587        hl_group = 'DiagnosticDeprecated'
588      end
589      local kind, kind_hlgroup = generate_kind(item)
590      local info, info_kind, info_complete = complete_item_info(item, popup)
591      local commit_chars --- @type string?
592      if use_commit then
593        if commit_support and item.commitCharacters then
594          -- may be '': an explicit empty list also suppresses allCommitCharacters
595          commit_chars = commit_chars_str(item.commitCharacters)
596        else
597          commit_chars = all_commit_str
598        end
599      end
600      local completion_item = {
601        word = word,
602        abbr = ('%s%s'):format(item.label, vim.tbl_get(item, 'labelDetails', 'detail') or ''),
603        kind = kind,
604        menu = vim.tbl_get(item, 'labelDetails', 'description') or '',
605        info = info,
606        icase = 1,
607        dup = 1,
608        empty = 1,
609        abbr_hlgroup = hl_group,
610        kind_hlgroup = kind_hlgroup,
611        preselect = item.preselect,
612        commit_chars = commit_chars,
613        user_data = {
614          nvim = {
615            lsp = {
616              completion_item = item,
617              info_kind = info_kind,
618              completion_item_needs_resolving = server_supports_resolve and not info_complete,
619              client_id = client_id,
620            },
621          },
622        },
623        _fuzzy_score = score,
624      }
625      if user_convert then
626        completion_item = vim.tbl_extend('keep', user_convert(item), completion_item)
627      end
628      table.insert(candidates, completion_item)
629    end
630  end
631
632  if not user_cmp then
633    --- @param a { user_data: { nvim: { lsp: { completion_item: lsp.CompletionItem } } } }
634    --- @param b { user_data: { nvim: { lsp: { completion_item: lsp.CompletionItem } } } }
635    local function compare_by_sortText_and_label(a, b)
636      local itema = a.user_data.nvim.lsp.completion_item
637      local itemb = b.user_data.nvim.lsp.completion_item
638      return (nonempty(itema.sortText) or itema.label) < (nonempty(itemb.sortText) or itemb.label)
639    end
640
641    local use_fuzzy_sort = has_completeopt('fuzzy')
642      and not has_completeopt('nosort')
643      and not result.isIncomplete
644      and #prefix > 0
645
646    local compare_fn = use_fuzzy_sort
647        and function(a, b)
648          local score_a = a._fuzzy_score or 0
649          local score_b = b._fuzzy_score or 0
650          if score_a ~= score_b then
651            return score_a > score_b
652          end
653          return compare_by_sortText_and_label(a, b)
654        end
655      or compare_by_sortText_and_label
656
657    table.sort(candidates, compare_fn)
658  end
659  return candidates
660end
661
662--- @param lnum integer 0-indexed
663--- @param line string
664--- @param items lsp.CompletionItem[]
665--- @param encoding 'utf-8'|'utf-16'|'utf-32'
666--- @return integer?
667local function adjust_start_col(lnum, line, items, encoding)
668  local min_start_char = nil
669  for _, item in pairs(items) do
670    local start_char = edit_start_char(item, lnum)
671    if start_char and (not min_start_char or start_char < min_start_char) then
672      min_start_char = start_char
673    end
674  end
675  if min_start_char then
676    return vim.str_byteindex(line, encoding, min_start_char, false)
677  else
678    return nil
679  end
680end
681
682--- @param line string line content
683--- @param lnum integer 0-indexed line number
684--- @param cursor_col integer
685--- @param client_id integer client ID
686--- @param client_start_boundary integer 0-indexed word boundary
687--- @param server_start_boundary? integer 0-indexed word boundary, based on textEdit.range.start.character
688--- @param result vim.lsp.CompletionResult
689--- @param encoding 'utf-8'|'utf-16'|'utf-32'
690--- @return table[] matches
691--- @return integer? server_start_boundary
692function M._convert_results(
693  line,
694  lnum,
695  cursor_col,
696  client_id,
697  client_start_boundary,
698  server_start_boundary,
699  result,
700  encoding
701)
702  -- Completion response items may be relative to a position different than `client_start_boundary`.
703  -- Concrete example, with lua-language-server:
704  --
705  -- require('plenary.asy|
706  --         ▲       ▲   ▲
707  --         │       │   └── cursor_pos:                     20
708  --         │       └────── client_start_boundary:          17
709  --         └────────────── textEdit.range.start.character: 9
710  --                                 .newText = 'plenary.async'
711  --                  ^^^
712  --                  prefix (We'd remove everything not starting with `asy`,
713  --                  so we'd eliminate the `plenary.async` result
714  --
715  -- `adjust_start_col` is used to prefer the language server boundary.
716  --
717  local candidates = get_items(result)
718  local curstartbyte = adjust_start_col(lnum, line, candidates, encoding)
719  if server_start_boundary == nil then
720    server_start_boundary = curstartbyte
721  elseif curstartbyte ~= nil and curstartbyte ~= server_start_boundary then
722    server_start_boundary = client_start_boundary
723  end
724  local prefix = line:sub((server_start_boundary or client_start_boundary) + 1, cursor_col)
725  local default_start_byte = curstartbyte and client_start_boundary or nil
726  local matches = M._lsp_to_complete_items(
727    result,
728    prefix,
729    client_id,
730    server_start_boundary,
731    line,
732    lnum,
733    encoding,
734    default_start_byte
735  )
736
737  return matches, server_start_boundary
738end
739
740-- NOTE: The reason we don't use `lsp.buf_request_all` here is because we want to filter the clients
741-- that received the request based on the trigger characters.
742--- @param clients table<integer, vim.lsp.Client> # keys != client_id
743--- @param bufnr integer
744--- @param win integer
745--- @param ctx? lsp.CompletionContext
746--- @param callback fun(responses: table<integer, { err: lsp.ResponseError, result: vim.lsp.CompletionResult }>)
747--- @return function # Cancellation function
748local function request(clients, bufnr, win, ctx, callback)
749  local responses = {} --- @type table<integer, { err: lsp.ResponseError, result: any }>
750  local request_ids = {} --- @type table<integer, integer>
751  local remaining_requests = vim.tbl_count(clients)
752
753  for _, client in pairs(clients) do
754    local client_id = client.id
755    local params = lsp.util.make_position_params(win, client.offset_encoding)
756    --- @cast params lsp.CompletionParams
757    params.context = ctx
758    local ok, request_id = client:request('textDocument/completion', params, function(err, result)
759      responses[client_id] = { err = err, result = result }
760      remaining_requests = remaining_requests - 1
761      if remaining_requests == 0 then
762        callback(responses)
763      end
764    end, bufnr)
765
766    if ok then
767      request_ids[client_id] = request_id
768    end
769  end
770
771  return function()
772    for client_id, request_id in pairs(request_ids) do
773      local client = lsp.get_client_by_id(client_id)
774      if client then
775        client:cancel_request(request_id)
776      end
777    end
778  end
779end
780
781---@param bufnr integer
782---@return string
783local function get_augroup(bufnr)
784  return string.format('nvim.lsp.completion_%d', bufnr)
785end
786
787--- Updates the completion preview popup: configures conceal level, applies Treesitter or
788--- fallback syntax, and resizes height to fit content
789---
790--- @param winid integer
791--- @param bufnr integer
792--- @param kind? string
793local function update_popup_window(winid, bufnr, kind)
794  if winid and api.nvim_win_is_valid(winid) and bufnr and api.nvim_buf_is_valid(bufnr) then
795    if kind == protocol.MarkupKind.Markdown then
796      vim.wo[winid].conceallevel = 2
797      vim.treesitter.start(bufnr, kind)
798    end
799    local all = api.nvim_win_text_height(winid).all
800    api.nvim_win_resize(winid, -1, all)
801  end
802end
803
804--- Handles the LSP "completionItem/resolve"
805---
806--- @nodoc
807--- @class CompletionResolver
808--- @field timer uv.uv_timer_t? Timer used for debouncing
809--- @field bufnr integer? Buffer number for which the resolution is triggered
810--- @field word string? Word being completed
811--- @field last_request_time integer? Last request timestamp
812--- @field doc_rtt_ms number Last request timestamp
813--- @field doc_compute_new_average fun(sample: number): number Last request timestamp
814local CompletionResolver = {}
815CompletionResolver.__index = CompletionResolver
816
817--- @nodoc
818---
819--- Creates a new instance of `resolve_completion_item`.
820---
821--- @return CompletionResolver
822function CompletionResolver.new()
823  local self = setmetatable({}, CompletionResolver)
824  self.timer = nil
825  self.bufnr = nil
826  self.word = nil
827  self.last_request_time = nil
828  self.doc_rtt_ms = 100
829  self.doc_compute_new_average = exp_avg(10, 5)
830  return self
831end
832
833--- @nodoc
834---
835--- Cancels any pending requests.
836function CompletionResolver:cancel_pending_requests()
837  if self.bufnr then
838    lsp.util._cancel_requests({
839      method = 'completionItem/resolve',
840      bufnr = self.bufnr,
841    })
842  end
843end
844
845--- @nodoc
846---
847--- Cleans up the timer and cancels any ongoing requests.
848function CompletionResolver:cleanup()
849  if self.timer and not self.timer:is_closing() then
850    self.timer:stop()
851    self.timer:close()
852  end
853  self.timer = nil
854  self:cancel_pending_requests()
855end
856
857--- @nodoc
858---
859--- Checks if the completionItem/resolve request is valid by ensuring the buffer
860--- and word are valid.
861---
862--- @return boolean, table Validity of the request and the completion info
863function CompletionResolver:is_valid()
864  local cmp_info = vim.fn.complete_info({ 'selected', 'completed' })
865  return self.bufnr ~= nil
866    and api.nvim_buf_is_valid(self.bufnr)
867    and api.nvim_get_current_buf() == self.bufnr
868    and vim.startswith(api.nvim_get_mode().mode, 'i')
869    and vim.fn.pumvisible() ~= 0
870    and (vim.tbl_get(cmp_info, 'completed', 'word') or '') == self.word,
871    cmp_info
872end
873
874--- @nodoc
875---
876--- Invokes and handles "completionItem/resolve".
877---
878--- @param bufnr integer The buffer number where the request is triggered
879--- @param param table The parameters for the LSP request
880--- @param selected_word string The word being completed
881function CompletionResolver:request(bufnr, param, selected_word)
882  self:cleanup()
883
884  self.bufnr = bufnr
885  self.word = selected_word
886  local debounce_time = adaptive_debounce(self.last_request_time, self.doc_rtt_ms)
887
888  self.timer = vim.defer_fn(function()
889    local valid, cmp_info = self:is_valid()
890    if not valid then
891      self:cleanup()
892      return
893    end
894    self:cancel_pending_requests()
895
896    local client_id = vim.tbl_get(cmp_info.completed, 'user_data', 'nvim', 'lsp', 'client_id')
897    local client = client_id and lsp.get_client_by_id(client_id)
898    -- completionItem/resolve is not registrable, so supports_method() would
899    -- only see the static capability.
900    if not client or not completion_options(client, bufnr).resolveProvider then
901      return
902    end
903
904    local start_time = vim.uv.hrtime()
905    self.last_request_time = start_time
906
907    ---@param result lsp.CompletionItem
908    client:request('completionItem/resolve', param, function(err, result)
909      local end_time = vim.uv.hrtime()
910      local response_time = (end_time - start_time) * ns_to_ms
911      self.doc_rtt_ms = self.doc_compute_new_average(response_time)
912
913      if err or not result or next(result) == nil then
914        if err then
915          vim.notify(err.message, vim.log.levels.WARN)
916        end
917        return
918      end
919
920      valid, cmp_info = self:is_valid()
921      if not valid then
922        return
923      end
924
925      local info, kind = complete_item_info(result, has_completeopt('popup'))
926      if info ~= '' and info ~= cmp_info.completed.info then
927        local windata = api.nvim__complete_set(cmp_info.selected, { info = info })
928        update_popup_window(windata.winid, windata.bufnr, kind)
929      end
930    end, bufnr)
931  end, math.floor(debounce_time))
932end
933
934--- Defines a CompleteChanged handler to highlight the completion info popup and request/display LSP
935--- completion item documentation via completionItem/resolve
936--- @param group string
937--- @param bufnr integer
938local function on_completechanged(group, bufnr)
939  nvim_on('CompleteChanged', group, {
940    buf = bufnr,
941    desc = 'Highlight completion info popup and request/display LSP completion item documentation via completionItem/resolve',
942  }, function(ev)
943    local completed_item = vim.v.event.completed_item or {}
944    local user_data = vim.tbl_get(completed_item, 'user_data', 'nvim', 'lsp')
945    if not user_data then
946      return
947    end
948    if (completed_item.info or '') ~= '' then
949      local data = vim.fn.complete_info({ 'selected' })
950      update_popup_window(data.preview_winid, data.preview_bufnr, user_data.info_kind)
951    end
952
953    if user_data.completion_item_needs_resolving then
954      Context.resolve_handler = Context.resolve_handler or CompletionResolver.new()
955      Context.resolve_handler:request(
956        ev.buf,
957        user_data.completion_item,
958        assert(completed_item.word)
959      )
960    end
961  end)
962end
963
964local function on_complete_done()
965  local completed_item = api.nvim_get_vvar('completed_item')
966  if not completed_item or not completed_item.user_data or not completed_item.user_data.nvim then
967    Context:reset()
968    return
969  end
970
971  local cursor_row, cursor_col = unpack(api.nvim_win_get_cursor(0)) --- @type integer, integer
972  cursor_row = cursor_row - 1
973  local completion_item = completed_item.user_data.nvim.lsp.completion_item --- @type lsp.CompletionItem
974  local client_id = completed_item.user_data.nvim.lsp.client_id --- @type integer
975  if not completion_item or not client_id then
976    Context:reset()
977    return
978  end
979
980  local bufnr = api.nvim_get_current_buf()
981  local expand_snippet = completion_item.insertTextFormat == protocol.InsertTextFormat.Snippet
982    and (completion_item.textEdit ~= nil or completion_item.insertText ~= nil)
983
984  Context:reset()
985
986  local client = lsp.get_client_by_id(client_id)
987  if not client then
988    return
989  end
990
991  local position_encoding = client.offset_encoding or 'utf-16'
992  local resolve_provider = completion_options(client, bufnr).resolveProvider
993
994  -- Keep reference to avoid race where completion/resolve response arrives after on_insert_leave
995  -- and Context.cursor got cleared before clear_word() gets called
996  local context_cursor = assert(Context.cursor)
997
998  local function clear_word()
999    if not expand_snippet then
1000      return nil
1001    end
1002
1003    -- Remove the already inserted word.
1004    api.nvim_buf_set_text(
1005      bufnr,
1006      context_cursor[1] - 1,
1007      context_cursor[2] - 1,
1008      cursor_row,
1009      cursor_col,
1010      { '' }
1011    )
1012  end
1013
1014  local function exec_command()
1015    local command = completion_item.command
1016    if command then
1017      client:exec_cmd(command, { bufnr = bufnr })
1018    end
1019  end
1020
1021  --- @param edits lsp.TextEdit[]
1022  local function apply_additional_edits(edits)
1023    -- The edits can move the cursor; keep it where it was.
1024    lsp.util.apply_text_edits(edits, bufnr, position_encoding, nil, { keep_cursor = true })
1025  end
1026
1027  clear_word()
1028
1029  local edits = completion_item.additionalTextEdits
1030  local has_edits = edits ~= nil and next(edits) ~= nil
1031  if has_edits then
1032    apply_additional_edits(assert(edits))
1033  end
1034  if expand_snippet then
1035    apply_snippet(completion_item)
1036  end
1037
1038  -- Nothing to gain if the item carried its edits, or it cannot be resolved.
1039  if has_edits or not resolve_provider or type(completion_item) ~= 'table' then
1040    exec_command()
1041    return
1042  end
1043
1044  --- @param result lsp.CompletionItem
1045  client:request('completionItem/resolve', completion_item, function(err, result)
1046    if not api.nvim_buf_is_valid(bufnr) then
1047      return
1048    end
1049    if err then
1050      vim.notify_once(err.message, vim.log.levels.WARN)
1051    elseif result then
1052      if result.additionalTextEdits then
1053        apply_additional_edits(result.additionalTextEdits)
1054      end
1055      -- A resolved command replaces the one the item came with.
1056      if result.command then
1057        completion_item.command = result.command
1058      end
1059    end
1060    exec_command()
1061  end, bufnr)
1062end
1063
1064---@param bufnr integer
1065---@return integer
1066local function register_completedone(bufnr)
1067  local group = api.nvim_create_augroup(get_augroup(bufnr), { clear = false })
1068  if #api.nvim_get_autocmds({ buf = bufnr, event = 'CompleteDone', group = group }) > 0 then
1069    return group
1070  end
1071
1072  nvim_on('CompleteDone', group, { buf = bufnr }, function()
1073    local reason = api.nvim_get_vvar('event').reason ---@type string
1074    if reason == 'accept' then
1075      on_complete_done()
1076    elseif reason == 'cancel' then
1077      -- <C-e> dismissed the pum; stop re-querying an incomplete list.
1078      Context:reset()
1079    end
1080  end)
1081
1082  return group
1083end
1084
1085--- @param bufnr integer
1086--- @param clients table<integer, vim.lsp.Client>
1087--- @param ctx lsp.CompletionContext
1088local function trigger(bufnr, clients, ctx)
1089  reset_timer()
1090  Context:cancel_pending()
1091
1092  if vim.fn.pumvisible() ~= 0 and not Context.isIncomplete then
1093    return
1094  end
1095
1096  if ctx and ctx.triggerKind == protocol.CompletionTriggerKind.Invoked then
1097    register_completedone(bufnr)
1098  end
1099
1100  local win = api.nvim_get_current_win()
1101  local cursor_row = api.nvim_win_get_cursor(win)[1]
1102  local start_time = vim.uv.hrtime() --[[@as integer]]
1103  Context.last_request_time = start_time
1104
1105  local cancel_request = request(clients, bufnr, win, ctx, function(responses)
1106    local end_time = vim.uv.hrtime()
1107    rtt_ms = compute_new_average((end_time - start_time) * ns_to_ms)
1108
1109    Context.pending_requests = {}
1110    Context.isIncomplete = false
1111
1112    local new_cursor_row, cursor_col = unpack(api.nvim_win_get_cursor(win)) --- @type integer, integer
1113    local row_changed = new_cursor_row ~= cursor_row
1114    local mode = api.nvim_get_mode().mode
1115    if row_changed or not (mode == 'i' or mode == 'ic') then
1116      return
1117    end
1118
1119    local line = api.nvim_get_current_line()
1120    local line_to_cursor = line:sub(1, cursor_col)
1121    local word_boundary = vim.fn.match(line_to_cursor, '\\k*$')
1122
1123    local matches = {}
1124
1125    local server_start_boundary --- @type integer?
1126    for client_id, response in pairs(responses) do
1127      local client = lsp.get_client_by_id(client_id)
1128      if response.err then
1129        local msg = ('%s: %s %s'):format(
1130          client and client.name or 'UNKNOWN',
1131          response.err.code or 'NO_CODE',
1132          response.err.message
1133        )
1134        vim.notify_once(msg, vim.log.levels.WARN)
1135      end
1136
1137      local result = response.result
1138      if type(result) == 'table' and result.items == vim.NIL then
1139        error(
1140          ('%s: completion response has items=null, expected CompletionItem[]'):format(
1141            client and client.name or 'UNKNOWN'
1142          )
1143        )
1144      -- result is CompletionItem[] or CompletionList; result.items may be empty, and
1145      -- an empty incomplete list means request again when needed.
1146      elseif not vim.isnil(result) then
1147        Context.isIncomplete = Context.isIncomplete or result.isIncomplete
1148        if #(result.items or result) > 0 then
1149          local encoding = client and client.offset_encoding or 'utf-16'
1150          local client_matches, tmp_server_start_boundary
1151          client_matches, tmp_server_start_boundary = M._convert_results(
1152            line,
1153            cursor_row - 1,
1154            cursor_col,
1155            client_id,
1156            word_boundary,
1157            nil,
1158            result,
1159            encoding
1160          )
1161
1162          server_start_boundary = tmp_server_start_boundary or server_start_boundary
1163          vim.list_extend(matches, client_matches)
1164        end
1165      end
1166    end
1167
1168    --- @type table[]
1169    local prev_matches = vim.fn.complete_info({ 'items', 'matches' })['items']
1170
1171    --- @param prev_match table
1172    prev_matches = vim.tbl_filter(function(prev_match)
1173      local client_id = vim.tbl_get(prev_match, 'user_data', 'nvim', 'lsp', 'client_id')
1174      if client_id and responses[client_id] ~= nil then
1175        return false
1176      end
1177      return vim.tbl_get(prev_match, 'match')
1178    end, prev_matches)
1179
1180    matches = vim.list_extend(prev_matches, matches)
1181    local user_cmp = vim.tbl_get(buf_handles, bufnr, 'cmp')
1182    if user_cmp then
1183      table.sort(matches, user_cmp)
1184    end
1185
1186    local start_col = (server_start_boundary or word_boundary) + 1
1187    Context.cursor = { cursor_row, start_col }
1188    if #matches > 0 and has_completeopt('popup') then
1189      local group = get_augroup(bufnr)
1190      if #api.nvim_get_autocmds({ buf = bufnr, event = 'CompleteChanged', group = group }) == 0 then
1191        on_completechanged(group, bufnr)
1192      end
1193    end
1194    vim.fn.complete(start_col, matches)
1195  end)
1196
1197  table.insert(Context.pending_requests, cancel_request)
1198end
1199
1200--- @param handle vim.lsp.completion.BufHandle
1201local function on_insert_char_pre(handle)
1202  if Context.isIncomplete then
1203    reset_timer()
1204
1205    local debounce_ms = adaptive_debounce(Context.last_request_time, rtt_ms)
1206    local ctx = { triggerKind = protocol.CompletionTriggerKind.TriggerForIncompleteCompletions }
1207    if debounce_ms == 0 then
1208      vim.schedule(function()
1209        M.get({ ctx = ctx })
1210      end)
1211    else
1212      completion_timer = new_timer()
1213      completion_timer:start(
1214        math.floor(debounce_ms),
1215        0,
1216        vim.schedule_wrap(function()
1217          M.get({ ctx = ctx })
1218        end)
1219      )
1220    end
1221
1222    return
1223  end
1224
1225  if vim.fn.pumvisible() ~= 0 then
1226    return
1227  end
1228
1229  local char = vim.v.char
1230  local matched_clients = handle.triggers[char]
1231  -- Discard pending trigger char, complete the "latest" one.
1232  -- Can happen if a mapping inputs multiple trigger chars simultaneously.
1233  reset_timer()
1234  if matched_clients then
1235    completion_timer = assert(vim.uv.new_timer())
1236    completion_timer:start(25, 0, function()
1237      reset_timer()
1238      vim.schedule(function()
1239        trigger(api.nvim_get_current_buf(), matched_clients, {
1240          triggerKind = protocol.CompletionTriggerKind.TriggerCharacter,
1241          triggerCharacter = char,
1242        })
1243      end)
1244    end)
1245  end
1246end
1247
1248local function on_insert_leave()
1249  reset_timer()
1250  Context.cursor = nil
1251  Context:reset()
1252end
1253
1254--- @param client_id integer
1255--- @param bufnr integer
1256local function disable_completions(client_id, bufnr)
1257  local handle = buf_handles[bufnr]
1258  if not handle then
1259    return
1260  end
1261
1262  handle.clients[client_id] = nil
1263  if not next(handle.clients) then
1264    buf_handles[bufnr] = nil
1265    api.nvim_del_augroup_by_name(get_augroup(bufnr))
1266  else
1267    for char, clients in pairs(handle.triggers) do
1268      --- @param c vim.lsp.Client
1269      handle.triggers[char] = vim.tbl_filter(function(c)
1270        return c.id ~= client_id
1271      end, clients)
1272    end
1273  end
1274end
1275
1276--- @inlinedoc
1277--- @class vim.lsp.completion.BufferOpts
1278--- @field autotrigger? boolean  (default: false) When true, completion triggers automatically based on the server's `triggerCharacters`.
1279--- @field convert? fun(item: lsp.CompletionItem): table Transforms an LSP CompletionItem to |complete-items|.
1280--- @field cmp? fun(a: table, b: table): boolean Comparator for sorting merged completion items from all servers.
1281--- @field commit_characters? boolean  (default: true) When false, commit characters are ignored.
1282
1283---@param client_id integer
1284---@param bufnr integer
1285---@param opts vim.lsp.completion.BufferOpts
1286local function enable_completions(client_id, bufnr, opts)
1287  local buf_handle = buf_handles[bufnr]
1288  if not buf_handle then
1289    buf_handle = {
1290      clients = {},
1291      triggers = {},
1292      convert = opts.convert,
1293      cmp = opts.cmp,
1294      commit_characters = opts.commit_characters ~= false,
1295    }
1296    buf_handles[bufnr] = buf_handle
1297
1298    -- Set up autocommands.
1299    local group = register_completedone(bufnr)
1300    nvim_on('BufUnload', group, {
1301      buf = bufnr,
1302      desc = 'vim.lsp.completion: clean up on unload',
1303    }, function(ev)
1304      buf_handles[ev.buf] = nil
1305      api.nvim_del_augroup_by_id(group)
1306    end)
1307    nvim_on('LspDetach', group, {
1308      buf = bufnr,
1309      desc = 'vim.lsp.completion: clean up client on detach',
1310    }, function(ev)
1311      disable_completions(ev.data.client_id, ev.buf)
1312    end)
1313
1314    if opts.autotrigger then
1315      nvim_on('InsertCharPre', group, { buf = bufnr }, function()
1316        on_insert_char_pre(buf_handles[bufnr])
1317      end)
1318      nvim_on('InsertLeave', group, { buf = bufnr }, on_insert_leave)
1319    end
1320  end
1321
1322  if not buf_handle.clients[client_id] then
1323    local client = assert(lsp.get_client_by_id(client_id), 'invalid client ID')
1324
1325    -- Add the new client to the buffer's clients.
1326    buf_handle.clients[client_id] = client
1327
1328    -- Add the new client to the clients that should be triggered by its trigger characters.
1329    --- @type string[]
1330    local triggers = completion_options(client, bufnr).triggerCharacters or {}
1331    for _, char in ipairs(triggers) do
1332      local clients_for_trigger = buf_handle.triggers[char]
1333      if not clients_for_trigger then
1334        clients_for_trigger = {}
1335        buf_handle.triggers[char] = clients_for_trigger
1336      end
1337      local client_exists = vim.iter(clients_for_trigger):any(function(c)
1338        return c.id == client_id
1339      end)
1340      if not client_exists then
1341        table.insert(clients_for_trigger, client)
1342      end
1343    end
1344  end
1345end
1346
1347--- Enables or disables completions from the given language client in the given
1348--- buffer. Effects of enabling completions are:
1349---
1350--- - Calling |vim.lsp.completion.get()| uses the enabled clients to retrieve completion candidates.
1351--- - Selecting a completion item shows a preview popup ("completionItem/resolve") if 'completeopt'
1352---   has "popup".
1353--- - Accepting a completion item using `<c-y>` applies side effects like expanding snippets,
1354---   text edits (e.g. insert import statements) and executing associated commands. This works for
1355---   completions triggered via autotrigger, 'omnifunc' or [vim.lsp.completion.get()].
1356---
1357--- Examples: |lsp-attach| |lsp-completion|
1358---
1359--- @note |vim.lsp.omnifunc()| (|i_CTRL-X_CTRL-O|) queries every client that advertises completion,
1360--- including clients that were disabled by `enable(false)`. To suppress completions for a client,
1361--- clear its capability on |LspAttach|: `client.server_capabilities.completionProvider = nil`.
1362---
1363--- @note Behavior of `autotrigger=true` is controlled by the LSP `triggerCharacters` field. You
1364--- can override it on LspAttach, see |lsp-autocompletion|.
1365---
1366--- @param enable boolean True to enable, false to disable
1367--- @param client_id integer Client ID
1368--- @param bufnr integer Buffer handle, or 0 for the current buffer
1369--- @param opts? vim.lsp.completion.BufferOpts
1370function M.enable(enable, client_id, bufnr, opts)
1371  bufnr = vim._resolve_bufnr(bufnr)
1372
1373  if enable then
1374    enable_completions(client_id, bufnr, opts or {})
1375  else
1376    disable_completions(client_id, bufnr)
1377  end
1378end
1379
1380--- @inlinedoc
1381--- @class vim.lsp.completion.get.Opts
1382--- @field ctx? lsp.CompletionContext Completion context. Defaults to a trigger kind of `invoked`.
1383
1384--- Triggers LSP completion once in the current buffer, if LSP completion is enabled
1385--- (see |lsp-attach| |lsp-completion|).
1386---
1387--- Use CTRL-Y to select an item from the completion menu. |complete_CTRL-Y|
1388---
1389--- To invoke manually with CTRL-space, use this mapping:
1390--- ```lua
1391--- -- Use CTRL-space to trigger LSP completion.
1392--- -- Use CTRL-Y to select an item. |complete_CTRL-Y|
1393--- vim.keymap.set('i', '<c-space>', function()
1394---   vim.lsp.completion.get()
1395--- end)
1396--- ```
1397---
1398--- @param opts? vim.lsp.completion.get.Opts
1399function M.get(opts)
1400  opts = opts or {}
1401  local ctx = opts.ctx or { triggerKind = protocol.CompletionTriggerKind.Invoked }
1402  local bufnr = api.nvim_get_current_buf()
1403  local clients = (buf_handles[bufnr] or {}).clients or {}
1404
1405  trigger(bufnr, clients, ctx)
1406end
1407
1408--- Implements 'omnifunc' compatible LSP completion.
1409---
1410--- @see |complete-functions|
1411--- @see |complete-items|
1412--- @see |CompleteDone|
1413---
1414--- @param findstart integer 0 or 1, decides behavior
1415--- @param base integer findstart=0, text to match against
1416---
1417--- @return integer|table Decided by {findstart}:
1418--- - findstart=1: column where the completion starts, or -2 or -3
1419--- - findstart=0: list of matches (actually just calls |complete()|)
1420function M._omnifunc(findstart, base)
1421  lsp.log.debug('omnifunc.findstart', { findstart = findstart, base = base })
1422  local bufnr = api.nvim_get_current_buf()
1423  local clients = lsp.get_clients({ bufnr = bufnr, method = 'textDocument/completion' })
1424  local remaining = #clients
1425  if remaining == 0 then
1426    return findstart == 1 and -1 or {}
1427  end
1428
1429  trigger(bufnr, clients, { triggerKind = protocol.CompletionTriggerKind.Invoked })
1430
1431  -- Return -2 to signal that we should continue completion so that we can
1432  -- async complete.
1433  return -2
1434end
1435
1436return M