robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
15.7 KiB514 linesraw
1--- @brief
2--- This module provides the LSP "inline completion" feature, for completing multiline text (e.g.,
3--- whole methods) instead of just a word or line, which may result in "syntactically or
4--- semantically incorrect" code. Unlike regular completion, this is typically presented as overlay
5--- text instead of a menu of completion candidates.
6---
7--- LSP spec: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.18/specification/#textDocument_inlineCompletion
8---
9--- To try it out, here is a quickstart example using Copilot: [lsp-copilot]()
10---
11--- 1. Install Copilot:
12---    ```sh
13---    npm install --global @github/copilot-language-server
14---    ```
15--- 2. Define a config, (or copy `lsp/copilot.lua` from https://github.com/neovim/nvim-lspconfig):
16---    ```lua
17---    vim.lsp.config('copilot', {
18---      cmd = { 'copilot-language-server', '--stdio' },
19---      root_markers = { '.git' },
20---       init_options = {
21---         editorInfo = {
22---           name = 'Neovim', version = tostring(vim.version()) },
23---           editorPluginInfo = { name = 'Neovim', version = tostring(vim.version()) },
24---         },
25---    })
26---    ```
27--- 3. Activate the config:
28---    ```lua
29---    vim.lsp.enable('copilot')
30---    ```
31--- 4. Sign in to Copilot, or use the `:LspCopilotSignIn` command from https://github.com/neovim/nvim-lspconfig
32--- 5. Enable inline completion:
33---    ```lua
34---    vim.lsp.inline_completion.enable()
35---    ```
36--- 6. Set a keymap for `vim.lsp.inline_completion.get()` and invoke the keymap.
37
38local util = require('vim.lsp.util')
39local log = require('vim.lsp.log')
40local protocol = require('vim.lsp.protocol')
41local grammar = require('vim.lsp._snippet_grammar')
42local api = vim.api
43local nvim_on = require('vim._core.util').nvim_on
44
45local Capability = require('vim.lsp._capability')
46
47local M = {}
48
49local namespace = api.nvim_create_namespace('nvim.lsp.inline_completion')
50
51---@class vim.lsp.inline_completion.Item
52---@field _index integer The index among all items form all clients.
53---@field client_id integer Client ID
54---@field insert_text string|lsp.StringValue The text to be inserted, can be a snippet.
55---@field _filter_text? string
56---@field range? vim.Range Which range it be applied.
57---@field command? lsp.Command Corresponding server command.
58
59---@class (private) vim.lsp.inline_completion.ClientState
60---@field items? lsp.InlineCompletionItem[]
61
62---@class (private) vim.lsp.inline_completion.Completor : vim.lsp.Capability
63---@field active table<integer, vim.lsp.inline_completion.Completor?>
64---@field timer? uv.uv_timer_t Timer for debouncing automatic requests
65---@field current? vim.lsp.inline_completion.Item Currently selected item
66---@field _overlay? boolean Whether `current` replaces buffer text, per its original range
67---@field client_state table<integer, vim.lsp.inline_completion.ClientState>
68local Completor = {
69  name = 'inline_completion',
70  method = 'textDocument/inlineCompletion',
71  active = {},
72}
73Completor.__index = Completor
74setmetatable(Completor, Capability)
75Capability.all[Completor.name] = Completor
76
77---@package
78---@param buf integer
79---@return vim.lsp.inline_completion.Completor
80function Completor:new(buf)
81  self = Capability.new(self, buf)
82  self.client_state = {}
83  nvim_on({ 'InsertEnter', 'CursorMovedI', 'TextChangedP' }, self.augroup, { buf = buf }, function()
84    self:automatic_request()
85  end)
86  nvim_on({ 'InsertLeave' }, self.augroup, { buf = buf }, function()
87    self:abort()
88  end)
89  return self
90end
91
92---@package
93function Completor:destroy()
94  self:reset_timer()
95  api.nvim_buf_clear_namespace(self.bufnr, namespace, 0, -1)
96  Capability.destroy(self)
97end
98
99--- Longest common prefix
100---
101---@param a string
102---@param b string
103---@return integer index where the common prefix ends, exclusive
104local function lcp(a, b)
105  local i, la, lb = 1, #a, #b
106  while i <= la and i <= lb and a:sub(i, i) == b:sub(i, i) do
107    i = i + 1
108  end
109  return i
110end
111
112--- `lsp.Handler` for `textDocument/inlineCompletion`.
113---
114---@package
115---@param err? lsp.ResponseError
116---@param result? lsp.InlineCompletionItem[]|lsp.InlineCompletionList
117---@param ctx lsp.HandlerContext
118function Completor:handler(err, result, ctx)
119  if err then
120    log.error('inline_completion', err)
121    return
122  end
123  if not result or not vim.startswith(api.nvim_get_mode().mode, 'i') then
124    return
125  end
126
127  local items = result.items or result
128  self.client_state[ctx.client_id].items = items
129  self:select(1)
130end
131
132---@package
133function Completor:count_items()
134  local n = 0
135  for _, state in pairs(self.client_state) do
136    local items = state.items
137    if items then
138      n = n + #items
139    end
140  end
141  return n
142end
143
144---@package
145---@param i integer
146---@return integer?, lsp.InlineCompletionItem?
147function Completor:get_item(i)
148  local n = self:count_items()
149  i = i % (n + 1)
150  ---@type integer[]
151  local client_ids = vim.tbl_keys(self.client_state)
152  table.sort(client_ids)
153  for _, client_id in ipairs(client_ids) do
154    local items = self.client_state[client_id].items
155    if items then
156      if i > #items then
157        i = i - #items
158      else
159        return client_id, items[i]
160      end
161    end
162  end
163end
164
165--- Select the {index}-th completion item.
166---
167---@package
168---@param index integer
169---@param show_index? boolean
170function Completor:select(index, show_index)
171  self.current = nil
172  local client_id, item = self:get_item(index)
173  if not client_id or not item then
174    self:hide()
175    return
176  end
177
178  local client = assert(vim.lsp.get_client_by_id(client_id))
179  local range = item.range and vim.range.lsp(self.bufnr, item.range, client.offset_encoding)
180  self.current = {
181    _index = index,
182    client_id = client_id,
183    insert_text = item.insertText,
184    range = range,
185    _filter_text = item.filterText,
186    command = item.command,
187  }
188  -- Recorded here because `show()` may grow the range over typed characters.
189  self._overlay = range ~= nil and not range:is_empty()
190
191  local hint = show_index and (' (%d/%d)'):format(index, self:count_items()) or nil
192  self:show(hint)
193end
194
195--- Show or update the current completion item.
196---
197---@package
198---@param hint? string
199function Completor:show(hint)
200  self:hide()
201  local current = self.current
202  if not current then
203    return
204  end
205
206  local insert_text = current.insert_text
207  local text = type(insert_text) == 'string' and insert_text
208    or tostring(grammar.parse(insert_text.value))
209  local lines = {} ---@type [string, string][][]
210  for s in vim.gsplit(text, '\n', { plain = true }) do
211    table.insert(lines, { { s, 'ComplHint' } })
212  end
213  if hint then
214    table.insert(lines[#lines], { hint, 'ComplHintMore' })
215  end
216
217  local row, col ---@type integer, integer
218  if current.range then
219    row, col = current.range:to_extmark()
220  else
221    row, col =
222      vim.pos.cursor(self.bufnr, api.nvim_win_get_cursor(vim.fn.bufwinid(self.bufnr))):to_extmark()
223  end
224
225  -- To ensure that virtual text remains visible continuously (without flickering)
226  -- while the user is editing the buffer, we allow displaying expired virtual text.
227  -- Since the position of virtual text may become invalid after document changes,
228  -- out-of-range items are ignored.
229  local line_text = api.nvim_buf_get_lines(self.bufnr, row, row + 1, false)[1]
230  if not (line_text and #line_text >= col) then
231    self.current = nil
232    return
233  end
234
235  -- The first line of the text to be inserted
236  -- usually contains characters entered by the user,
237  -- which should be skipped before displaying the virtual text.
238  -- Splitting on a nonempty separator always yields a line, with its first chunk.
239  local virt_text = assert(lines[1])
240  assert(virt_text[1])
241  local skip = lcp(line_text:sub(col + 1), virt_text[1][1])
242  local winid = api.nvim_get_current_win()
243  -- At least, characters before the cursor should be skipped.
244  if api.nvim_win_get_buf(winid) == self.bufnr then
245    local cursor_row, cursor_col =
246      vim.pos.cursor(self.bufnr, api.nvim_win_get_cursor(winid)):to_extmark()
247    if row == cursor_row then
248      -- Characters typed since the request lie past the item's range, so `accept()`
249      -- would leave them behind. `skip` stops where the buffer stops matching.
250      if current.range and col + skip - 1 >= cursor_col then
251        local start_row, start_col, _, end_col = current.range:to_extmark()
252        if end_col < cursor_col then
253          current.range = vim.range.extmark(self.bufnr, start_row, start_col, row, cursor_col)
254        end
255      end
256      skip = math.max(skip, cursor_col - col + 1)
257    end
258  end
259  virt_text[1][1] = virt_text[1][1]:sub(skip)
260  col = col + skip - 1
261
262  local virt_lines = { unpack(lines, 2) }
263  for i, s in ipairs(virt_lines) do
264    if #s == 1 and s[1][1] == '' then
265      virt_lines[i] = {}
266    end
267  end
268
269  api.nvim_buf_set_extmark(self.bufnr, namespace, row, col, {
270    virt_text = virt_text,
271    virt_lines = virt_lines,
272    virt_text_pos = (self._overlay and 'overlay') or 'inline',
273    hl_mode = 'combine',
274  })
275end
276
277--- Hide the current completion item.
278---
279---@package
280function Completor:hide()
281  api.nvim_buf_clear_namespace(self.bufnr, namespace, 0, -1)
282end
283
284---@package
285---@param kind lsp.InlineCompletionTriggerKind
286function Completor:request(kind)
287  for client_id in pairs(self.client_state) do
288    local client = assert(vim.lsp.get_client_by_id(client_id))
289    ---@type lsp.InlineCompletionContext
290    local context = { triggerKind = kind }
291    if
292      kind == protocol.InlineCompletionTriggerKind.Invoked and api.nvim_get_mode().mode:match('^v')
293    then
294      context.selectedCompletionInfo = {
295        range = util.make_given_range_params(nil, nil, self.bufnr, client.offset_encoding).range,
296        text = table.concat(vim.fn.getregion(vim.fn.getpos("'<"), vim.fn.getpos("'>")), '\n'),
297      }
298    end
299
300    ---@type lsp.InlineCompletionParams
301    local params = {
302      textDocument = util.make_text_document_params(self.bufnr),
303      position = util.make_position_params(0, client.offset_encoding).position,
304      context = context,
305    }
306    client:request('textDocument/inlineCompletion', params, function(...)
307      self:handler(...)
308    end, self.bufnr)
309  end
310end
311
312---@private
313function Completor:reset_timer()
314  local timer = self.timer
315  if timer then
316    self.timer = nil
317    if not timer:is_closing() then
318      timer:stop()
319      timer:close()
320    end
321  end
322end
323
324--- Automatically request with debouncing, used as callbacks in autocmd events.
325---
326---@package
327function Completor:automatic_request()
328  self:show()
329  self:reset_timer()
330  self.timer = vim.defer_fn(function()
331    self:request(protocol.InlineCompletionTriggerKind.Automatic)
332  end, 200)
333end
334
335--- Abort the current completion item and pending requests.
336---
337---@package
338function Completor:abort()
339  util._cancel_requests({
340    bufnr = self.bufnr,
341    method = 'textDocument/inlineCompletion',
342    type = 'pending',
343  })
344  self:reset_timer()
345  self:hide()
346  self.current = nil
347end
348
349--- Accept the current completion item to the buffer.
350---
351---@package
352---@param item vim.lsp.inline_completion.Item
353function Completor:accept(item)
354  local insert_text = item.insert_text
355  if type(insert_text) == 'string' then
356    if item.range then
357      local start_row, start_col, end_row, end_col = item.range:to_extmark()
358      -- The line may have shrunk past the range since the item arrived.
359      local end_line = api.nvim_buf_get_lines(self.bufnr, end_row, end_row + 1, true)[1]
360      end_col = math.min(end_col, #end_line)
361
362      local lines = vim.split(insert_text, '\n')
363      api.nvim_buf_set_text(self.bufnr, start_row, start_col, end_row, end_col, lines)
364      local win = api.nvim_get_current_win()
365      win = api.nvim_win_get_buf(win) == self.bufnr and win or vim.fn.bufwinid(self.bufnr)
366      local row, col = item.range:to_mark()
367      api.nvim_win_set_cursor(win, {
368        row + #lines - 1,
369        (#lines == 1 and col or 0) + #lines[#lines],
370      })
371    else
372      api.nvim_paste(insert_text, false, 0)
373    end
374  elseif insert_text.kind == 'snippet' then
375    vim.snippet.expand(insert_text.value)
376  end
377
378  -- Execute the command *after* inserting this completion.
379  if item.command then
380    local client = assert(vim.lsp.get_client_by_id(item.client_id))
381    client:exec_cmd(item.command, { bufnr = self.bufnr })
382  end
383end
384
385--- Query whether inline completion is enabled in the {filter}ed scope
386---@param filter? vim.lsp.capability.enable.Filter
387function M.is_enabled(filter)
388  return vim.lsp._capability.is_enabled('inline_completion', filter)
389end
390
391--- Enables or disables inline completion for the {filter}ed scope,
392--- inline completion will automatically be refreshed when you are in insert mode.
393---
394--- To "toggle", pass the inverse of `is_enabled()`:
395---
396--- ```lua
397--- vim.lsp.inline_completion.enable(not vim.lsp.inline_completion.is_enabled())
398--- ```
399---
400---@param enable? boolean true/nil to enable, false to disable
401---@param filter? vim.lsp.capability.enable.Filter
402function M.enable(enable, filter)
403  vim.lsp._capability.enable('inline_completion', enable, filter)
404end
405
406---@class vim.lsp.inline_completion.select.Opts
407---@inlinedoc
408---
409--- (default: current buffer)
410---@field bufnr? integer
411---
412--- The number of candidates to move by.
413--- A positive integer moves forward by {count} candidates,
414--- while a negative integer moves backward by {count} candidates.
415--- (default: v:count1)
416---@field count? integer
417---
418--- Whether to loop around file or not. Similar to 'wrapscan'.
419--- (default: `true`)
420---@field wrap? boolean
421
422--- Switch between available inline completion candidates.
423---
424---@param opts? vim.lsp.inline_completion.select.Opts
425function M.select(opts)
426  vim.validate('opts', opts, 'table', true)
427  opts = opts or {}
428  local bufnr = vim._resolve_bufnr(opts.bufnr)
429  local completor = Completor.active[bufnr]
430  if not completor then
431    return
432  end
433
434  local count = opts.count or vim.v.count1
435  local wrap = opts.wrap ~= false
436
437  local current = completor.current
438  if not current then
439    return
440  end
441
442  local n = completor:count_items()
443  local index = current._index + count
444  if wrap then
445    index = (index - 1) % n + 1
446  else
447    index = math.max(1, math.min(index, n))
448  end
449  completor:select(index, true)
450end
451
452---@class vim.lsp.inline_completion.get.Opts
453---@inlinedoc
454---
455--- Buffer handle, or 0 for current.
456--- (default: 0)
457---@field bufnr? integer
458---
459--- A callback triggered when a completion item is accepted.
460--- You can use it to modify the completion item that is about to be accepted
461--- and return it to apply the changes,
462--- or return `nil` to prevent the changes from being applied to the buffer
463--- so you can implement custom behavior.
464---@field on_accept? fun(item: vim.lsp.inline_completion.Item): vim.lsp.inline_completion.Item?
465
466--- Accept the currently displayed completion candidate to the buffer.
467---
468--- It returns false when no candidate can be accepted,
469--- so you can use the return value to implement a fallback:
470---
471--- ```lua
472---  vim.keymap.set('i', '<Tab>', function()
473---   if not vim.lsp.inline_completion.get() then
474---     return '<Tab>'
475---   end
476--- end, { expr = true, desc = 'Accept the current inline completion' })
477--- ````
478---@param opts? vim.lsp.inline_completion.get.Opts
479---@return boolean `true` if a completion was applied, else `false`.
480function M.get(opts)
481  vim.validate('opts', opts, 'table', true)
482  opts = opts or {}
483
484  local bufnr = vim._resolve_bufnr(opts.bufnr)
485  local on_accept = opts.on_accept
486
487  local completor = Completor.active[bufnr]
488  if completor and completor.current then
489    -- Schedule apply to allow `get()` can be mapped with `<expr>`.
490    vim.schedule(function()
491      local item = completor.current
492      completor:abort()
493      if not item then
494        return
495      end
496
497      -- Note that we do not intend for `on_accept`
498      -- to take effect when there is no current item.
499      if on_accept then
500        local accepted_item = on_accept(item)
501        if accepted_item then
502          completor:accept(accepted_item)
503        end
504      else
505        completor:accept(item)
506      end
507    end)
508    return true
509  end
510
511  return false
512end
513
514return M