robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
52.1 KiB1578 linesraw
1--- @brief
2--- The `vim.lsp.buf_…` functions perform operations for LSP clients attached to the current buffer.
3
4local api = vim.api
5local nvim_on = require('vim._core.util').nvim_on
6local lsp = vim.lsp
7local validate = vim.validate
8local util = require('vim.lsp.util')
9local npcall = vim.npcall
10local Range = require('vim.treesitter._range')
11
12local M = {}
13
14--- @param params? table
15--- @return fun(client: vim.lsp.Client): lsp.TextDocumentPositionParams
16local function client_positional_params(params)
17  local win = api.nvim_get_current_win()
18  return function(client)
19    local ret = util.make_position_params(win, client.offset_encoding)
20    if params then
21      ret = vim.tbl_extend('force', ret, params)
22    end
23    return ret
24  end
25end
26
27local hover_ns = api.nvim_create_namespace('nvim.lsp.hover_range')
28local rename_ns = api.nvim_create_namespace('nvim.lsp.rename_range')
29
30--- Returns false if the LSP response is stale and should be discarded.
31--- @param ctx lsp.HandlerContext
32--- @return boolean
33local function ctx_is_valid(ctx)
34  local bufnr = ctx.bufnr
35  if
36    not bufnr
37    or not api.nvim_buf_is_valid(bufnr)
38    or api.nvim_get_current_buf() ~= bufnr
39    or lsp.util.buf_versions[bufnr] ~= ctx.version
40  then
41    return false
42  end
43  ---@type lsp.Position?
44  local p = ctx.params and ctx.params.position
45  if not p then
46    return true
47  end
48
49  local c = lsp.get_client_by_id(ctx.client_id)
50  local enc = c and c.offset_encoding
51  if not enc then
52    return false
53  end
54
55  local cur_pos = vim.pos.cursor(0)
56  local pos = vim.pos.lsp(bufnr, p, enc)
57  return cur_pos == pos
58end
59
60--- @class vim.lsp.buf.hover.Opts : vim.lsp.util.open_floating_preview.Opts
61--- @field silent? boolean
62
63--- Displays hover information about the symbol under the cursor in a floating
64--- window. The window will be dismissed on cursor move.
65--- Calling the function twice will jump into the floating window
66--- (thus by default, "KK" will open the hover window and focus it).
67--- In the floating window, all commands and mappings are available as usual,
68--- except that "q" dismisses the window.
69--- You can scroll the contents the same as you would any other buffer.
70---
71--- Note: to disable hover highlights, add the following to your config:
72---
73--- ```lua
74--- vim.api.nvim_create_autocmd('ColorScheme', {
75---   callback = function()
76---     vim.api.nvim_set_hl(0, 'LspReferenceTarget', {})
77---   end,
78--- })
79--- ```
80--- @param config? vim.lsp.buf.hover.Opts
81function M.hover(config)
82  validate('config', config, 'table', true)
83
84  config = config or {}
85  config.focus_id = 'textDocument/hover'
86
87  lsp.buf_request_all(0, 'textDocument/hover', client_positional_params(), function(results, ctx)
88    local bufnr = ctx.bufnr
89    if not bufnr or not ctx_is_valid(ctx) then
90      return -- Ignore result if context changed. Can happen for slow LS.
91    end
92
93    -- Filter errors from results
94    local results1 = {} --- @type table<integer,lsp.Hover>
95    local nresults = 0
96    local empty_response = false
97
98    for client_id, resp in pairs(results) do
99      local err, result = resp.err, resp.result
100      if err then
101        lsp.log.error(err.code, err.message)
102      elseif result and result.contents then
103        -- Make sure the response is not empty
104        -- Five response shapes:
105        -- - MarkupContent: { kind="markdown", value="doc" }
106        -- - MarkedString-string: "doc"
107        -- - MarkedString-pair: { language="c", value="doc" }
108        -- - MarkedString[]-string: { "doc1", ... }
109        -- - MarkedString[]-pair: { { language="c", value="doc1" }, ... }
110        local valid = false
111        if type(result.contents) == 'table' then
112          local value_len = #(
113            vim.tbl_get(result.contents, 'value') -- MarkupContent or MarkedString-pair
114            or vim.tbl_get(result.contents, 1, 'value') -- MarkedString[]-pair
115            or result.contents[1] -- MarkedString[]-string
116            or ''
117          )
118          valid = value_len > 0
119        elseif type(result.contents) == 'string' then
120          valid = #result.contents > 0
121        end
122
123        if valid then
124          results1[client_id] = result
125          nresults = nresults + 1
126        else
127          empty_response = true
128        end
129      end
130    end
131
132    if nresults == 0 then
133      if config.silent ~= true then
134        if empty_response then
135          vim.notify('Empty hover response', vim.log.levels.INFO)
136        else
137          vim.notify('No information available', vim.log.levels.INFO)
138        end
139      end
140      return
141    end
142
143    local contents = {} --- @type string[]
144    local MarkupKind = lsp.protocol.MarkupKind
145    local format = MarkupKind.Markdown
146
147    for client_id, result in pairs(results1) do
148      local client = assert(lsp.get_client_by_id(client_id))
149      if nresults > 1 then
150        -- Show client name if there are multiple clients
151        contents[#contents + 1] = string.format('# %s', client.name)
152      end
153
154      if type(result.contents) == 'table' and result.contents.kind == MarkupKind.PlainText then
155        if nresults == 1 then
156          -- Only one client: use PlainText format
157          format = MarkupKind.PlainText
158          contents = vim.split(result.contents.value or '', '\n', { trimempty = true })
159        else
160          -- Multiple clients: surround plaintext with ``` to get correct formatting
161          contents[#contents + 1] = '```'
162          vim.list_extend(
163            contents,
164            vim.split(result.contents.value or '', '\n', { trimempty = true })
165          )
166          contents[#contents + 1] = '```'
167        end
168      else
169        vim.list_extend(contents, util.convert_input_to_markdown_lines(result.contents))
170      end
171      if result.range then
172        local range = vim.range.lsp(bufnr, result.range, client.offset_encoding)
173
174        vim.hl.range(
175          bufnr,
176          hover_ns,
177          'LspReferenceTarget',
178          { range.start_row, range.start_col },
179          { range.end_row, range.end_col },
180          { priority = vim.hl.priorities.user }
181        )
182      end
183      contents[#contents + 1] = '---'
184    end
185
186    -- Remove last linebreak ('---') if contents is not empty
187    if #contents > 0 then
188      contents[#contents] = nil
189    end
190
191    local _, winid = lsp.util.open_floating_preview(contents, format, config)
192
193    nvim_on('WinClosed', nil, { pattern = tostring(winid), once = true }, function()
194      api.nvim_buf_clear_namespace(bufnr, hover_ns, 0, -1)
195      return true
196    end)
197  end)
198end
199
200--- @param name vim.lsp.protocol.Method.ClientToServer.Request
201--- @param params lsp.DocumentSymbolParams|lsp.WorkspaceSymbolParams
202--- @param opts? vim.lsp.ListOpts
203local function request_with_opts(name, params, opts)
204  local req_handler --- @type function?
205  if opts then
206    --- @param err lsp.ResponseError?
207    --- @param result lsp.DocumentSymbol[]|lsp.SymbolInformation[]|lsp.WorkspaceSymbol[]|nil
208    --- @param ctx lsp.HandlerContext
209    --- @param config? vim.lsp.ListOpts
210    req_handler = function(err, result, ctx, config)
211      local client = assert(lsp.get_client_by_id(ctx.client_id))
212      local handler = client.handlers[name] or lsp.handlers[name]
213      handler(err, result, ctx, vim.tbl_extend('force', config or {}, opts))
214    end
215  end
216  lsp.buf_request(0, name, params, req_handler)
217end
218
219---@param method vim.lsp.protocol.Method.ClientToServer.Request
220---@param context? lsp.ReferenceContext
221---@param opts? vim.lsp.ListOpts
222local function get_locations(method, context, opts)
223  opts = opts or {}
224  ---@diagnostic disable-next-line: undefined-field
225  if opts.reuse_win then
226    vim.deprecate(
227      'vim.lsp.buf.<method>({ reuse_win = true })',
228      "vim.lsp.buf.<method>() and the value of 'switchbuf' of preference",
229      '0.13'
230    )
231  end
232
233  local pos = opts.pos or vim.pos.cursor(0)
234  local buf = pos.buf
235
236  local clients = lsp.get_clients({ method = method, bufnr = buf })
237  if not next(clients) then
238    vim.notify(lsp._unsupported_method(method), vim.log.levels.WARN)
239    return
240  end
241
242  local from = vim.fn.getpos('.')
243  from[1] = buf
244  local tagname = vim.fn.expand('<cword>')
245
246  lsp.buf_request_all(buf, method, function(client)
247    ---@type lsp.TextDocumentPositionParams
248    local params = {
249      textDocument = util.make_text_document_params(buf),
250      position = pos:to_lsp(client.offset_encoding),
251    }
252    if method == 'textDocument/references' then
253      ---@cast params lsp.ReferenceParams
254      params.context = context or { includeDeclaration = true }
255    end
256    return params
257  end, function(results)
258    ---@type vim.quickfix.entry[]
259    local all_items = {}
260
261    for client_id, res in pairs(results) do
262      local client = assert(lsp.get_client_by_id(client_id))
263      local locations = {}
264      if res then
265        locations = vim.islist(res.result) and res.result or { res.result }
266      end
267      local items = util.locations_to_items(locations, client.offset_encoding)
268      vim.list_extend(all_items, items)
269    end
270
271    local name = string.gsub(assert(method:match('textDocument/(.*)')), '(%u)', ' %1'):lower()
272    if vim.tbl_isempty(all_items) then
273      vim.notify(('No %s found'):format(name), vim.log.levels.INFO)
274      return
275    end
276
277    ---@type vim.fn.setqflist.what
278    local what = {
279      title = name:gsub('^%l', string.upper),
280      items = all_items,
281      context = { bufnr = buf, method = method },
282    }
283    if opts.on_list then
284      validate('opts.on_list', opts.on_list, 'function')
285      opts.on_list(what)
286    else
287      if opts.loclist then
288        vim.fn.setloclist(0, {}, ' ', what)
289      else
290        vim.fn.setqflist({}, ' ', what)
291      end
292
293      if
294        #all_items == 1
295        and method ~= 'textDocument/implementation'
296        and method ~= 'textDocument/references'
297      then
298        local tagstack = { { tagname = tagname, from = from } }
299        vim.fn.settagstack(vim.fn.bufwinid(buf), { items = tagstack }, 't')
300        if opts.loclist then
301          vim.cmd('lfirst')
302        else
303          vim.cmd('cfirst')
304        end
305      else
306        if opts.loclist then
307          vim.cmd('botright lopen')
308        else
309          vim.cmd('botright copen')
310        end
311      end
312    end
313  end)
314end
315
316--- @class vim.lsp.ListOpts
317---
318--- list-handler replacing the default handler.
319--- Called for any non-empty result.
320--- The default handler populates the quickfix (or location) list with the result.
321--- If there is a single result (and the method is not `implementation` or `references`),
322--- it pushes a tag onto the tagstack and jumps to the result.
323--- For example, when `loclist == false` (the default), the handler is equivalent to:
324--- ```lua
325--- local function on_list(what)
326---   vim.fn.setqflist({}, ' ', what)
327---   if
328---     #what.items == 1
329---     and what.context.method ~= 'textDocument/implementation'
330---     and what.context.method ~= 'textDocument/references'
331---   then
332---     local tagstack = { { tagname = tagname, from = from } }
333---     vim.fn.settagstack(vim.fn.win_getid(win), { items = tagstack }, 't')
334---     vim.cmd('cfirst')
335---   else
336---     vim.cmd('botright copen')
337---   end
338--- end
339---
340--- vim.lsp.buf.definition({ on_list = on_list })
341--- vim.lsp.buf.references(nil, { on_list = on_list })
342--- ```
343--- The list can be transformed before it is shown. For example, to remove
344--- duplicate locations returned by multiple clients:
345--- ```lua
346--- local function on_list(what)
347---   vim.list.unique(what.items, function(item)
348---     return ('%s\0%d\0%d\0%d\0%d'):format(
349---       item.filename or '',
350---       item.lnum or 0,
351---       item.col or 0,
352---       item.end_lnum or 0,
353---       item.end_col or 0
354---     )
355---   end)
356---   vim.fn.setqflist({}, ' ', what)
357---   vim.cmd('botright copen')
358--- end
359---
360--- vim.lsp.buf.definition({ on_list = on_list })
361--- vim.lsp.buf.references(nil, { on_list = on_list })
362--- ```
363--- See |setqflist-what| for the structure of the `what` parameter.
364--- @field on_list? fun(what: vim.fn.setqflist.what)
365---
366--- Whether to use the |location-list| or the |quickfix| list in the default handler.
367--- ```lua
368--- vim.lsp.buf.definition({ loclist = true })
369--- vim.lsp.buf.references(nil, { loclist = false })
370--- ```
371--- @field loclist? boolean
372---
373--- Position on a buffer to request.
374--- (default: cursor position)
375--- @field pos? vim.Pos
376
377--- Jumps to the declaration of the symbol under the cursor.
378--- @note Many servers do not implement this method. Generally, see |vim.lsp.buf.definition()| instead.
379--- @param opts? vim.lsp.ListOpts
380function M.declaration(opts)
381  validate('opts', opts, 'table', true)
382  get_locations('textDocument/declaration', nil, opts)
383end
384
385--- Jumps to the definition of the symbol under the cursor.
386--- @param opts? vim.lsp.ListOpts
387function M.definition(opts)
388  validate('opts', opts, 'table', true)
389  get_locations('textDocument/definition', nil, opts)
390end
391
392--- Jumps to the definition of the type of the symbol under the cursor.
393--- @param opts? vim.lsp.ListOpts
394function M.type_definition(opts)
395  validate('opts', opts, 'table', true)
396  get_locations('textDocument/typeDefinition', nil, opts)
397end
398
399--- Lists all the implementations for the symbol under the cursor in the
400--- quickfix window.
401--- @param opts? vim.lsp.ListOpts
402function M.implementation(opts)
403  validate('opts', opts, 'table', true)
404  get_locations('textDocument/implementation', nil, opts)
405end
406
407--- @param results table<integer,{err: lsp.ResponseError?, result: lsp.SignatureHelp?}>
408local function process_signature_help_results(results)
409  local signatures = {} --- @type [vim.lsp.Client,lsp.SignatureInformation][]
410  local active_signature = 1
411
412  -- Pre-process results
413  for client_id, r in pairs(results) do
414    local err = r.err
415    local client = assert(lsp.get_client_by_id(client_id))
416    if err then
417      vim.notify(
418        client.name .. ': ' .. tostring(err.code) .. ': ' .. err.message,
419        vim.log.levels.ERROR
420      )
421      api.nvim_command('redraw')
422    else
423      local result = r.result
424      if result and result.signatures then
425        for i, sig in ipairs(result.signatures) do
426          sig.activeParameter = sig.activeParameter or result.activeParameter
427          local idx = #signatures + 1
428          if (result.activeSignature or 0) + 1 == i then
429            active_signature = idx
430          end
431          signatures[idx] = { client, sig }
432        end
433      end
434    end
435  end
436
437  return signatures, active_signature
438end
439
440local sig_help_ns = api.nvim_create_namespace('nvim.lsp.signature_help')
441
442--- @class vim.lsp.buf.signature_help.Opts : vim.lsp.util.open_floating_preview.Opts
443--- @field silent? boolean
444
445--- Displays signature information about the symbol under the cursor in a
446--- floating window. Allows cycling through signature overloads with `<C-s>`,
447--- which can be remapped via `<Plug>(nvim.lsp.ctrl-s)`
448---
449--- Example:
450---
451--- ```lua
452--- vim.keymap.set('n', '<C-b>', '<Plug>(nvim.lsp.ctrl-s)')
453--- ```
454---
455--- @param config? vim.lsp.buf.signature_help.Opts
456function M.signature_help(config)
457  validate('config', config, 'table', true)
458
459  local method = 'textDocument/signatureHelp'
460
461  config = config and vim.deepcopy(config) or {}
462  config.focus_id = method
463  local user_title = config.title
464
465  lsp.buf_request_all(0, method, client_positional_params(), function(results, ctx)
466    if not ctx_is_valid(ctx) then
467      return -- Ignore result if context changed. Can happen for slow LS.
468    end
469
470    local signatures, active_signature = process_signature_help_results(results)
471
472    if not next(signatures) then
473      if config.silent ~= true then
474        vim.notify('No signature help available', vim.log.levels.INFO)
475      end
476      return
477    end
478
479    local ft = vim.bo[assert(ctx.bufnr)].filetype
480    local total = #signatures
481    local can_cycle = total > 1 and config.focusable ~= false
482    local idx = active_signature - 1
483
484    --- @param update_win? integer
485    local function show_signature(update_win)
486      idx = (idx % total) + 1
487      local signature = assert(signatures[idx])
488      local client, result = signature[1], signature[2]
489      --- @type string[]?
490      local triggers =
491        vim.tbl_get(client.server_capabilities, 'signatureHelpProvider', 'triggerCharacters')
492      local lines, hl =
493        util.convert_signature_help_to_markdown_lines({ signatures = { result } }, ft, triggers)
494      if not lines then
495        return
496      end
497
498      -- Show title only if there are multiple clients or multiple signatures.
499      if total > 1 then
500        local sfx = total > 1
501            and string.format(' (%d/%d)%s', idx, total, can_cycle and ' (<C-s> to cycle)' or '')
502          or ''
503        config.title = user_title or string.format('Signature Help: %s%s', client.name, sfx)
504        -- If no border is set, render title inside the window.
505        if not (config.border or vim.o.winborder ~= '') then
506          table.insert(lines, 1, '# ' .. config.title)
507          if hl then
508            hl[1] = hl[1] + 1
509            hl[3] = hl[3] + 1
510          end
511        end
512      end
513
514      config._update_win = update_win
515
516      local buf, win = util.open_floating_preview(lines, 'markdown', config)
517
518      if hl then
519        api.nvim_buf_clear_namespace(buf, sig_help_ns, 0, -1)
520        vim.hl.range(
521          buf,
522          sig_help_ns,
523          'LspSignatureActiveParameter',
524          { hl[1], hl[2] },
525          { hl[3], hl[4] }
526        )
527      end
528      return buf, win
529    end
530
531    local fbuf, fwin = show_signature()
532
533    if can_cycle then
534      vim.keymap.set('n', '<Plug>(nvim.lsp.ctrl-s)', function()
535        show_signature(fwin)
536      end, {
537        buf = fbuf,
538        desc = 'Cycle next signature',
539      })
540      if vim.fn.hasmapto('<Plug>(nvim.lsp.ctrl-s)', 'n') == 0 then
541        vim.keymap.set('n', '<C-s>', '<Plug>(nvim.lsp.ctrl-s)', {
542          buf = fbuf,
543          desc = 'Cycle next signature',
544        })
545      end
546    end
547  end)
548end
549
550---@param bufnr integer
551---@param mode "v"|"V"
552---@return {start: [integer,integer], end: [integer,integer]} using (1, 0) indexing
553local function range_from_selection(bufnr, mode)
554  -- TODO: Use `vim.fn.getregionpos()` instead.
555
556  -- [bufnum, lnum, col, off]; both row and column 1-indexed
557  local start = vim.fn.getpos('v')
558  local end_ = vim.fn.getpos('.')
559  local start_row = start[2]
560  local start_col = start[3]
561  local end_row = end_[2]
562  local end_col = end_[3]
563
564  -- A user can start visual selection at the end and move backwards
565  -- Normalize the range to start < end
566  if start_row == end_row and end_col < start_col then
567    end_col, start_col = start_col, end_col --- @type integer, integer
568  elseif end_row < start_row then
569    start_row, end_row = end_row, start_row --- @type integer, integer
570    start_col, end_col = end_col, start_col --- @type integer, integer
571  end
572  if mode == 'V' then
573    start_col = 1
574    local lines = api.nvim_buf_get_lines(bufnr, end_row - 1, end_row, true)
575    end_col = #lines[1]
576  end
577  return {
578    ['start'] = { start_row, start_col - 1 },
579    ['end'] = { end_row, end_col - 1 },
580  }
581end
582
583--- @class vim.lsp.buf.format.Opts
584--- @inlinedoc
585---
586--- Can be used to specify FormattingOptions. Some unspecified options will be
587--- automatically derived from the current Nvim options.
588--- See https://microsoft.github.io/language-server-protocol/specification/#formattingOptions
589--- @field formatting_options? lsp.FormattingOptions
590---
591--- Time in milliseconds allowed for each formatting request. On timeout, cancels
592--- the request and continues with the next client. With async=true, there is no
593--- timeout unless this option is set. Responses received after the request times
594--- out are ignored.
595--- (default: `1000` for synchronous requests)
596--- @field timeout_ms? integer
597---
598--- Restrict formatting to the clients attached to the given buffer.
599--- (default: current buffer)
600--- @field bufnr? integer
601---
602--- Predicate used to filter clients. Receives a client as argument and must
603--- return a boolean. Clients matching the predicate are included. Example:
604--- ```lua
605--- -- Never request typescript-language-server for formatting
606--- vim.lsp.buf.format {
607---   filter = function(client) return client.name ~= "ts_ls" end
608--- }
609--- ```
610--- @field filter? fun(client: vim.lsp.Client): boolean?
611---
612--- If true the method won't block.
613--- Editing the buffer while formatting asynchronous can lead to unexpected
614--- changes.
615--- (Default: false)
616--- @field async? boolean
617---
618--- Restrict formatting to the client with ID (client.id) matching this field.
619--- @field id? integer
620---
621--- Restrict formatting to the client with name (client.name) matching this field.
622--- @field name? string
623---
624--- Range to format.
625--- Table must contain `start` and `end` keys with {row,col} tuples using
626--- (1,0) indexing. The end column can be -1 to format through the end of the line.
627--- Can also be a list of tables that contain `start` and `end` keys as described above,
628--- in which case `textDocument/rangesFormatting` support is required.
629--- (Default: current selection in visual mode, `nil` in other modes,
630--- formatting the full buffer)
631--- @field range? {start:[integer,integer],end:[integer, integer]}|{start:[integer,integer],end:[integer,integer]}[]
632
633--- Formats a buffer using the attached (and optionally filtered) language
634--- server clients.
635---
636--- @param opts? vim.lsp.buf.format.Opts
637function M.format(opts)
638  validate('opts', opts, 'table', true)
639
640  opts = opts or {}
641  local bufnr = vim._resolve_bufnr(opts.bufnr)
642  local mode = api.nvim_get_mode().mode
643  local range = opts.range
644  -- Try to use visual selection if no range is given
645  if not range and (mode == 'v' or mode == 'V') then
646    range = range_from_selection(bufnr, mode)
647  end
648
649  local passed_multiple_ranges = (range and #range ~= 0 and type(range[1]) == 'table')
650  local method ---@type vim.lsp.protocol.Method.ClientToServer.Request
651  if passed_multiple_ranges then
652    method = 'textDocument/rangesFormatting'
653  elseif range then
654    method = 'textDocument/rangeFormatting'
655  else
656    method = 'textDocument/formatting'
657  end
658
659  local clients = lsp.get_clients({
660    id = opts.id,
661    bufnr = bufnr,
662    name = opts.name,
663    method = method,
664  })
665  if opts.filter then
666    clients = vim.tbl_filter(opts.filter, clients)
667  end
668
669  if #clients == 0 then
670    vim.notify('[LSP] Format request failed, no matching language servers.')
671  end
672
673  --- @param client vim.lsp.Client
674  --- @param params lsp.DocumentFormattingParams
675  --- @return lsp.DocumentFormattingParams|lsp.DocumentRangeFormattingParams|lsp.DocumentRangesFormattingParams
676  local function set_range(client, params)
677    ---  @param r {start:[integer,integer],end:[integer, integer]}
678    local function to_lsp_range(r)
679      if r['end'][2] == -1 then
680        local end_line = api.nvim_buf_get_lines(bufnr, r['end'][1] - 1, r['end'][1], true)[1]
681        return {
682          start = vim.pos(bufnr, r.start[1] - 1, r.start[2]):to_lsp(client.offset_encoding),
683          ['end'] = vim.pos(bufnr, r['end'][1] - 1, #end_line):to_lsp(client.offset_encoding),
684        }
685      end
686      return util.make_given_range_params(r.start, r['end'], bufnr, client.offset_encoding).range
687    end
688
689    --- @type lsp.DocumentFormattingParams|lsp.DocumentRangeFormattingParams|lsp.DocumentRangesFormattingParams
690    local ret = params
691    if passed_multiple_ranges then
692      --- @cast range {start:[integer,integer],end:[integer, integer]}[]
693      --- @cast ret lsp.DocumentRangesFormattingParams
694      ret.ranges = vim.tbl_map(to_lsp_range, range)
695    elseif range then
696      --- @cast range {start:[integer,integer],end:[integer, integer]}
697      --- @cast ret lsp.DocumentRangeFormattingParams
698      ret.range = to_lsp_range(range)
699    end
700    return ret
701  end
702
703  if opts.async then
704    --- @param idx? integer
705    --- @param client? vim.lsp.Client
706    local function do_format(idx, client)
707      if not idx or not client then
708        return
709      end
710      local params = set_range(client, util.make_formatting_params(opts.formatting_options))
711      local timer = opts.timeout_ms and assert(vim.uv.new_timer())
712      local success, request_id = client:request(method, params, function(...)
713        if timer then
714          if timer:is_closing() then
715            return
716          end
717          timer:close()
718        end
719        local handler = client.handlers[method] or lsp.handlers[method]
720        handler(...)
721        do_format(next(clients, idx))
722      end, bufnr)
723      if timer and not timer:is_closing() then
724        if not success then
725          timer:close()
726          return
727        end
728        timer:start(
729          assert(opts.timeout_ms),
730          0,
731          vim.schedule_wrap(function()
732            if timer:is_closing() then
733              return
734            end
735            timer:close()
736            if request_id and client.requests[request_id] then
737              client:cancel_request(request_id)
738            end
739            vim.notify(string.format('[LSP][%s] timeout', client.name), vim.log.levels.WARN)
740            do_format(next(clients, idx))
741          end)
742        )
743      end
744    end
745    do_format(next(clients))
746  else
747    local timeout_ms = opts.timeout_ms or 1000
748    for _, client in pairs(clients) do
749      local params = set_range(client, util.make_formatting_params(opts.formatting_options))
750      local result, err = client:request_sync(method, params, timeout_ms, bufnr)
751      if result and result.result then
752        util.apply_text_edits(result.result, bufnr, client.offset_encoding)
753      elseif err then
754        vim.notify(string.format('[LSP][%s] %s', client.name, err), vim.log.levels.WARN)
755      end
756    end
757  end
758end
759
760--- @class vim.lsp.buf.rename.Opts
761--- @inlinedoc
762---
763--- Predicate used to filter clients. Receives a client as argument and
764--- must return a boolean. Clients matching the predicate are included.
765--- @field filter? fun(client: vim.lsp.Client): boolean?
766---
767--- Restrict clients used for rename to ones where client.name matches
768--- this field.
769--- @field name? string
770---
771--- (default: current buffer)
772--- @field bufnr? integer
773
774--- Renames all references to the symbol under the cursor.
775---
776---@param new_name string|nil If not provided, the user will be prompted for a new
777---                name using |vim.ui.input()|.
778---@param opts? vim.lsp.buf.rename.Opts Additional options:
779function M.rename(new_name, opts)
780  validate('new_name', new_name, 'string', true)
781  validate('opts', opts, 'table', true)
782
783  opts = opts or {}
784  local bufnr = vim._resolve_bufnr(opts.bufnr)
785  local clients = lsp.get_clients({
786    bufnr = bufnr,
787    name = opts.name,
788    -- Clients must at least support rename, prepareRename is optional
789    method = 'textDocument/rename',
790  })
791  if opts.filter then
792    clients = vim.tbl_filter(opts.filter, clients)
793  end
794
795  if #clients == 0 then
796    vim.notify('[LSP] Rename, no matching language servers with rename capability.')
797  end
798
799  local win = api.nvim_get_current_win()
800
801  -- Compute early to account for cursor movements after going async
802  local cword = vim.fn.expand('<cword>')
803
804  --- @param range lsp.Range
805  --- @param position_encoding 'utf-8'|'utf-16'|'utf-32'
806  local function get_text_at_range(range, position_encoding)
807    local vim_range = vim.range.lsp(bufnr, range, position_encoding)
808    return api.nvim_buf_get_text(
809      bufnr,
810      vim_range.start_row,
811      vim_range.start_col,
812      vim_range.end_row,
813      vim_range.end_col,
814      {}
815    )[1]
816  end
817
818  --- @param idx? integer
819  --- @param client? vim.lsp.Client
820  local function try_use_client(idx, client)
821    if not idx or not client then
822      return
823    end
824
825    --- @param name string
826    local function rename(name)
827      local params = util.make_position_params(win, client.offset_encoding) --[[@as lsp.RenameParams]]
828      params.newName = name
829      local handler = client.handlers['textDocument/rename'] or lsp.handlers['textDocument/rename']
830      client:request('textDocument/rename', params, function(...)
831        handler(...)
832        try_use_client(next(clients, idx))
833      end, bufnr)
834    end
835
836    if client:supports_method('textDocument/prepareRename') then
837      local params = util.make_position_params(win, client.offset_encoding)
838      ---@param result? lsp.PrepareRenameResult
839      client:request('textDocument/prepareRename', params, function(err, result)
840        if err or result == nil then
841          if next(clients, idx) then
842            try_use_client(next(clients, idx))
843          else
844            local msg = err and ('Error on prepareRename: ' .. (err.message or ''))
845              or 'Nothing to rename'
846            vim.notify(msg, vim.log.levels.INFO)
847          end
848          return
849        end
850
851        if new_name then
852          rename(new_name)
853          return
854        end
855
856        local range ---@type vim.Range?
857        if result.start then
858          range = vim.range.lsp(bufnr, result, client.offset_encoding)
859        elseif result.range then
860          range = vim.range.lsp(bufnr, result.range, client.offset_encoding)
861        end
862        if range then
863          vim.hl.range(
864            bufnr,
865            rename_ns,
866            'LspReferenceTarget',
867            { range.start_row, range.start_col },
868            { range.end_row, range.end_col },
869            { priority = vim.hl.priorities.user }
870          )
871        end
872
873        local prompt_opts = {
874          prompt = 'New Name: ',
875          scope = 'cursor',
876        }
877        if result.placeholder then
878          prompt_opts.default = result.placeholder
879        elseif result.start then
880          prompt_opts.default = get_text_at_range(result, client.offset_encoding)
881        else
882          prompt_opts.default = cword
883        end
884        vim.ui.input(prompt_opts, function(input)
885          if input and #input ~= 0 then
886            rename(input)
887          end
888          api.nvim_buf_clear_namespace(bufnr, rename_ns, 0, -1)
889        end)
890      end, bufnr)
891    else
892      assert(
893        client:supports_method('textDocument/rename'),
894        'Client must support textDocument/rename'
895      )
896      if new_name then
897        rename(new_name)
898        return
899      end
900
901      local prompt_opts = {
902        prompt = 'New Name: ',
903        default = cword,
904        scope = 'cursor',
905      }
906      vim.ui.input(prompt_opts, function(input)
907        if not input or #input == 0 then
908          return
909        end
910        rename(input)
911      end)
912    end
913  end
914
915  try_use_client(next(clients))
916end
917
918--- Lists all the references to the symbol under the cursor in the quickfix window.
919---
920---@param context lsp.ReferenceContext? Context for the request
921---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references
922---@param opts? vim.lsp.ListOpts
923function M.references(context, opts)
924  validate('context', context, 'table', true)
925  validate('opts', opts, 'table', true)
926  get_locations('textDocument/references', context, opts)
927end
928
929--- Lists all symbols in the current buffer in the |location-list|.
930--- @param opts? vim.lsp.ListOpts
931function M.document_symbol(opts)
932  validate('opts', opts, 'table', true)
933  opts = vim.tbl_deep_extend('keep', opts or {}, { loclist = true })
934  local params = { textDocument = util.make_text_document_params() }
935  request_with_opts('textDocument/documentSymbol', params, opts)
936end
937
938--- @param client_id integer
939--- @param method vim.lsp.protocol.Method.ClientToServer.Request
940--- @param params table
941--- @param handler? lsp.Handler
942--- @param bufnr? integer
943local function request_with_id(client_id, method, params, handler, bufnr)
944  local client = lsp.get_client_by_id(client_id)
945  if not client then
946    vim.notify(
947      string.format('Client with id=%d disappeared during hierarchy request', client_id),
948      vim.log.levels.WARN
949    )
950    return
951  end
952  client:request(method, params, handler, bufnr)
953end
954
955--- @param item lsp.TypeHierarchyItem|lsp.CallHierarchyItem
956local function format_hierarchy_item(item)
957  if not item.detail or #item.detail == 0 then
958    return item.name
959  end
960  return string.format('%s %s', item.name, item.detail)
961end
962
963--- @alias vim.lsp.buf.HierarchyMethod
964--- | 'typeHierarchy/subtypes'
965--- | 'typeHierarchy/supertypes'
966--- | 'callHierarchy/incomingCalls'
967--- | 'callHierarchy/outgoingCalls'
968
969--- @type table<vim.lsp.buf.HierarchyMethod, 'type' | 'call'>
970local hierarchy_methods = {
971  ['typeHierarchy/subtypes'] = 'type',
972  ['typeHierarchy/supertypes'] = 'type',
973  ['callHierarchy/incomingCalls'] = 'call',
974  ['callHierarchy/outgoingCalls'] = 'call',
975}
976
977--- @param method vim.lsp.buf.HierarchyMethod
978local function hierarchy(method)
979  local kind = hierarchy_methods[method]
980
981  local prepare_method = kind == 'type' and 'textDocument/prepareTypeHierarchy'
982    or 'textDocument/prepareCallHierarchy'
983
984  local bufnr = api.nvim_get_current_buf()
985  local clients = lsp.get_clients({ bufnr = bufnr, method = prepare_method })
986  if not next(clients) then
987    vim.notify(lsp._unsupported_method(method), vim.log.levels.WARN)
988    return
989  end
990
991  local win = api.nvim_get_current_win()
992
993  lsp.buf_request_all(bufnr, prepare_method, function(client)
994    return util.make_position_params(win, client.offset_encoding)
995  end, function(req_results)
996    local results = {} --- @type [integer, lsp.TypeHierarchyItem|lsp.CallHierarchyItem][]
997    for client_id, res in pairs(req_results) do
998      if res.err then
999        vim.notify(res.err.message, vim.log.levels.WARN)
1000      elseif res.result then
1001        local result = res.result --- @type lsp.TypeHierarchyItem[]|lsp.CallHierarchyItem[]
1002        for _, item in ipairs(result) do
1003          results[#results + 1] = { client_id, item }
1004        end
1005      end
1006    end
1007
1008    if #results == 0 then
1009      vim.notify('No item resolved', vim.log.levels.WARN)
1010    elseif #results == 1 then
1011      local client_id, item = results[1][1], results[1][2]
1012      request_with_id(client_id, method, { item = item }, nil, bufnr)
1013    else
1014      vim.ui.select(results, {
1015        prompt = string.format('Select a %s hierarchy item:', kind),
1016        kind = kind .. 'hierarchy',
1017        format_item = function(x)
1018          return format_hierarchy_item(x[2])
1019        end,
1020      }, function(x)
1021        if x then
1022          local client_id, item = x[1], x[2]
1023          request_with_id(client_id, method, { item = item }, nil, bufnr)
1024        end
1025      end)
1026    end
1027  end)
1028end
1029
1030--- Lists all the call sites of the symbol under the cursor in the
1031--- |quickfix| window. If the symbol can resolve to multiple
1032--- items, the user can pick one in the |inputlist()|.
1033function M.incoming_calls()
1034  hierarchy('callHierarchy/incomingCalls')
1035end
1036
1037--- Lists all the items that are called by the symbol under the
1038--- cursor in the |quickfix| window. If the symbol can resolve to
1039--- multiple items, the user can pick one in the |inputlist()|.
1040function M.outgoing_calls()
1041  hierarchy('callHierarchy/outgoingCalls')
1042end
1043
1044--- Lists all the subtypes or supertypes of the symbol under the
1045--- cursor in the |quickfix| window. If the symbol can resolve to
1046--- multiple items, the user can pick one using |vim.ui.select()|.
1047---@param kind "subtypes"|"supertypes"
1048function M.typehierarchy(kind)
1049  validate('kind', kind, function(v)
1050    return v == 'subtypes' or v == 'supertypes'
1051  end)
1052
1053  local method = kind == 'subtypes' and 'typeHierarchy/subtypes' or 'typeHierarchy/supertypes'
1054  hierarchy(method)
1055end
1056
1057--- List workspace folders.
1058---
1059function M.list_workspace_folders()
1060  local workspace_folders = {}
1061  for _, client in pairs(lsp.get_clients({ bufnr = 0 })) do
1062    for _, folder in pairs(client.workspace_folders or {}) do
1063      table.insert(workspace_folders, folder.name)
1064    end
1065  end
1066  return workspace_folders
1067end
1068
1069--- Add the folder at path to the workspace folders. If {path} is
1070--- not provided, the user will be prompted for a path using |input()|.
1071--- @param workspace_folder? string
1072function M.add_workspace_folder(workspace_folder)
1073  validate('workspace_folder', workspace_folder, 'string', true)
1074
1075  workspace_folder = workspace_folder
1076    or npcall(vim.fn.input, 'Workspace Folder: ', vim.fn.expand('%:p:h'), 'dir')
1077  api.nvim_command('redraw')
1078  if not (workspace_folder and #workspace_folder > 0) then
1079    return
1080  end
1081  if vim.fn.isdirectory(workspace_folder) == 0 then
1082    vim.notify(workspace_folder .. ' is not a valid directory')
1083    return
1084  end
1085  local bufnr = api.nvim_get_current_buf()
1086  for _, client in pairs(lsp.get_clients({ bufnr = bufnr })) do
1087    client:_add_workspace_folder(workspace_folder)
1088  end
1089end
1090
1091--- Remove the folder at path from the workspace folders. If
1092--- {path} is not provided, the user will be prompted for
1093--- a path using |input()|.
1094--- @param workspace_folder? string
1095function M.remove_workspace_folder(workspace_folder)
1096  validate('workspace_folder', workspace_folder, 'string', true)
1097
1098  workspace_folder = workspace_folder
1099    or npcall(vim.fn.input, 'Workspace Folder: ', vim.fn.expand('%:p:h'))
1100  api.nvim_command('redraw')
1101  if not workspace_folder or #workspace_folder == 0 then
1102    return
1103  end
1104  local bufnr = api.nvim_get_current_buf()
1105  for _, client in pairs(lsp.get_clients({ bufnr = bufnr })) do
1106    client:_remove_workspace_folder(workspace_folder)
1107  end
1108  vim.notify(workspace_folder .. 'is not currently part of the workspace')
1109end
1110
1111--- Lists all symbols in the current workspace in the quickfix window.
1112---
1113--- The list is filtered against {query}; if the argument is omitted from the
1114--- call, the user is prompted to enter a string on the command line. An empty
1115--- string means no filtering is done.
1116---
1117--- @param query string? optional
1118--- @param opts? vim.lsp.ListOpts
1119function M.workspace_symbol(query, opts)
1120  validate('query', query, 'string', true)
1121  validate('opts', opts, 'table', true)
1122
1123  query = query or npcall(vim.fn.input, 'Query: ')
1124  if query == nil then
1125    return
1126  end
1127  local params = { query = query }
1128  request_with_opts('workspace/symbol', params, opts)
1129end
1130
1131--- @class vim.lsp.WorkspaceDiagnosticsOpts
1132--- @inlinedoc
1133---
1134--- Only request diagnostics from the indicated client. If nil, the request is sent to all clients.
1135--- @field client_id? integer
1136
1137--- Request workspace-wide diagnostics.
1138--- @param opts? vim.lsp.WorkspaceDiagnosticsOpts
1139--- @see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_diagnostic
1140function M.workspace_diagnostics(opts)
1141  validate('opts', opts, 'table', true)
1142
1143  lsp.diagnostic._workspace_diagnostics(opts or {})
1144end
1145
1146--- Send request to the server to resolve document highlights for the current
1147--- text document position. This request can be triggered by a  key mapping or
1148--- by events such as `CursorHold`, e.g.:
1149---
1150--- ```vim
1151--- autocmd CursorHold  <buffer> lua vim.lsp.buf.document_highlight()
1152--- autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight()
1153--- autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references()
1154--- ```
1155---
1156--- Note: Usage of |vim.lsp.buf.document_highlight()| requires the following highlight groups
1157---       to be defined or you won't be able to see the actual highlights.
1158---         |hl-LspReferenceText|
1159---         |hl-LspReferenceRead|
1160---         |hl-LspReferenceWrite|
1161function M.document_highlight()
1162  lsp.buf_request(0, 'textDocument/documentHighlight', client_positional_params())
1163end
1164
1165--- Removes document highlights from current buffer.
1166function M.clear_references()
1167  util.buf_clear_references()
1168end
1169
1170---@nodoc
1171---@class vim.lsp.CodeActionResultEntry
1172---@field err? lsp.ResponseError
1173---@field result? (lsp.Command|lsp.CodeAction)[]
1174---@field context lsp.HandlerContext
1175
1176--- Corresponds to `lsp.CodeActionContext`, but all fields are optional:
1177--- @class vim.lsp.buf.code_action.context : lsp.CodeActionContext
1178--- @inlinedoc
1179---
1180--- Inferred from the current position if not provided.
1181--- @field diagnostics? lsp.Diagnostic[]
1182---
1183--- `CodeActionKind`s used to filter the code actions. Most servers support values like "refactor" or "quickfix".
1184--- @field only? lsp.CodeActionKind[]
1185---
1186--- Why code actions were requested.
1187--- @field triggerKind? lsp.CodeActionTriggerKind
1188
1189--- @class vim.lsp.buf.code_action.Opts
1190--- @inlinedoc
1191---
1192--- @field context? vim.lsp.buf.code_action.context
1193---
1194--- Predicate taking a code action or command and the provider's ID.
1195--- If it returns false, the action is filtered out.
1196--- @field filter? fun(x: lsp.CodeAction|lsp.Command, client_id: integer):boolean
1197---
1198--- When set to `true`, and there is just one remaining action
1199--- (after filtering), the action is applied without user query.
1200--- @field apply? boolean
1201---
1202--- Range for which code actions should be requested.
1203--- If in visual mode this defaults to the active selection.
1204--- Table must contain `start` and `end` keys with {row,col} tuples
1205--- using mark-like indexing. See |api-indexing|
1206--- @field range? {start: integer[], end: integer[]}
1207
1208--- This is not public because the main extension point is
1209--- vim.ui.select which can be overridden independently.
1210---
1211--- Can't call/use vim.lsp.handlers['textDocument/codeAction'] because it expects
1212--- `(err, CodeAction[] | Command[], ctx)`, but we want to aggregate the results
1213--- from multiple clients to have 1 single UI prompt for the user, yet we still
1214--- need to be able to link a `CodeAction|Command` to the right client for
1215--- `codeAction/resolve`
1216---@param results table<integer, vim.lsp.CodeActionResultEntry>
1217---@param opts? vim.lsp.buf.code_action.Opts
1218local function on_code_action_results(results, opts)
1219  ---@param a lsp.Command|lsp.CodeAction
1220  ---@param client_id integer
1221  local function action_filter(a, client_id)
1222    -- filter by specified action kind
1223    if opts and opts.context then
1224      if opts.context.only then
1225        if not a.kind then
1226          return false
1227        end
1228        local found = false
1229        for _, o in ipairs(opts.context.only) do
1230          -- action kinds are hierarchical with . as a separator: when requesting only 'type-annotate'
1231          -- this filter allows both 'type-annotate' and 'type-annotate.foo', for example
1232          if a.kind == o or vim.startswith(a.kind, o .. '.') then
1233            found = true
1234            break
1235          end
1236        end
1237        if not found then
1238          return false
1239        end
1240      end
1241      -- Only show disabled code actions when the trigger kind is "Invoked".
1242      if a.disabled and opts.context.triggerKind ~= lsp.protocol.CodeActionTriggerKind.Invoked then
1243        return false
1244      end
1245    end
1246    -- filter by user function
1247    if opts and opts.filter and not opts.filter(a, client_id) then
1248      return false
1249    end
1250    -- no filter removed this action
1251    return true
1252  end
1253
1254  ---@type {action: lsp.Command|lsp.CodeAction, ctx: lsp.HandlerContext}[]
1255  local actions = {}
1256  for _, result in pairs(results) do
1257    for _, action in pairs(result.result or {}) do
1258      if action_filter(action, result.context.client_id) then
1259        table.insert(actions, { action = action, ctx = result.context })
1260      end
1261    end
1262  end
1263  if #actions == 0 then
1264    vim.notify('No code actions available', vim.log.levels.INFO)
1265    return
1266  end
1267
1268  ---@param action lsp.Command|lsp.CodeAction
1269  ---@param client vim.lsp.Client
1270  ---@param ctx lsp.HandlerContext
1271  local function apply_action(action, client, ctx)
1272    if action.edit then
1273      util.apply_workspace_edit(action.edit, client.offset_encoding)
1274    end
1275    local a_cmd = action.command
1276    if a_cmd then
1277      local command = type(a_cmd) == 'table' and a_cmd or action
1278      --- @cast command lsp.Command
1279      client:exec_cmd(command, ctx)
1280    end
1281  end
1282
1283  ---@param choice? {action: lsp.Command|lsp.CodeAction, ctx: lsp.HandlerContext}
1284  local function on_user_choice(choice)
1285    if not choice then
1286      return
1287    end
1288
1289    -- textDocument/codeAction can return either Command[] or CodeAction[]
1290    --
1291    -- CodeAction
1292    --  ...
1293    --  edit?: WorkspaceEdit    -- <- must be applied before command
1294    --  command?: Command
1295    --
1296    -- Command:
1297    --  title: string
1298    --  command: string
1299    --  arguments?: any[]
1300
1301    local client = assert(lsp.get_client_by_id(choice.ctx.client_id))
1302    local action = choice.action
1303    local bufnr = assert(choice.ctx.bufnr, 'Must have buffer number')
1304
1305    -- Only code actions are resolved, so if we have a command, just apply it.
1306    if type(action.title) == 'string' and type(action.command) == 'string' then
1307      apply_action(action, client, choice.ctx)
1308      return
1309    end
1310
1311    -- Work around incorrect union narrowing: EmmyLuaLs/emmylua-analyzer-rust#1239.
1312    ---@cast action lsp.CodeAction
1313    if action.disabled then
1314      vim.notify(action.disabled.reason, vim.log.levels.ERROR)
1315      return
1316    end
1317
1318    if not (action.edit and action.command) and client:supports_method('codeAction/resolve') then
1319      client:request('codeAction/resolve', action, function(err, resolved_action)
1320        if err then
1321          -- If resolve fails, try to apply the edit/command from the original code action.
1322          if action.edit or action.command then
1323            apply_action(action, client, choice.ctx)
1324          else
1325            vim.notify(err.code .. ': ' .. err.message, vim.log.levels.ERROR)
1326          end
1327        else
1328          apply_action(resolved_action, client, choice.ctx)
1329        end
1330      end, bufnr)
1331    else
1332      apply_action(action, client, choice.ctx)
1333    end
1334  end
1335
1336  -- If options.apply is given, and there are just one remaining code action,
1337  -- apply it directly without querying the user.
1338  if opts and opts.apply and #actions == 1 then
1339    on_user_choice(actions[1])
1340    return
1341  end
1342
1343  ---@param item {action: lsp.Command|lsp.CodeAction, ctx: lsp.HandlerContext}
1344  local function format_item(item)
1345    local clients = lsp.get_clients({ bufnr = item.ctx.bufnr })
1346    local title = item.action.title:gsub('\r\n', '\\r\\n'):gsub('\n', '\\n')
1347
1348    if item.action.disabled then
1349      title = title .. ' (disabled)'
1350    end
1351
1352    if #clients == 1 then
1353      return title
1354    end
1355
1356    local source = assert(lsp.get_client_by_id(item.ctx.client_id)).name
1357    return ('%s [%s]'):format(title, source)
1358  end
1359
1360  local select_opts = {
1361    prompt = 'Code actions:',
1362    kind = 'codeaction',
1363    format_item = format_item,
1364  }
1365  vim.ui.select(actions, select_opts, on_user_choice)
1366end
1367
1368---@param diagnostic vim.Diagnostic
1369---@param bufnr integer
1370---@param lnum integer
1371---@param col integer
1372---@return boolean
1373local function diagnostic_contains_cursor(diagnostic, bufnr, lnum, col)
1374  local start = vim.pos(bufnr, diagnostic.lnum, diagnostic.col)
1375  local finish =
1376    vim.pos(bufnr, diagnostic.end_lnum or diagnostic.lnum, diagnostic.end_col or diagnostic.col)
1377  local cursor = vim.pos(bufnr, lnum, col)
1378
1379  if start == finish then
1380    return cursor == start
1381  end
1382
1383  return start <= cursor and cursor < finish
1384end
1385
1386--- Selects a code action (LSP: "textDocument/codeAction" request) available at cursor position.
1387---
1388---@param opts? vim.lsp.buf.code_action.Opts
1389---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction
1390---@see vim.lsp.protocol.CodeActionTriggerKind
1391function M.code_action(opts)
1392  validate('options', opts, 'table', true)
1393  opts = opts or {}
1394  -- Detect old API call code_action(context) which should now be
1395  -- code_action({ context = context} )
1396  --- @diagnostic disable-next-line:undefined-field
1397  if opts.diagnostics or opts.only then
1398    opts = { options = opts }
1399  end
1400  local context = opts.context and vim.deepcopy(opts.context) or {}
1401  if not context.triggerKind then
1402    context.triggerKind = lsp.protocol.CodeActionTriggerKind.Invoked
1403  end
1404  local mode = api.nvim_get_mode().mode
1405  local bufnr = api.nvim_get_current_buf()
1406  local win = api.nvim_get_current_win()
1407  local range = opts.range
1408  if range == nil and (mode == 'v' or mode == 'V') then
1409    range = range_from_selection(bufnr, mode)
1410  end
1411  local cursor = api.nvim_win_get_cursor(win)
1412  local lnum = cursor[1] - 1
1413  local col = cursor[2]
1414  local clients = lsp.get_clients({ bufnr = bufnr, method = 'textDocument/codeAction' })
1415  if not next(clients) then
1416    vim.notify(lsp._unsupported_method('textDocument/codeAction'), vim.log.levels.WARN)
1417    return
1418  end
1419
1420  lsp.buf_request_all(bufnr, 'textDocument/codeAction', function(client)
1421    local params
1422
1423    if range then
1424      validate('range', range, 'table')
1425      validate('range.start', range.start, 'table')
1426      validate('range.end', range['end'], 'table')
1427      params =
1428        util.make_given_range_params(range.start, range['end'], bufnr, client.offset_encoding)
1429    else
1430      params = util.make_range_params(win, client.offset_encoding)
1431    end
1432
1433    --- @cast params lsp.CodeActionParams
1434
1435    if context.diagnostics then
1436      params.context = context
1437    else
1438      local ns_push = lsp.diagnostic.get_namespace(client.id)
1439      local diagnostics = {}
1440
1441      client:_provider_foreach('textDocument/diagnostic', function(cap)
1442        --- @cast cap lsp.DiagnosticRegistrationOptions
1443        local ns_pull = lsp.diagnostic.get_namespace(client.id, true, cap.identifier)
1444        vim.list_extend(
1445          diagnostics,
1446          vim.diagnostic.get(bufnr, { namespace = ns_pull, lnum = lnum })
1447        )
1448      end)
1449
1450      vim.list_extend(diagnostics, vim.diagnostic.get(bufnr, { namespace = ns_push, lnum = lnum }))
1451      if range == nil then
1452        diagnostics = vim.tbl_filter(function(diagnostic)
1453          return diagnostic_contains_cursor(diagnostic, bufnr, lnum, col)
1454        end, diagnostics)
1455      end
1456      params.context = vim.tbl_extend('force', context, {
1457        ---@diagnostic disable-next-line: no-unknown
1458        diagnostics = vim.tbl_map(function(d)
1459          return d.user_data.lsp
1460        end, diagnostics),
1461      })
1462    end
1463
1464    return params
1465  end, function(results)
1466    on_code_action_results(results, opts)
1467  end)
1468end
1469
1470---@type { index: integer, ranges: lsp.Range[] }?
1471local selection_ranges = nil
1472
1473---@param range lsp.Range
1474local function select_range(range)
1475  local start_line = range.start.line
1476  local end_line = range['end'].line
1477
1478  local start_col = range.start.character
1479  local end_col = range['end'].character
1480
1481  Range.visual_select({ start_line, start_col, end_line, end_col })
1482end
1483
1484---@param range lsp.Range
1485local function is_empty(range)
1486  return range.start.line == range['end'].line and range.start.character == range['end'].character
1487end
1488
1489--- [lsp-incremental-selection]()
1490---
1491--- Expands or contracts a |Visual| selection at cursor, based on ranges given by LSP. The
1492--- `direction` parameter specifies the number of times to expand the selection. Negative values
1493--- will shrink the selection.
1494---
1495--- @param direction integer
1496--- @param timeout_ms integer? (default: `1000`) Maximum time (milliseconds) to wait for a result.
1497function M.selection_range(direction, timeout_ms)
1498  validate('direction', direction, 'number')
1499  validate('timeout_ms', timeout_ms, 'number', true)
1500
1501  if selection_ranges then
1502    local new_index = selection_ranges.index + direction
1503    selection_ranges.index = math.min(#selection_ranges.ranges, math.max(1, new_index))
1504
1505    select_range(assert(selection_ranges.ranges[selection_ranges.index]))
1506    return
1507  end
1508
1509  local method = 'textDocument/selectionRange'
1510  local client = lsp.get_clients({ method = method, bufnr = 0 })[1]
1511  if not client then
1512    vim.notify(lsp._unsupported_method(method), vim.log.levels.WARN)
1513    return
1514  end
1515
1516  local position_params = util.make_position_params(0, client.offset_encoding)
1517
1518  ---@type lsp.SelectionRangeParams
1519  local params = {
1520    textDocument = position_params.textDocument,
1521    positions = { position_params.position },
1522  }
1523
1524  timeout_ms = timeout_ms or 1000
1525  local result, err = lsp.buf_request_sync(0, method, params, timeout_ms)
1526  if err then
1527    local err_message = type(err) == 'table' and lsp.rpc.format_rpc_error(err) or err
1528    lsp.log.error('selectionRange request failed: ' .. err_message)
1529    return
1530  end
1531  if not result or not result[client.id] or not result[client.id].result then
1532    return
1533  end
1534  if result[client.id].error then
1535    lsp.log.error(result[client.id].error.code, result[client.id].error.message)
1536  end
1537
1538  -- We only requested one range, thus we get the first and only response here.
1539  local response = assert(result[client.id].result[1]) ---@type lsp.SelectionRange?
1540  local ranges = {} ---@type lsp.Range[]
1541  local lines = api.nvim_buf_get_lines(0, 0, -1, false)
1542
1543  -- Populate the list of ranges from the given request.
1544  while response do
1545    local range = response.range
1546    if not is_empty(range) then
1547      local start_line = range.start.line
1548      local end_line = range['end'].line
1549      range.start.character = vim.str_byteindex(
1550        lines[start_line + 1] or '',
1551        client.offset_encoding,
1552        range.start.character,
1553        false
1554      )
1555      range['end'].character = vim.str_byteindex(
1556        lines[end_line + 1] or '',
1557        client.offset_encoding,
1558        range['end'].character,
1559        false
1560      )
1561      ranges[#ranges + 1] = range
1562    end
1563    response = response.parent
1564  end
1565
1566  -- Clear selection ranges when leaving visual mode.
1567  nvim_on('ModeChanged', nil, { once = true, pattern = 'v*:*' }, function()
1568    selection_ranges = nil
1569  end)
1570
1571  if #ranges > 0 then
1572    local index = math.min(#ranges, math.max(1, direction))
1573    selection_ranges = { index = index, ranges = ranges }
1574    select_range(assert(ranges[index]))
1575  end
1576end
1577
1578return M