robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
52.6 KiB1602 linesraw
1local api = vim.api
2local validate = vim.validate
3local nvim_on = require('vim._core.util').nvim_on
4
5local lsp = vim._defer_require('vim.lsp', {
6  _capability = ..., --- @module 'vim.lsp._capability'
7  _changetracking = ..., --- @module 'vim.lsp._changetracking'
8  _folding_range = ..., --- @module 'vim.lsp._folding_range'
9  _snippet_grammar = ..., --- @module 'vim.lsp._snippet_grammar'
10  _watchfiles = ..., --- @module 'vim.lsp._watchfiles'
11  buf = ..., --- @module 'vim.lsp.buf'
12  client = ..., --- @module 'vim.lsp.client'
13  codelens = ..., --- @module 'vim.lsp.codelens'
14  completion = ..., --- @module 'vim.lsp.completion'
15  diagnostic = ..., --- @module 'vim.lsp.diagnostic'
16  document_color = ..., --- @module 'vim.lsp.document_color'
17  handlers = ..., --- @module 'vim.lsp.handlers'
18  inlay_hint = ..., --- @module 'vim.lsp.inlay_hint'
19  inline_completion = ..., --- @module 'vim.lsp.inline_completion'
20  linked_editing_range = ..., --- @module 'vim.lsp.linked_editing_range'
21  log = ..., --- @module 'vim.lsp.log'
22  on_type_formatting = ..., --- @module 'vim.lsp.on_type_formatting'
23  protocol = ..., --- @module 'vim.lsp.protocol'
24  rpc = ..., --- @module 'vim.lsp.rpc'
25  semantic_tokens = ..., --- @module 'vim.lsp.semantic_tokens'
26  -- Work around EmmyLuaLs/emmylua-analyzer-rust#1238 for function exports.
27  --- @type fun(pattern: string, flags: string): table[]|vim.NIL
28  tagfunc = ..., --- @module 'vim.lsp.tagfunc'
29  util = ..., --- @module 'vim.lsp.util'
30})
31
32local log = lsp.log
33local protocol = lsp.protocol
34local util = lsp.util
35local changetracking = lsp._changetracking
36
37-- Export these directly from rpc.
38---@nodoc
39lsp.rpc_response_error = lsp.rpc.rpc_response_error
40
41-- TODO improve handling of scratch buffers with LSP attached.
42
43--- Called by the client when trying to call a method that's not
44--- supported in any of the servers registered for the current buffer.
45---@param method (vim.lsp.protocol.Method.ClientToServer) name of the method
46function lsp._unsupported_method(method)
47  local msg = string.format(
48    'vim.lsp: method %q is not supported by any server activated for this buffer',
49    method
50  )
51  log.warn(msg)
52  return msg
53end
54
55---@param workspace_folders string|lsp.WorkspaceFolder[]?
56---@return lsp.WorkspaceFolder[]?
57function lsp._get_workspace_folders(workspace_folders)
58  if type(workspace_folders) == 'table' then
59    return workspace_folders
60  elseif type(workspace_folders) == 'string' then
61    return {
62      {
63        uri = vim.uri_from_fname(workspace_folders),
64        name = workspace_folders,
65      },
66    }
67  end
68end
69
70local wait_result_reason = { [-1] = 'timeout', [-2] = 'interrupted', [-3] = 'error' }
71
72local format_line_ending = {
73  ['unix'] = '\n',
74  ['dos'] = '\r\n',
75  ['mac'] = '\r',
76}
77
78---@param bufnr integer
79---@return string
80function lsp._buf_get_line_ending(bufnr)
81  return format_line_ending[vim.bo[bufnr].fileformat] or '\n'
82end
83
84local client_errors_base = table.maxn(lsp.rpc.client_errors)
85local client_errors_offset = 0
86
87---@param name string
88local function client_error(name)
89  client_errors_offset = client_errors_offset + 1
90  local index = client_errors_base + client_errors_offset
91  return { [name] = index, [index] = name }
92end
93
94--- Error codes to be used with `on_error` from |vim.lsp.start_client|.
95--- Can be used to look up the string from a the number or the number
96--- from the string.
97--- @nodoc
98lsp.client_errors = vim.tbl_extend(
99  'error',
100  lsp.rpc.client_errors,
101  client_error('BEFORE_INIT_CALLBACK_ERROR'),
102  client_error('ON_INIT_CALLBACK_ERROR'),
103  client_error('ON_ATTACH_ERROR'),
104  client_error('ON_EXIT_CALLBACK_ERROR')
105)
106
107--- Returns full text of buffer {bufnr} as a string.
108---
109---@param bufnr integer Buffer handle, or 0 for current.
110---@return string # Buffer text as string.
111function lsp._buf_get_full_text(bufnr)
112  local line_ending = lsp._buf_get_line_ending(bufnr)
113  local text = table.concat(api.nvim_buf_get_lines(bufnr, 0, -1, true), line_ending)
114  if vim.bo[bufnr].eol then
115    text = text .. line_ending
116  end
117  return text
118end
119
120--- @param client vim.lsp.Client
121--- @param config vim.lsp.ClientConfig
122--- @return boolean
123local function reuse_client_default(client, config)
124  if client.name ~= config.name or client:is_stopped() then
125    return false
126  end
127
128  local config_folders = lsp._get_workspace_folders(config.workspace_folders or config.root_dir)
129
130  if not config_folders or not next(config_folders) then
131    -- Reuse if the client was configured with no workspace folders
132    local client_config_folders =
133      lsp._get_workspace_folders(client.config.workspace_folders or client.config.root_dir)
134    return not client_config_folders or not next(client_config_folders)
135  end
136
137  for _, config_folder in ipairs(config_folders) do
138    local found = false
139    for _, client_folder in ipairs(client.workspace_folders or {}) do
140      if config_folder.uri == client_folder.uri then
141        found = true
142        break
143      end
144    end
145    if not found then
146      return false
147    end
148  end
149
150  return true
151end
152
153--- Creates and initializes a client with the given configuration.
154--- @param config vim.lsp.ClientConfig Configuration for the server.
155--- @return integer? client_id |vim.lsp.get_client_by_id()| Note: client may not be
156---         fully initialized. Use `on_init` to do any actions once
157---         the client has been initialized.
158--- @return string? # Error message, if any
159local function create_and_init_client(config)
160  local ok, res = pcall(require('vim.lsp.client').create, config)
161  if not ok then
162    return nil, res --[[@as string]]
163  end
164
165  local client = assert(res)
166
167  client:initialize()
168
169  return client.id, nil
170end
171
172--- @class vim.lsp.Config : vim.lsp.ClientConfig
173---
174--- See `cmd` in [vim.lsp.ClientConfig].
175--- See also `reuse_client` to dynamically decide (per-buffer) when `cmd` should be re-invoked.
176--- @field cmd? string[]|fun(dispatchers: vim.lsp.rpc.Dispatchers, config: vim.lsp.ClientConfig): vim.lsp.rpc.Client
177---
178--- Filetypes the client will attach to, or `nil` for ALL filetypes. To match files by name,
179--- pattern, or contents, you can define a custom filetype using |vim.filetype.add()|:
180--- ```lua
181--- vim.filetype.add({
182---   filename = {
183---     ['my_filename'] = 'my_filetype1',
184---   },
185---   pattern = {
186---     ['.*/etc/my_file_pattern/.*'] = 'my_filetype2',
187---   },
188--- })
189--- vim.lsp.config('…', {
190---   filetypes = { 'my_filetype1', 'my_filetype2' },
191--- })
192--- ```
193--- @field filetypes? string[]
194---
195--- Predicate which decides if a client should be re-used. Used on all running clients. The default
196--- implementation re-uses a client if name and root_dir matches.
197--- @field reuse_client? fun(client: vim.lsp.Client, config: vim.lsp.ClientConfig, bufnr: integer): boolean #
198---
199--- [lsp-root_dir()]()
200--- Decides the workspace root: the directory where the LSP server will base its workspaceFolders,
201--- rootUri, and rootPath on initialization. The function form must call the `on_dir` callback to
202--- provide the root dir, or LSP will not be activated for the buffer. Thus a `root_dir()` function
203--- can dynamically decide per-buffer whether to activate (or skip) LSP.
204--- See example at |vim.lsp.enable()|.
205--- @field root_dir? string|fun(bufnr: integer, on_dir:fun(root_dir?:string)) #
206---
207--- [lsp-root_markers]()
208--- Filename(s) (".git/", "package.json", …) used to decide the workspace root. Unused if `root_dir`
209--- is defined. The list order decides priority. To indicate "equal priority", specify names in
210--- a nested list `{ { 'a.txt', 'b.lua' }, ... }`.
211--- - For each item, Nvim will search upwards (from the buffer file) for that marker, or list of
212---   markers; search stops at the first directory containing that marker, and the directory is used
213---   as the root dir (workspace folder).
214--- - Example: Find the first ancestor directory containing file or directory "stylua.toml"; if not
215---   found, find the first ancestor containing ".git":
216---   ```
217---   root_markers = { 'stylua.toml', '.git' }
218---   ```
219--- - Example: Find the first ancestor directory containing EITHER "stylua.toml" or ".luarc.json";
220---   if not found, find the first ancestor containing ".git":
221---   ```
222---   root_markers = { { 'stylua.toml', '.luarc.json' }, '.git' }
223---   ```
224---
225--- @field root_markers? (string|string[])[]
226
227--- Sets the default configuration for an LSP client (or _all_ clients if the special name "*" is
228--- used).
229---
230--- Can also be accessed by table-indexing (`vim.lsp.config[…]`) to get the resolved config, or
231--- redefine the config (instead of "merging" with the config chain).
232---
233--- Examples:
234---
235--- - Add root markers for ALL clients:
236---   ```lua
237---   vim.lsp.config('*', {
238---       root_markers = { '.git', '.hg' },
239---     })
240---   ```
241--- - Add capabilities to ALL clients:
242---   ```lua
243---   vim.lsp.config('*', {
244---     capabilities = {
245---       textDocument = {
246---         semanticTokens = {
247---           multilineTokenSupport = true,
248---         }
249---       }
250---     }
251---   })
252---   ```
253--- - Add root markers and capabilities for "clangd":
254---   ```lua
255---   vim.lsp.config('clangd', {
256---     root_markers = { '.clang-format', 'compile_commands.json' },
257---     capabilities = {
258---       textDocument = {
259---         completion = {
260---           completionItem = {
261---             snippetSupport = true,
262---           }
263---         }
264---       }
265---     }
266---   })
267---   ```
268--- - (Re-)define the "clangd" configuration (overrides the resolved chain):
269---   ```lua
270---   vim.lsp.config.clangd = {
271---     cmd = {
272---       'clangd',
273---       '--clang-tidy',
274---       '--background-index',
275---       '--offset-encoding=utf-8',
276---     },
277---     root_markers = { '.clangd', 'compile_commands.json' },
278---     filetypes = { 'c', 'cpp' },
279---   }
280---   ```
281--- - Get the resolved configuration for "emmylua_ls":
282---   ```lua
283---   local cfg = vim.lsp.config.emmylua_ls
284---   ```
285---
286---@since 13
287---
288--- @param name string
289--- @param cfg vim.lsp.Config
290--- @type vim.lsp.config
291--- @diagnostic disable-next-line:assign-type-mismatch
292lsp.config = function(name, cfg)
293  local _, _ = name, cfg -- ignore unused
294  -- dummy proto for docs
295end
296
297lsp._enabled_configs = {} --- @type table<string,{resolved_config:vim.lsp.Config?}>
298
299--- If a config in vim.lsp.config() is accessed then the resolved config becomes invalid.
300--- @param name string
301local function invalidate_enabled_config(name)
302  if name == '*' then
303    for _, v in pairs(lsp._enabled_configs) do
304      v.resolved_config = nil
305    end
306  elseif lsp._enabled_configs[name] then
307    lsp._enabled_configs[name].resolved_config = nil
308  end
309end
310
311--- @param name any
312local function validate_config_name(name)
313  validate('name', name, function(value)
314    if type(value) ~= 'string' then
315      return false
316    end
317    if value ~= '*' and value:match('%*') then
318      return false, 'LSP config name cannot contain wildcard ("*")'
319    end
320    return true
321  end, 'non-wildcard string')
322end
323
324--- @nodoc
325--- @class vim.lsp.config
326--- @field [string] vim.lsp.Config?
327--- @field package _configs table<string,vim.lsp.Config>
328--- @overload fun(name: string, cfg: vim.lsp.Config)
329lsp.config = setmetatable({ _configs = {} }, {
330  --- @param self vim.lsp.config
331  --- @param name string
332  --- @return vim.lsp.Config?
333  __index = function(self, name)
334    validate_config_name(name)
335
336    local rconfig = lsp._enabled_configs[name] or {}
337
338    if not rconfig.resolved_config then
339      if name == '*' then
340        rconfig.resolved_config = self._configs['*'] or {}
341        return rconfig.resolved_config
342      end
343
344      -- Resolve configs from lsp/*.lua
345      -- Calls to vim.lsp.config in lsp/* have a lower precedence than calls from other sites.
346      local rtp_config --- @type vim.lsp.Config?
347      for _, v in ipairs(api.nvim_get_runtime_file(('lsp/%s.lua'):format(name), true)) do
348        local chunk, err = loadfile(v)
349        local config = assert(chunk, err)() ---@type any?
350        if type(config) == 'table' then
351          --- @type vim.lsp.Config?
352          rtp_config = vim.tbl_deep_extend('force', rtp_config or {}, config)
353        else
354          error(('%s: not a table'):format(v))
355        end
356      end
357
358      if not rtp_config and not self._configs[name] then
359        return
360      end
361
362      rconfig.resolved_config = vim.tbl_deep_extend(
363        'force',
364        self._configs['*'] or {},
365        rtp_config or {},
366        self._configs[name] or {}
367      )
368      rconfig.resolved_config.name = name
369    end
370
371    return rconfig.resolved_config
372  end,
373
374  --- @param self vim.lsp.config
375  --- @param name string
376  --- @param cfg vim.lsp.Config
377  __newindex = function(self, name, cfg)
378    validate_config_name(name)
379    local msg = ('table (hint: to resolve a config, use vim.lsp.config["%s"])'):format(name)
380    validate('cfg', cfg, 'table', msg)
381    invalidate_enabled_config(name)
382    self._configs[name] = cfg
383  end,
384
385  --- @param self vim.lsp.config
386  --- @param name string
387  --- @param cfg vim.lsp.Config
388  __call = function(self, name, cfg)
389    validate_config_name(name)
390    local msg = ('table (hint: to resolve a config, use vim.lsp.config["%s"])'):format(name)
391    validate('cfg', cfg, 'table', msg)
392    invalidate_enabled_config(name)
393    self[name] = vim.tbl_deep_extend('force', self._configs[name] or {}, cfg)
394  end,
395})
396
397--- @return string[]
398local function get_config_names()
399  local config_names = vim
400    .iter(api.nvim_get_runtime_file('lsp/*.lua', true))
401    :map(function(path)
402      local file_name = assert(path:match('[^/]*.lua$'))
403      return file_name:sub(0, #file_name - 4)
404    end)
405    :totable() --[[@as string[] ]]
406
407  vim.list_extend(config_names, vim.tbl_keys(lsp.config._configs))
408
409  return vim
410    .iter(config_names)
411    :unique()
412    :filter(function(name)
413      return name ~= '*'
414    end)
415    :totable()
416end
417
418--- Key-value pairs used to filter the returned configs.
419--- @class vim.lsp.get_configs.Filter
420--- @inlinedoc
421---
422--- If true, only return enabled configs. If false, only return configs that
423--- aren't enabled.
424--- @field enabled? boolean
425---
426--- Only return configs which attach to the given filetype.
427--- @field filetype? string
428
429--- Gets LSP configs.
430---
431--- See also [vim.lsp.get_clients()] to get the runtime values of dynamic fields like `root_dir`,
432--- which depend on the current buffer/workspace/etc.
433---
434--- WARNING: May eagerly (prematurely!) evaluate config files in 'runtimepath'.
435---
436--- @since 14
437--- @param filter? vim.lsp.get_configs.Filter
438--- @return vim.lsp.Config[]: List of |vim.lsp.Config| objects
439function lsp.get_configs(filter)
440  validate('filter', filter, 'table', true)
441
442  filter = filter or {}
443
444  local configs = {} --- @type vim.lsp.Config[]
445
446  local config_names = filter.enabled
447      -- Get enabled configs, without resolving other configs.
448      and vim.tbl_keys(lsp._enabled_configs)
449    or get_config_names()
450
451  for _, config_name in ipairs(config_names) do
452    local config = lsp.config[config_name]
453    if
454      config
455      and (filter.enabled ~= false or not lsp.is_enabled(config_name))
456      and (
457        filter.filetype == nil
458        or (config.filetypes ~= nil and vim.list_contains(config.filetypes, filter.filetype))
459      )
460    then
461      configs[#configs + 1] = config
462    end
463  end
464  return configs
465end
466
467local lsp_enable_autocmd_id --- @type integer?
468
469--- @param v any
470local function validate_cmd(v)
471  if type(v) == 'table' then
472    if vim.fn.executable(v[1]) == 0 then
473      return false, v[1] .. ' is not executable'
474    end
475    return true
476  end
477  return type(v) == 'function'
478end
479
480--- @param config vim.lsp.Config
481local function validate_config(config)
482  validate('cmd', config.cmd, validate_cmd, 'expected function or table with executable command')
483  validate('reuse_client', config.reuse_client, 'function', true)
484  validate('filetypes', config.filetypes, 'table', true)
485end
486
487--- Returns true if:
488--- 1. the config is managed by vim.lsp,
489--- 2. it applies to the given buffer, and
490--- 3. its config is valid (in particular: its `cmd` isn't broken).
491---
492--- @param bufnr integer
493--- @param config vim.lsp.Config
494--- @param logging boolean
495local function can_start(bufnr, config, logging)
496  if
497    type(config.filetypes) == 'table'
498    and not vim.tbl_contains(config.filetypes, vim.bo[bufnr].filetype)
499  then
500    return false
501  end
502
503  local config_ok, err = pcall(validate_config, config)
504  if not config_ok then
505    if logging then
506      log.error(('invalid "%s" config: %s'):format(config.name, err))
507    end
508    return false
509  end
510
511  return true
512end
513
514--- @param bufnr integer
515--- @param config vim.lsp.Config
516local function start_config(bufnr, config)
517  return vim.lsp.start(config, {
518    bufnr = bufnr,
519    reuse_client = config.reuse_client,
520    _root_markers = config.root_markers,
521  })
522end
523
524--- @param bufnr integer
525local function lsp_enable_callback(bufnr)
526  -- Only ever attach to buffers (including "help") that represent an actual file.
527  if vim.bo[bufnr].buftype ~= '' and vim.bo[bufnr].buftype ~= 'help' then
528    return
529  end
530
531  -- Stop any clients that no longer apply to this buffer.
532  local clients = lsp.get_clients({ bufnr = bufnr, _uninitialized = true })
533  for _, client in ipairs(clients) do
534    -- Don't index into lsp.config[…] unless is_enabled() is true.
535    if
536      lsp.is_enabled(client.name)
537      -- Check that the client is managed by vim.lsp.config before deciding to detach it!
538      and lsp.config[client.name]
539    then
540      if can_start(bufnr, lsp.config[client.name], false) then
541        -- When switch between lsp supported filetype (e.g. json to jsonc like #39498),
542        -- client should send `textDocument/didClose` + `textDocument/didOpen` with new language id
543        local new_language_id = client.get_language_id(bufnr, vim.bo[bufnr].filetype)
544        local old_language_id = client.attached_buffers[bufnr] ---@type string?
545        if old_language_id and old_language_id ~= new_language_id then
546          client:_text_document_did_close_handler(bufnr)
547          client.attached_buffers[bufnr] = new_language_id
548          client:_text_document_did_open_handler(bufnr)
549        end
550      else
551        lsp.buf_detach_client(bufnr, client.id)
552      end
553    end
554  end
555
556  -- Start any clients that apply to this buffer.
557  for name in vim.spairs(lsp._enabled_configs) do
558    local config = lsp.config[name]
559    if config and can_start(bufnr, config, true) then
560      -- Deepcopy config so changes done in the client
561      -- do not propagate back to the enabled configs.
562      config = vim.deepcopy(config)
563
564      if type(config.root_dir) == 'function' then
565        ---@param root_dir string?
566        config.root_dir(bufnr, function(root_dir)
567          config.root_dir = root_dir
568          vim.schedule(function()
569            start_config(bufnr, config)
570          end)
571        end)
572      else
573        start_config(bufnr, config)
574      end
575    end
576  end
577end
578
579--- Enables a [lsp-config]: automatically attaches the client to any buffer based on the config
580--- `filetypes`, `root_markers`, and `root_dir`. See [lsp-activate] for details.
581---
582--- To disable, pass `enable=false`: Stops related clients and servers (force-stops servers after
583--- a timeout, unless `exit_timeout=false`).
584---
585--- Raises an error under the following conditions:
586--- - `{name}` is not a valid LSP config name (for example, `'*'`).
587--- - `{name}` corresponds to an LSP config file which raises an error.
588---
589--- If an error is raised when multiple names are provided, this function will
590--- have no side-effects; it will not enable/disable any configs, including
591--- ones which contain no errors.
592---
593--- Examples:
594---
595--- ```lua
596--- vim.lsp.enable('clangd')
597--- vim.lsp.enable({'emmylua_ls', 'pyright'})
598--- ```
599---
600--- Example: To _dynamically_ decide whether LSP is activated, define a |lsp-root_dir()| function
601--- which calls `on_dir()` only when you want that config to activate:
602---
603--- ```lua
604--- vim.lsp.config('emmylua_ls', {
605---   root_dir = function(bufnr, on_dir)
606---     if vim.fs.ext(vim.fn.bufname(bufnr)) ~= 'txt' then
607---       on_dir(vim.fn.getcwd())
608---     end
609---   end
610--- })
611--- ```
612---
613---@since 13
614---
615--- @param name string|string[] Name(s) of client(s) to enable.
616--- @param enable? boolean If `true|nil`, enables auto-activation of the given LSP config on current
617--- and future buffers. If `false`, disables auto-activation and stops related LSP clients and
618--- servers (force-stops servers after `exit_timeout` milliseconds).
619function lsp.enable(name, enable)
620  validate('name', name, { 'string', 'table' })
621
622  local names = vim._ensure_list(name) --[[@as string[] ]]
623
624  -- Check for errors, and abort with no side-effects if there is one.
625  for _, nm in ipairs(names) do
626    if nm:match('%*') then
627      error('LSP config name cannot contain wildcard ("*")')
628    end
629
630    -- Raise error if `lsp.config[nm]` raises an error, instead of waiting for
631    -- the error to be triggered by `lsp_enable_callback()`.
632    if enable ~= false then
633      _ = lsp.config[nm]
634    end
635  end
636
637  -- Now that there can be no errors, enable/disable all names.
638  for _, nm in ipairs(names) do
639    lsp._enabled_configs[nm] = enable ~= false and {} or nil
640  end
641
642  if not next(lsp._enabled_configs) then
643    -- If there are no remaining LSPs enabled, remove the enable autocmd.
644    if lsp_enable_autocmd_id then
645      api.nvim_del_autocmd(lsp_enable_autocmd_id)
646      lsp_enable_autocmd_id = nil
647    end
648  else
649    -- Only ever create autocmd once to reuse computation of config merging.
650    lsp_enable_autocmd_id = lsp_enable_autocmd_id
651      or nvim_on('FileType', api.nvim_create_augroup('nvim.lsp.enable'), function(ev)
652        lsp_enable_callback(ev.buf)
653      end)
654  end
655
656  -- Ensure any pre-existing buffers start/stop their LSP clients.
657  if enable ~= false then
658    if (vim.v.vim_did_enter == 1 or vim.fn.did_filetype() == 1) and next(lsp._enabled_configs) then
659      vim.cmd.doautoall('nvim.lsp.enable FileType')
660    end
661  else
662    for _, nm in ipairs(names) do
663      for _, client in ipairs(lsp.get_clients({ name = nm })) do
664        client:stop(client.exit_timeout)
665      end
666    end
667  end
668end
669
670--- Checks if the given LSP config is enabled (globally, not per-buffer).
671---
672--- Unlike `vim.lsp.config['…']`, this does not have the side-effect of resolving the config.
673---
674--- @param name string Config name
675--- @return boolean
676function lsp.is_enabled(name)
677  return lsp._enabled_configs[name] ~= nil
678end
679
680--- @class vim.lsp.start.Opts
681--- @inlinedoc
682---
683--- Predicate used to decide if a client should be re-used. Used on all
684--- running clients. The default implementation re-uses a client if it has the
685--- same name and if the given workspace folders (or root_dir) are all included
686--- in the client's workspace folders.
687--- @field reuse_client? fun(client: vim.lsp.Client, config: vim.lsp.ClientConfig, bufnr: integer): boolean
688---
689--- Buffer handle to attach to if starting or re-using a client (0 for current).
690--- @field bufnr? integer
691---
692--- Whether to attach the client to a buffer (default true).
693--- If set to `false`, `reuse_client` and `bufnr` will be ignored.
694--- @field attach? boolean
695---
696--- Suppress error reporting if the LSP server fails to start (default false).
697--- @field silent? boolean
698---
699--- @field package _root_markers? (string|string[])[]
700
701--- Create a new LSP client and start a language server or reuses an already
702--- running client if one is found matching `name` and `root_dir`.
703--- Attaches the current buffer to the client.
704---
705--- Example:
706---
707--- ```lua
708--- vim.lsp.start({
709---    name = 'my-server-name',
710---    cmd = {'name-of-language-server-executable'},
711---    root_dir = vim.fs.root(0, {'pyproject.toml', 'setup.py'}),
712--- })
713--- ```
714---
715--- See |vim.lsp.ClientConfig| for all available options. The most important are:
716---
717--- - `name` arbitrary name for the LSP client. Should be unique per language server.
718--- - `cmd` command string[] or function. See also |lsp-server|.
719--- - `root_dir` path to the project root. By default this is used to decide if an existing client
720---   should be re-used. The example above uses |vim.fs.root()| to detect the root by traversing
721---   the file system upwards starting from the current directory until either a `pyproject.toml`
722---   or `setup.py` file is found.
723--- - `workspace_folders` list of `{ uri:string, name: string }` tables specifying the project root
724---   folders used by the language server. If `nil` the property is derived from `root_dir` for
725---   convenience.
726---
727--- Language servers use this information to discover metadata like the
728--- dependencies of your project and they tend to index the contents within the
729--- project folder.
730---
731---
732--- To ensure a language server is only started for languages it can handle,
733--- make sure to call |vim.lsp.start()| within a |FileType| autocmd.
734--- Either use |:au|, |nvim_create_autocmd()| or put the call in a
735--- `ftplugin/<filetype_name>.lua` (See |ftplugin-name|)
736---
737--- @since 10
738---
739--- @param config vim.lsp.ClientConfig Configuration for the server.
740--- @param opts vim.lsp.start.Opts? Optional keyword arguments.
741--- @return integer? client_id
742function lsp.start(config, opts)
743  opts = opts or {}
744  local reuse_client = opts.reuse_client or reuse_client_default
745  local bufnr = vim._resolve_bufnr(opts.bufnr)
746
747  if not config.root_dir and opts._root_markers then
748    validate('root_markers', opts._root_markers, 'table')
749    config = vim.deepcopy(config)
750
751    config.root_dir = vim.fs.root(bufnr, opts._root_markers)
752  end
753
754  if
755    not config.root_dir
756    and (not config.workspace_folders or #config.workspace_folders == 0)
757    and config.workspace_required
758  then
759    log.info(
760      ('skipping config "%s": workspace_required=true, no workspace found'):format(config.name)
761    )
762    return
763  end
764
765  for _, client in pairs(lsp.client._all) do
766    if reuse_client(client, config, bufnr) then
767      if opts.attach == false then
768        return client.id
769      end
770
771      if lsp.buf_attach_client(bufnr, client.id) then
772        return client.id
773      end
774      return
775    end
776  end
777
778  local client_id, err = create_and_init_client(config)
779  if err then
780    if not opts.silent then
781      vim.notify(err, vim.log.levels.WARN)
782    end
783    return
784  end
785
786  if opts.attach == false then
787    return client_id
788  end
789
790  if client_id and lsp.buf_attach_client(bufnr, client_id) then
791    return client_id
792  end
793end
794
795--- Consumes the latest progress messages from all clients and formats them as a string.
796--- Empty if there are no clients or if no new messages
797---
798---@return string
799function lsp.status()
800  local percentage = nil
801  local messages = {} --- @type string[]
802  for _, client in ipairs(vim.lsp.get_clients()) do
803    --- @diagnostic disable-next-line:no-unknown
804    for progress in client.progress do
805      --- @cast progress {token: lsp.ProgressToken, value: lsp.LSPAny}
806      local value = progress.value
807      if type(value) == 'table' and value.kind then
808        -- Progress handlers carry the title over to report and end messages.
809        local message = value.message and (value.title .. ': ' .. value.message) or value.title --[[@as string?]]
810        messages[#messages + 1] = message
811        if type(value.percentage) == 'number' then
812          percentage = math.max(percentage or 0, value.percentage --[[@as number]])
813        end
814      end
815      -- else: Doesn't look like work done progress and can be in any format
816      -- Just ignore it as there is no sensible way to display it
817    end
818  end
819  local message = table.concat(messages, ', ')
820  if percentage then
821    return string.format('%3d%%: %s', percentage, message)
822  end
823  return message
824end
825
826-- Determines whether the given option can be set by `set_defaults`.
827---@param bufnr integer
828---@param option string
829---@return boolean
830local function is_empty_or_default(bufnr, option)
831  if vim.bo[bufnr][option] == '' then
832    return true
833  end
834
835  local info = api.nvim_get_option_info2(option, { buf = bufnr })
836  ---@param e vim.fn.getscriptinfo.ret
837  local scriptinfo = vim.tbl_filter(function(e)
838    return e.sid == info.last_set_sid
839  end, vim.fn.getscriptinfo())
840
841  if #scriptinfo ~= 1 then
842    return false
843  end
844
845  return vim.startswith(scriptinfo[1].name, vim.fn.expand('$VIMRUNTIME'))
846end
847
848---@param client vim.lsp.Client
849---@param bufnr integer
850function lsp._set_defaults(client, bufnr)
851  if
852    client:supports_method('textDocument/definition') and is_empty_or_default(bufnr, 'tagfunc')
853  then
854    vim.bo[bufnr].tagfunc = lsp.tagfunc
855  end
856  if
857    client:supports_method('textDocument/completion') and is_empty_or_default(bufnr, 'omnifunc')
858  then
859    vim.bo[bufnr].omnifunc = lsp.omnifunc
860  end
861  if
862    (
863      client:supports_method('textDocument/rangeFormatting')
864      or client:supports_method('textDocument/formatting')
865    )
866    and is_empty_or_default(bufnr, 'formatprg')
867    and is_empty_or_default(bufnr, 'formatexpr')
868  then
869    vim.bo[bufnr].formatexpr = 'v:lua.vim.lsp.formatexpr()'
870  end
871  vim._with({ buf = bufnr }, function()
872    if
873      client:supports_method('textDocument/hover')
874      and is_empty_or_default(bufnr, 'keywordprg')
875      and vim.fn.maparg('K', 'n', false, false) == ''
876    then
877      vim.keymap.set('n', 'K', function()
878        vim.lsp.buf.hover()
879      end, { buf = bufnr, desc = 'vim.lsp.buf.hover()' })
880    end
881  end)
882end
883
884--- @deprecated
885--- Starts and initializes a client with the given configuration.
886--- @param config vim.lsp.ClientConfig Configuration for the server.
887--- @return integer? client_id |vim.lsp.get_client_by_id()| Note: client may not be
888---         fully initialized. Use `on_init` to do any actions once
889---         the client has been initialized.
890--- @return string? # Error message, if any
891function lsp.start_client(config)
892  vim.deprecate('vim.lsp.start_client()', 'vim.lsp.start()', '0.13')
893  return create_and_init_client(config)
894end
895
896---Buffer lifecycle handler for textDocument/didSave
897--- @param bufnr integer
898local function text_document_did_save_handler(bufnr)
899  changetracking._send_did_save(bufnr)
900end
901
902--- @type table<integer,true>
903local attached_buffers = {}
904
905--- @param bufnr integer
906local function buf_attach(bufnr)
907  if attached_buffers[bufnr] then
908    return
909  end
910  attached_buffers[bufnr] = true
911
912  local uri = vim.uri_from_bufnr(bufnr)
913  local augroup = ('nvim.lsp.b_%d_save'):format(bufnr)
914  local group = api.nvim_create_augroup(augroup, { clear = true })
915  nvim_on('BufWritePre', group, {
916    buf = bufnr,
917    desc = 'vim.lsp: textDocument/willSave',
918  }, function(ctx)
919    for _, client in ipairs(lsp.get_clients({ bufnr = ctx.buf })) do
920      local params = {
921        textDocument = {
922          uri = uri,
923        },
924        reason = protocol.TextDocumentSaveReason.Manual, ---@type integer
925      }
926      if client:supports_method('textDocument/willSave') then
927        client:notify('textDocument/willSave', params, bufnr)
928      end
929      if client:supports_method('textDocument/willSaveWaitUntil') then
930        local result, err =
931          client:request_sync('textDocument/willSaveWaitUntil', params, 1000, ctx.buf)
932        if result and result.result then
933          util.apply_text_edits(result.result, ctx.buf, client.offset_encoding)
934        elseif err then
935          log.error(vim.inspect(err))
936        end
937      end
938    end
939  end)
940  nvim_on('BufWritePost', group, {
941    buf = bufnr,
942    desc = 'vim.lsp: textDocument/didSave handler',
943  }, function(ctx)
944    text_document_did_save_handler(ctx.buf)
945  end)
946  -- First time, so attach and set up stuff.
947  api.nvim_buf_attach(bufnr, false, {
948    on_lines = function(_, _, changedtick, firstline, lastline, new_lastline)
949      if #lsp.get_clients({ bufnr = bufnr }) == 0 then
950        -- detach if there are no clients
951        return #lsp.get_clients({ bufnr = bufnr, _uninitialized = true }) == 0
952      end
953      util.buf_versions[bufnr] = changedtick
954      changetracking.send_changes(bufnr, firstline, lastline, new_lastline)
955    end,
956
957    on_reload = function()
958      local clients = lsp.get_clients({ bufnr = bufnr })
959      local params = { textDocument = { uri = uri } }
960      for _, client in ipairs(clients) do
961        changetracking.reset_buf(client, bufnr)
962        if client:supports_method('textDocument/didClose') then
963          client:notify('textDocument/didClose', params, bufnr)
964        end
965      end
966      for _, client in ipairs(clients) do
967        client:_text_document_did_open_handler(bufnr)
968      end
969    end,
970
971    on_detach = function()
972      local clients = lsp.get_clients({ bufnr = bufnr, _uninitialized = true })
973      for _, client in ipairs(clients) do
974        client:_on_detach(bufnr)
975      end
976      attached_buffers[bufnr] = nil
977      util.buf_versions[bufnr] = nil
978    end,
979
980    -- TODO if we know all of the potential clients ahead of time, then we
981    -- could conditionally set this.
982    --      utf_sizes = size_index > 1;
983    utf_sizes = true,
984  })
985end
986
987--- Implements the `textDocument/did…` notifications required to track a buffer
988--- for any language server.
989---
990--- Without calling this, the server won't be notified of changes to a buffer.
991---
992---@param bufnr (integer) Buffer handle, or 0 for current
993---@param client_id (integer) Client id
994---@return boolean success `true` if client was attached successfully; `false` otherwise
995function lsp.buf_attach_client(bufnr, client_id)
996  validate('bufnr', bufnr, 'number', true)
997  validate('client_id', client_id, 'number')
998  bufnr = vim._resolve_bufnr(bufnr)
999  if not api.nvim_buf_is_loaded(bufnr) then
1000    log.warn(string.format('buf_attach_client called on unloaded buffer (id: %d): ', bufnr))
1001    return false
1002  end
1003
1004  local client = lsp.get_client_by_id(client_id)
1005  if not client then
1006    return false
1007  end
1008
1009  buf_attach(bufnr)
1010
1011  if client.attached_buffers[bufnr] then
1012    return true
1013  end
1014
1015  client.attached_buffers[bufnr] = client.get_language_id(bufnr, vim.bo[bufnr].filetype)
1016
1017  -- This is our first time attaching this client to this buffer.
1018  -- Send didOpen for the client if it is initialized. If it isn't initialized
1019  -- then it will send didOpen on initialize.
1020  if client.initialized then
1021    client:on_attach(bufnr)
1022  end
1023  return true
1024end
1025
1026--- Detaches client from the specified buffer.
1027--- Note: While the server is notified that the text document (buffer)
1028--- was closed, it is still able to send notifications should it ignore this notification.
1029---
1030---@param bufnr integer Buffer handle, or 0 for current
1031---@param client_id integer Client id
1032function lsp.buf_detach_client(bufnr, client_id)
1033  validate('bufnr', bufnr, 'number', true)
1034  validate('client_id', client_id, 'number')
1035  bufnr = vim._resolve_bufnr(bufnr)
1036
1037  local client = lsp.get_client_by_id(client_id)
1038  if not client or not client.attached_buffers[bufnr] then
1039    vim.notify(
1040      string.format(
1041        'Buffer (id: %d) is not attached to client (id: %d). Cannot detach.',
1042        bufnr,
1043        client_id
1044      )
1045    )
1046    return
1047  else
1048    client:_on_detach(bufnr)
1049  end
1050end
1051
1052--- Checks if a buffer is attached for a particular client.
1053---
1054---@param bufnr integer Buffer handle, or 0 for current
1055---@param client_id integer the client id
1056function lsp.buf_is_attached(bufnr, client_id)
1057  return lsp.get_clients({ bufnr = bufnr, id = client_id, _uninitialized = true })[1] ~= nil
1058end
1059
1060--- Gets a client by id, or nil if the id is invalid or the client was stopped.
1061--- The returned client may not yet be fully initialized.
1062---
1063---@param client_id integer client id
1064---
1065---@return vim.lsp.Client? client rpc object
1066function lsp.get_client_by_id(client_id)
1067  return lsp.client._all[client_id]
1068end
1069
1070--- Returns list of buffers attached to client_id.
1071---
1072---@deprecated
1073---@param client_id integer client id
1074---@return integer[] buffers list of buffer ids
1075function lsp.get_buffers_by_client_id(client_id)
1076  vim.deprecate(
1077    'vim.lsp.get_buffers_by_client_id()',
1078    'vim.lsp.get_client_by_id(id).attached_buffers',
1079    '0.13'
1080  )
1081  local client = lsp.get_client_by_id(client_id)
1082  return client and vim.tbl_keys(client.attached_buffers) or {}
1083end
1084
1085--- Stops a client(s).
1086---
1087--- You can also use the `stop()` function on a |vim.lsp.Client| object.
1088--- To stop all clients:
1089---
1090--- ```lua
1091--- vim.lsp.stop_client(vim.lsp.get_clients())
1092--- ```
1093---
1094--- By default asks the server to shutdown, unless stop was requested already for this client (then
1095--- force-stop is attempted, unless `exit_timeout=false`).
1096---
1097---@deprecated
1098---@param client_id integer|integer[]|vim.lsp.Client[] id, list of id's, or list of |vim.lsp.Client| objects
1099---@param force? boolean|integer See |Client:stop()|
1100function lsp.stop_client(client_id, force)
1101  vim.deprecate('vim.lsp.stop_client()', 'vim.lsp.Client:stop()', '0.13')
1102  --- @type (integer|vim.lsp.Client)[]
1103  local ids = type(client_id) == 'table' and client_id or { client_id }
1104  for _, id in ipairs(ids) do
1105    if type(id) == 'table' then
1106      if id.stop then
1107        id:stop(force)
1108      end
1109    else
1110      local client = lsp.get_client_by_id(id)
1111      if client then
1112        client:stop(force)
1113      end
1114    end
1115  end
1116end
1117
1118--- Key-value pairs used to filter the returned clients.
1119--- @class vim.lsp.get_clients.Filter
1120--- @inlinedoc
1121---
1122--- Only return clients with the given id
1123--- @field id? integer
1124---
1125--- Only return clients attached to this buffer
1126--- @field bufnr? integer
1127---
1128--- Only return clients with the given name
1129--- @field name? string
1130---
1131--- Only return clients supporting the given method
1132--- @field method? vim.lsp.protocol.Method.ClientToServer
1133---
1134--- Also return uninitialized clients.
1135--- @field package _uninitialized? boolean
1136
1137--- Gets active clients.
1138---
1139---@since 12
1140---
1141---@param filter? vim.lsp.get_clients.Filter
1142---@return vim.lsp.Client[]: List of |vim.lsp.Client| objects
1143function lsp.get_clients(filter)
1144  validate('filter', filter, 'table', true)
1145
1146  filter = filter or {}
1147
1148  local clients = {} --- @type vim.lsp.Client[]
1149
1150  local bufnr = filter.bufnr and vim._resolve_bufnr(filter.bufnr)
1151
1152  for _, client in pairs(lsp.client._all) do
1153    if
1154      client
1155      and (filter.id == nil or client.id == filter.id)
1156      and (filter.bufnr == nil or client.attached_buffers[bufnr])
1157      and (filter.name == nil or client.name == filter.name)
1158      and (filter.method == nil or client:supports_method(filter.method, filter.bufnr))
1159      and (filter._uninitialized or client.initialized)
1160    then
1161      clients[#clients + 1] = client
1162    end
1163  end
1164  return clients
1165end
1166
1167-- Minimum time before warning about LSP exit_timeout on Nvim exit.
1168local min_warn_exit_timeout = 100
1169
1170nvim_on('VimLeavePre', nil, { desc = 'vim.lsp: exit handler' }, function()
1171  local active_clients = lsp.get_clients()
1172  log.info('exit_handler', active_clients)
1173
1174  local max_timeout = 0
1175  for _, client in pairs(active_clients) do
1176    max_timeout = math.max(max_timeout, vim._tointeger(client.exit_timeout) or 0)
1177    client:stop(client.exit_timeout)
1178  end
1179
1180  local exit_warning_timer = max_timeout > min_warn_exit_timeout
1181    and vim.defer_fn(function()
1182      api.nvim_echo({
1183        {
1184          string.format('Waiting %ss for LSP exit (Press Ctrl-C to force exit)', max_timeout / 1e3),
1185          'WarningMsg',
1186        },
1187      }, true, {})
1188    end, min_warn_exit_timeout)
1189
1190  vim.wait(max_timeout, function()
1191    return vim.iter(active_clients):all(function(client)
1192      return client.rpc.is_closing()
1193    end)
1194  end)
1195
1196  if exit_warning_timer and not exit_warning_timer:is_closing() then
1197    exit_warning_timer:close()
1198  end
1199end)
1200
1201---@nodoc
1202--- Sends an async request for all active clients attached to the
1203--- buffer.
1204---
1205---@param bufnr (integer) Buffer handle, or 0 for current.
1206---@param method (vim.lsp.protocol.Method.ClientToServer.Request) LSP method name
1207---@param params? table|(fun(client: vim.lsp.Client, bufnr: integer): table?) Parameters to send to the server
1208---@param handler? lsp.Handler See |lsp-handler|
1209---       If nil, follows resolution strategy defined in |lsp-handler-configuration|
1210---@param on_unsupported? fun()
1211---       The function to call when the buffer has no clients that support the given method.
1212---       Defaults to an `ERROR` level notification.
1213---@return table<integer, integer> client_request_ids Map of client-id:request-id pairs
1214---for all successful requests.
1215---@return function _cancel_all_requests Function which can be used to
1216---cancel all the requests. You could instead
1217---iterate all clients and call their `cancel_request()` methods.
1218function lsp.buf_request(bufnr, method, params, handler, on_unsupported)
1219  validate('bufnr', bufnr, 'number', true)
1220  validate('method', method, 'string')
1221  validate('handler', handler, 'function', true)
1222  validate('on_unsupported', on_unsupported, 'function', true)
1223
1224  bufnr = vim._resolve_bufnr(bufnr)
1225  local method_supported = false
1226  local clients = lsp.get_clients({ bufnr = bufnr })
1227  local client_request_ids = {} --- @type table<integer,integer>
1228  for _, client in ipairs(clients) do
1229    if client:supports_method(method, bufnr) then
1230      method_supported = true
1231
1232      local cparams = type(params) == 'function' and params(client, bufnr) or params --[[@as table?]]
1233      local request_success, request_id = client:request(method, cparams, handler, bufnr)
1234      -- This could only fail if the client shut down in the time since we looked
1235      -- it up and we did the request, which should be rare.
1236      if request_success then
1237        client_request_ids[client.id] = request_id
1238      end
1239    end
1240  end
1241
1242  -- if has client but no clients support the given method, notify the user
1243  if next(clients) and not method_supported then
1244    if on_unsupported == nil then
1245      vim.notify(lsp._unsupported_method(method), vim.log.levels.ERROR)
1246    else
1247      on_unsupported()
1248    end
1249    vim.cmd.redraw()
1250    return {}, function() end
1251  end
1252
1253  local function _cancel_all_requests()
1254    for client_id, request_id in pairs(client_request_ids) do
1255      local client = lsp.get_client_by_id(client_id)
1256      if client and client.requests[request_id] then
1257        client:cancel_request(request_id)
1258      end
1259    end
1260  end
1261
1262  return client_request_ids, _cancel_all_requests
1263end
1264
1265--- Sends an async request for all active clients attached to the buffer and executes the `handler`
1266--- callback with the combined result.
1267---
1268---@since 7
1269---
1270---@param bufnr (integer) Buffer handle, or 0 for current.
1271---@param method (vim.lsp.protocol.Method.ClientToServer.Request) LSP method name
1272---@param params? table|(fun(client: vim.lsp.Client, bufnr: integer): table?) Parameters to send to the server.
1273---               Can also be passed as a function that returns the params table for cases where
1274---               parameters are specific to the client.
1275---@param handler lsp.MultiHandler (function)
1276--- Handler called after all requests are completed. Server results are passed as
1277--- a `client_id:result` map.
1278---@return function cancel Function that cancels all requests.
1279function lsp.buf_request_all(bufnr, method, params, handler)
1280  local results = {} --- @type table<integer,{err: lsp.ResponseError?, result: any, context: lsp.HandlerContext}>
1281  local remaining --- @type integer?
1282
1283  local _, cancel = lsp.buf_request(bufnr, method, params, function(err, result, ctx, config)
1284    if not remaining then
1285      -- Calculate as late as possible in case a client is removed during the request
1286      remaining = #lsp.get_clients({ bufnr = bufnr, method = method })
1287    end
1288
1289    -- The error key is deprecated and will be removed in 0.13
1290    results[ctx.client_id] = { err = err, error = err, result = result, context = ctx }
1291    remaining = remaining - 1
1292
1293    if remaining == 0 then
1294      handler(results, ctx, config)
1295    end
1296  end)
1297
1298  return cancel
1299end
1300
1301--- Sends a request to all server and waits for the response of all of them.
1302---
1303--- Calls |vim.lsp.buf_request_all()| but blocks Nvim while awaiting the result.
1304--- Parameters are the same as |vim.lsp.buf_request_all()| but the result is
1305--- different. Waits a maximum of {timeout_ms}.
1306---
1307---@since 7
1308---
1309---@param bufnr integer Buffer handle, or 0 for current.
1310---@param method vim.lsp.protocol.Method.ClientToServer.Request LSP method name
1311---@param params? table|(fun(client: vim.lsp.Client, bufnr: integer): table?) Parameters to send to the server.
1312---               Can also be passed as a function that returns the params table for cases where
1313---               parameters are specific to the client.
1314---@param timeout_ms integer? Maximum time in milliseconds to wait for a result.
1315---                           (default: `1000`)
1316---@return table<integer, {error: lsp.ResponseError?, result: any}>? result Map of client_id:request_result.
1317---@return string? err On timeout, cancel, or error, `err` is a string describing the failure reason, and `result` is nil.
1318function lsp.buf_request_sync(bufnr, method, params, timeout_ms)
1319  local request_results ---@type table
1320
1321  local cancel = lsp.buf_request_all(bufnr, method, params, function(it)
1322    request_results = it
1323  end)
1324
1325  local wait_result, reason = vim.wait(timeout_ms or 1000, function()
1326    return request_results ~= nil
1327  end, 10)
1328
1329  if not wait_result then
1330    cancel()
1331    return nil, wait_result_reason[reason]
1332  end
1333
1334  return request_results
1335end
1336
1337--- Send a notification to a server
1338---
1339---@since 7
1340---
1341---@param bufnr integer? The number of the buffer
1342---@param method vim.lsp.protocol.Method.ClientToServer.Notification Name of the request method
1343---@param params any Arguments to send to the server
1344---
1345---@return boolean success true if any client returns true; false otherwise
1346function lsp.buf_notify(bufnr, method, params)
1347  validate('bufnr', bufnr, 'number', true)
1348  validate('method', method, 'string')
1349  local resp = false
1350  for _, client in ipairs(lsp.get_clients({ bufnr = bufnr })) do
1351    if client.rpc.notify(method, params) then
1352      resp = true
1353    end
1354  end
1355  return resp
1356end
1357
1358--- Implements 'omnifunc' compatible LSP completion.
1359---
1360---@see |complete-functions|
1361---@see |complete-items|
1362---@see |CompleteDone|
1363---
1364---@param findstart integer 0 or 1, decides behavior
1365---@param base integer findstart=0, text to match against
1366---
1367---@return integer|table Decided by {findstart}:
1368--- - findstart=1: column where the completion starts, or -2 or -3
1369--- - findstart=0: list of matches (actually just calls |complete()|)
1370function lsp.omnifunc(findstart, base)
1371  return vim.lsp.completion._omnifunc(findstart, base)
1372end
1373
1374--- @class vim.lsp.formatexpr.Opts
1375--- @inlinedoc
1376---
1377--- The timeout period for the formatting request.
1378--- (default: 500ms).
1379--- @field timeout_ms? integer
1380
1381--- Provides an interface between the built-in client and a `formatexpr` function.
1382---
1383--- Currently only supports a single client. This can be set via
1384--- `vim.bo[bufnr].formatexpr = vim.lsp.formatexpr`, or with a wrapper to pass options:
1385---
1386--- ```lua
1387--- vim.bo[bufnr].formatexpr = function()
1388---   return vim.lsp.formatexpr({ timeout_ms = 250 })
1389--- end
1390--- ```
1391---
1392---@param opts? vim.lsp.formatexpr.Opts
1393function lsp.formatexpr(opts)
1394  opts = opts or {}
1395  local timeout_ms = opts.timeout_ms or 500
1396
1397  if vim.list_contains({ 'i', 'R' }, vim.fn.mode()) then
1398    -- `formatexpr` is also called when exceeding `textwidth` in insert mode
1399    -- fall back to internal formatting
1400    return 1
1401  end
1402
1403  local start_lnum = vim.v.lnum
1404  local end_lnum = start_lnum + vim.v.count - 1
1405
1406  if start_lnum <= 0 or end_lnum <= 0 then
1407    return 0
1408  end
1409  local bufnr = api.nvim_get_current_buf()
1410  local range_is_whole_buffer = start_lnum == 1 and end_lnum == api.nvim_buf_line_count(bufnr)
1411  for _, client in pairs(lsp.get_clients({ bufnr = bufnr })) do
1412    local params = util.make_formatting_params()
1413    local method ---@type vim.lsp.protocol.Method.ClientToServer.Request?
1414    if client:supports_method('textDocument/rangeFormatting') then
1415      local end_line = vim.fn.getline(end_lnum)
1416      local end_col = vim.str_utfindex(end_line, client.offset_encoding)
1417      --- @cast params +lsp.DocumentRangeFormattingParams
1418      params.range = {
1419        start = {
1420          line = start_lnum - 1,
1421          character = 0,
1422        },
1423        ['end'] = {
1424          line = end_lnum - 1,
1425          character = end_col,
1426        },
1427      }
1428      method = 'textDocument/rangeFormatting'
1429    elseif client:supports_method('textDocument/formatting') and range_is_whole_buffer then
1430      method = 'textDocument/formatting'
1431    end
1432
1433    if method then
1434      local response = client:request_sync(method, params, timeout_ms, bufnr)
1435      if response and response.result then
1436        util.apply_text_edits(response.result, bufnr, client.offset_encoding)
1437        return 0
1438      end
1439    end
1440  end
1441
1442  -- do not run builtin formatter.
1443  return 0
1444end
1445
1446--- Provides an interface between the built-in client and a `foldexpr` function.
1447---
1448--- To use, set 'foldmethod' to "expr" and set the value of 'foldexpr':
1449---
1450--- ```lua
1451--- vim.o.foldmethod = 'expr'
1452--- vim.o.foldexpr = vim.lsp.foldexpr
1453--- ```
1454---
1455--- Or use it only when supported by checking for the "textDocument/foldingRange"
1456--- capability in an |LspAttach| autocommand. Example:
1457---
1458--- ```lua
1459--- vim.o.foldmethod = 'expr'
1460--- -- Default to treesitter folding
1461--- vim.o.foldexpr = vim.treesitter.foldexpr
1462--- -- Prefer LSP folding if client supports it
1463--- vim.api.nvim_create_autocmd('LspAttach', {
1464---   callback = function(ev)
1465---     local client = vim.lsp.get_client_by_id(ev.data.client_id)
1466---     if client:supports_method('textDocument/foldingRange') then
1467---       local win = vim.api.nvim_get_current_win()
1468---       vim.wo[win][0].foldexpr = vim.lsp.foldexpr
1469---     end
1470---   end,
1471--- })
1472--- ```
1473---
1474---@param lnum integer line number
1475function lsp.foldexpr(lnum)
1476  return vim.lsp._folding_range.foldexpr(lnum)
1477end
1478
1479--- Close all {kind} of folds in the window with {winid}.
1480---
1481--- To automatically fold imports when opening a file, you can use an autocmd:
1482---
1483--- ```lua
1484--- vim.api.nvim_create_autocmd('LspNotify', {
1485---   callback = function(ev)
1486---     if ev.data.method == 'textDocument/didOpen' then
1487---       vim.lsp.foldclose('imports', vim.fn.bufwinid(ev.buf))
1488---     end
1489---   end,
1490--- })
1491--- ```
1492---
1493---@since 13
1494---
1495---@param kind lsp.FoldingRangeKind Kind to close, one of "comment", "imports" or "region".
1496---@param winid? integer Defaults to the current window.
1497function lsp.foldclose(kind, winid)
1498  return vim.lsp._folding_range.foldclose(kind, winid)
1499end
1500
1501--- Provides a `foldtext` function that shows the `collapsedText` retrieved,
1502--- defaults to the first folded line if `collapsedText` is not provided.
1503---
1504--- The displayed foldtext will be highlighted via treesitter.
1505---@param lnum? integer line number (default: current fold start)
1506function lsp.foldtext(lnum)
1507  return vim.lsp._folding_range.foldtext(lnum)
1508end
1509
1510---@deprecated Use |vim.lsp.get_client_by_id()| instead.
1511---Checks whether a client is stopped.
1512---
1513---@param client_id integer
1514---@return boolean stopped true if client is stopped, false otherwise.
1515function lsp.client_is_stopped(client_id)
1516  vim.deprecate('vim.lsp.client_is_stopped()', 'vim.lsp.get_client_by_id()', '0.14')
1517  validate('client_id', client_id, 'number')
1518  return not lsp.get_client_by_id(client_id)
1519end
1520
1521--- Log level dictionary with reverse lookup as well.
1522---
1523--- Can be used to lookup the number from the name or the
1524--- name from the number.
1525--- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF"
1526--- Level numbers begin with "TRACE" at 0
1527--- @nodoc
1528lsp.log_levels = log.levels
1529
1530--- Sets the global log level for LSP logging.
1531---
1532--- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF"
1533---
1534--- Level numbers begin with "TRACE" at 0
1535---
1536--- Use `lsp.log_levels` for reverse lookup.
1537---
1538---@deprecated
1539---@see |vim.lsp.log_levels|
1540---
1541---@param level (integer|string) the case insensitive level name or number
1542function lsp.set_log_level(level)
1543  vim.deprecate('vim.lsp.set_log_level()', 'vim.lsp.log.set_level()', '0.13')
1544
1545  if type(level) == 'string' or type(level) == 'number' then
1546    log.set_level(level)
1547  else
1548    error(string.format('Invalid log level: %q', level))
1549  end
1550end
1551
1552--- Gets the path of the logfile used by the LSP client.
1553---
1554---@deprecated
1555---@return string path to log file
1556function lsp.get_log_path()
1557  vim.deprecate('vim.lsp.get_log_path()', 'vim.lsp.log.get_filename()', '0.13')
1558
1559  return log.get_filename()
1560end
1561
1562--- Map of client-defined handlers implementing custom (off-spec) commands which a server may
1563--- invoke. Each key is a unique command name; each value is a function which is called when an LSP
1564--- action (code action, code lenses, …) requests it by name.
1565---
1566--- If an LSP response requests a command not defined client-side, Nvim will forward it to the
1567--- server as `workspace/executeCommand`.
1568---
1569--- - Argument 1 is the `Command`:
1570---   ```
1571---   Command
1572---     title: String
1573---     command: String
1574---     arguments?: any[]
1575---   ```
1576--- - Argument 2 is the |lsp-handler| `ctx`.
1577---
1578--- Example:
1579---
1580--- ```lua
1581--- vim.lsp.commands['java.action.generateToStringPrompt'] = function(_, ctx)
1582---   require("jdtls.async").run(function()
1583---     local _, result = request(ctx.bufnr, 'java/checkToStringStatus', ctx.params)
1584---     local fields = ui.pick_many(result.fields, 'Include item in toString?', function(x)
1585---       return string.format('%s: %s', x.name, x.type)
1586---     end)
1587---     local _, edit = request(ctx.bufnr, 'java/generateToString', { context = ctx.params; fields = fields; })
1588---     vim.lsp.util.apply_workspace_edit(edit, offset_encoding)
1589---   end)
1590--- end
1591--- ```
1592---
1593--- @type table<string,fun(command: lsp.Command, ctx: table)>
1594lsp.commands = setmetatable({}, {
1595  __newindex = function(tbl, key, value)
1596    assert(type(key) == 'string', 'The key for commands in `vim.lsp.commands` must be a string')
1597    assert(type(value) == 'function', 'Command added to `vim.lsp.commands` must be a function')
1598    rawset(tbl, key, value)
1599  end,
1600})
1601
1602return lsp