robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
53.8 KiB1592 linesraw
1local uv = vim.uv
2local api = vim.api
3local lsp = vim.lsp
4local log = lsp.log
5local changetracking = lsp._changetracking
6local validate = vim.validate
7
8--- Tracks all clients initialized.
9---@type table<integer,vim.lsp.Client>
10local all_clients = {}
11
12---@param provider string
13---@param capability string[]?
14local function is_nested_server_capability_provider(provider, capability)
15  return capability ~= nil and #capability > 1 and provider == table.concat(capability, '.')
16end
17
18--- @alias vim.lsp.client.on_init_cb fun(client: vim.lsp.Client, init_result: lsp.InitializeResult)
19--- @alias vim.lsp.client.on_attach_cb fun(client: vim.lsp.Client, bufnr: integer)
20--- @alias vim.lsp.client.on_exit_cb fun(code: integer, signal: integer, client_id: integer)
21--- @alias vim.lsp.client.before_init_cb fun(params: lsp.InitializeParams, config: vim.lsp.ClientConfig)
22
23--- @class vim.lsp.Client.Flags
24--- @inlinedoc
25---
26--- Allow using incremental sync for buffer edits
27--- (default: `true`)
28--- @field allow_incremental_sync? boolean
29---
30--- Debounce `didChange` notifications to the server by the given number in milliseconds.
31--- (default: `150`)
32--- @field debounce_text_changes? integer
33
34--- @class vim.lsp.ClientConfig
35---
36--- Callback which can modify parameters before they are sent to the server. Invoked before LSP
37--- "initialize" phase (after `cmd` is invoked), where `params` is the parameters being sent to the
38--- server and `config` is the config passed to |vim.lsp.start()|.
39---
40--- Hint: use |vim.tbl_deep_extend()| to set nested fields easily.
41--- ```lua
42--- before_init = function(_, config)
43---   config.settings = vim.tbl_deep_extend('force',
44---     config.settings,
45---     { tailwindCSS = { experimental = { configFile = find_tailwind_global_css() } } }
46---   )
47--- end
48--- ```
49--- @field before_init? fun(params: lsp.InitializeParams, config: vim.lsp.ClientConfig)
50---
51--- Map overriding the default capabilities defined by |vim.lsp.protocol.make_client_capabilities()|,
52--- passed to the language server on initialization. Hint: use make_client_capabilities() and modify
53--- its result.
54--- - Note: To send an empty dictionary use |vim.empty_dict()|, else it will be encoded as an
55---   array.
56--- @field capabilities? lsp.ClientCapabilities
57---
58--- Command `string[]` that launches the language server (treated as in |jobstart()|, must be
59--- absolute or on `$PATH`, shell constructs like "~" are not expanded), or function that creates an
60--- RPC client (or an in-process |lsp-server|). Function receives a `dispatchers` table and the
61--- resolved `config`, and must return an object in the form of |vim.lsp.rpc.Client|.
62---
63--- Example (list):
64--- ```lua
65--- cmd = { 'flow', 'lsp' }
66--- ```
67--- Example (function):
68--- ```lua
69--- cmd = function(dispatchers, config)
70---   local cmd = vim.fn.executable('flow') == 1 and { 'flow', 'lsp' } or { 'npx', '--no-install', 'flow', 'lsp' }
71---   return vim.lsp.rpc.start(cmd, dispatchers)
72--- end
73--- ```
74---
75--- - See |vim.lsp.rpc.Client|.
76--- - For TCP there is a builtin RPC client factory: |vim.lsp.rpc.connect()|
77--- @field cmd string[]|fun(dispatchers: vim.lsp.rpc.Dispatchers, config: vim.lsp.ClientConfig): vim.lsp.rpc.Client
78---
79--- Directory where the `cmd` process is launched when `cmd` is a string array. Defaults to
80--- `root_dir` when available, then the current working directory.
81--- @field cmd_cwd? string
82---
83--- Environment variables passed to the LSP process on spawn. Non-string values are coerced to
84--- string.
85--- Example:
86--- ```lua
87--- { PORT = 8080, HOST = '0.0.0.0' }
88--- ```
89--- @field cmd_env? table
90---
91--- Map of client-defined commands overriding the global |vim.lsp.commands|.
92--- @field commands? table<string,fun(command: lsp.Command, ctx: table)>
93---
94--- Daemonize the server process so that it runs in a separate process group from Nvim.
95--- Nvim will shutdown the process on exit, but if Nvim fails to exit cleanly this could leave
96--- behind orphaned server processes.
97--- (default: `true`)
98--- @field detached? boolean
99---
100--- Decides if/when to force-stop the server after sending the "shutdown" request. See |Client:stop()|.
101--- Note: when Nvim itself is exiting,
102--- - `false`: Nvim will not force-stop LSP server(s).
103--- - `true`: Nvim will force-stop LSP server(s) that did not comply with the "shutdown" request.
104--- - `number`: Nvim will wait up to `exit_timeout` milliseconds before performing force-stop.
105--- (default: `false`)
106--- @field exit_timeout? integer|boolean
107---
108--- Experimental client flags:
109--- @field flags? vim.lsp.Client.Flags
110---
111--- Language ID as string. Defaults to the buffer filetype.
112--- @field get_language_id? fun(bufnr: integer, filetype: string): string
113---
114--- Map of LSP method names to |lsp-handler|s.
115--- @field handlers? table<string,function>
116---
117--- Values to pass in the initialization request as `initializationOptions`. See `initialize` in
118--- the LSP spec.
119--- @field init_options? lsp.LSPObject
120---
121--- Name in logs and user messages.
122--- (default: client-id)
123--- @field name? string
124---
125--- Called "position encoding" in LSP spec. The encoding that the LSP server expects, used for
126--- communication. Not validated. Can be modified in `on_init` before text is sent to the server.
127--- @field offset_encoding? 'utf-8'|'utf-16'|'utf-32'
128---
129--- Callback invoked when client attaches to a buffer.
130--- @field on_attach? elem_or_list<fun(client: vim.lsp.Client, bufnr: integer)>
131---
132--- Callback invoked when the client operation throws an error. `code` is a number describing the error.
133--- Other arguments may be passed depending on the error kind.  See `vim.lsp.rpc.client_errors`
134--- for possible errors. Use `vim.lsp.rpc.client_errors[code]` to get human-friendly name.
135--- @field on_error? fun(code: integer, err: string)
136---
137--- Callback invoked on client exit.
138---   - code: exit code of the process
139---   - signal: number describing the signal used to terminate (if any)
140---   - client_id: client handle
141--- @field on_exit? elem_or_list<fun(code: integer, signal: integer, client_id: integer)>
142---
143--- Callback invoked after LSP "initialize", where `result` is a table of `capabilities` and
144--- anything else the server may send. For example, clangd sends `init_result.offsetEncoding` if
145--- `capabilities.offsetEncoding` was sent to it. You can only modify the `client.offset_encoding`
146--- here before any notifications are sent.
147--- @field on_init? elem_or_list<fun(client: vim.lsp.Client, init_result: lsp.InitializeResult)>
148---
149--- Directory where the LSP server will base its workspaceFolders, rootUri, and rootPath on initialization.
150--- @field root_dir? string
151---
152--- Map of language server-specific settings, decided by the client. Sent to the LS if requested via
153--- `workspace/configuration`. Keys are case-sensitive.
154--- @field settings? lsp.LSPObject
155---
156--- Passed directly to the language server in the initialize request. Invalid/empty values will
157--- (default: "off")
158--- @field trace? 'off'|'messages'|'verbose'
159---
160--- List of workspace folders passed to the language server. For backwards compatibility rootUri and
161--- rootPath are derived from the first workspace folder in this list. Can be `null` if the client
162--- supports workspace folders but none are configured. See `workspaceFolders` in LSP spec.
163--- @field workspace_folders? lsp.WorkspaceFolder[]
164---
165--- Server requires a workspace (no "single file" support). Note: Without
166--- a workspace, cross-file features (navigation, hover) may or may not work depending on the
167--- language server, even if the server doesn't require a workspace.
168--- (default: `false`)
169--- @field workspace_required? boolean
170
171--- @class vim.lsp.Client.Progress: vim.Ringbuf<{token: integer|string, value: any}>
172--- @field pending table<lsp.ProgressToken,lsp.LSPAny>
173
174--- @class vim.lsp.Client
175---
176--- Each buffer's last used `languageId`.
177--- @field attached_buffers table<integer,string>
178---
179--- Capabilities provided by the client (editor or tool), at startup.
180--- @field capabilities lsp.ClientCapabilities
181---
182--- Client commands. See [vim.lsp.ClientConfig].
183--- @field commands table<string,fun(command: lsp.Command, ctx: table)>
184---
185--- Copy of the config passed to |vim.lsp.start()|.
186--- @field config vim.lsp.ClientConfig
187---
188--- Capabilities provided at runtime (after startup).
189--- @field dynamic_capabilities lsp.DynamicCapabilities
190---
191--- See [vim.lsp.ClientConfig].
192--- (default: `false`)
193--- @field exit_timeout integer|boolean
194---
195--- Experimental client flags:
196--- @field flags vim.lsp.Client.Flags
197---
198--- See [vim.lsp.ClientConfig].
199--- @field get_language_id fun(bufnr: integer, filetype: string): string
200---
201--- See [vim.lsp.ClientConfig].
202--- @field handlers table<string,lsp.Handler>
203---
204--- The id allocated to the client.
205--- @field id integer
206---
207--- @field initialized true?
208---
209--- See [vim.lsp.ClientConfig].
210--- @field name string
211---
212--- See [vim.lsp.ClientConfig].
213--- @field offset_encoding 'utf-8'|'utf-16'|'utf-32'
214---
215--- A ring buffer (|vim.ringbuf()|) containing progress messages
216--- sent by the server.
217--- @field progress vim.lsp.Client.Progress
218---
219--- The current pending requests in flight to the server. Entries are key-value
220--- pairs with the key being the request id while the value is a table with
221--- `type`, `bufnr`, and `method` key-value pairs. `type` is either "pending"
222--- for an active request, or "cancel" for a cancel request. It will be
223--- "complete" ephemerally while executing |LspRequest| autocmds when replies
224--- are received from the server.
225--- @field requests table<integer,{ type: string, bufnr: integer, method: vim.lsp.protocol.Method}?>
226---
227--- See [vim.lsp.ClientConfig].
228--- @field root_dir string?
229---
230--- RPC client object, for low level interaction with the client.
231--- See |vim.lsp.rpc.start()|.
232--- @field rpc vim.lsp.rpc.Client
233---
234--- Response from the server sent on `initialize` describing the server's capabilities.
235--- @field server_capabilities lsp.ServerCapabilities
236---
237--- Response from the server sent on `initialize` describing server information (e.g. version).
238--- @field server_info lsp.ServerInfo?
239---
240--- See [vim.lsp.ClientConfig].
241--- @field settings lsp.LSPObject
242---
243--- See [vim.lsp.ClientConfig].
244--- @field workspace_folders lsp.WorkspaceFolder[]?
245---
246--- @field _enabled_capabilities table<vim.lsp.capability.Name, boolean?>
247---
248--- Whether on-type formatting is enabled for this client.
249--- @field _otf_enabled boolean?
250---
251--- Timer for stop() with timeout.
252--- @field private _shutdown_timer uv.uv_timer_t?
253---
254--- Track this so that we can escalate automatically if we've already tried a
255--- graceful shutdown
256--- @field private _graceful_shutdown_failed true?
257---
258--- The initial trace setting. If omitted trace is disabled ("off").
259--- trace = "off" | "messages" | "verbose";
260--- @field private _trace 'off'|'messages'|'verbose'
261---
262--- @field private registrations table<string,lsp.Registration[]>
263--- @field private _log_prefix string
264---
265--- Caches compiled documentSelector globs and logs each invalid pattern only once per client.
266--- @field private _glob_cache table<string,vim.lpeg.Pattern|false>
267---
268--- @field private _before_init_cb? vim.lsp.client.before_init_cb
269--- @field private _on_attach_cbs vim.lsp.client.on_attach_cb[]
270--- @field private _on_init_cbs vim.lsp.client.on_init_cb[]
271--- @field private _on_exit_cbs vim.lsp.client.on_exit_cb[]
272--- @field private _on_error_cb? fun(code: integer, err: string)
273local Client = {}
274Client.__index = Client
275
276--- @param obj table<string,any>
277--- @param cls table
278--- @param name string
279local function method_wrapper(obj, cls, name)
280  local meth = assert(cls[name]) --[[@as function]]
281  obj[name] = function(...)
282    local arg = select(1, ...)
283    if arg and getmetatable(arg) == cls then
284      -- First argument is self, call meth directly
285      return meth(...)
286    end
287    vim.deprecate('client.' .. name, 'client:' .. name, '0.13')
288    -- First argument is not self, insert it
289    return meth(obj, ...)
290  end
291end
292
293local client_index = 0
294
295--- Checks whether a given path is a directory.
296--- @param filename (string) path to check
297--- @return boolean # true if {filename} exists and is a directory, false otherwise
298local function is_dir(filename)
299  validate('filename', filename, 'string')
300  local stat = uv.fs_stat(filename)
301  return stat and stat.type == 'directory' or false
302end
303
304local valid_encodings = {
305  ['utf-8'] = 'utf-8',
306  ['utf-16'] = 'utf-16',
307  ['utf-32'] = 'utf-32',
308  ['utf8'] = 'utf-8',
309  ['utf16'] = 'utf-16',
310  ['utf32'] = 'utf-32',
311}
312
313--- Normalizes {encoding} to valid LSP encoding names.
314--- @param encoding string? Encoding to normalize
315--- @return string # normalized encoding name
316local function validate_encoding(encoding)
317  validate('encoding', encoding, 'string', true)
318  if not encoding then
319    return valid_encodings.utf16
320  end
321  return valid_encodings[encoding:lower()]
322    or error(
323      string.format(
324        "Invalid position encoding %q. Must be one of: 'utf-8', 'utf-16', 'utf-32'",
325        encoding
326      )
327    )
328end
329
330--- Augments a validator function with support for optional (nil) values.
331--- @param fn (fun(v): boolean) The original validator function; should return a
332--- bool.
333--- @return fun(v): boolean # The augmented function. Also returns true if {v} is
334--- `nil`.
335local function optional_validator(fn)
336  return function(v)
337    return v == nil or fn(v)
338  end
339end
340
341--- By default, get_language_id just returns the exact filetype it is passed.
342--- It is possible to pass in something that will calculate a different filetype,
343--- to be sent by the client.
344--- @param _bufnr integer
345--- @param filetype string
346local function default_get_language_id(_bufnr, filetype)
347  return filetype
348end
349
350--- Validates a client configuration as given to |vim.lsp.start()|.
351--- @param config vim.lsp.ClientConfig
352local function validate_config(config)
353  validate('config', config, 'table')
354  validate('handlers', config.handlers, 'table', true)
355  validate('capabilities', config.capabilities, 'table', true)
356  validate('cmd_cwd', config.cmd_cwd, optional_validator(is_dir), 'directory')
357  validate('cmd_env', config.cmd_env, 'table', true)
358  validate('detached', config.detached, 'boolean', true)
359  validate('exit_timeout', config.exit_timeout, { 'number', 'boolean' }, true)
360  validate('name', config.name, 'string', true)
361  validate('on_error', config.on_error, 'function', true)
362  validate('on_exit', config.on_exit, { 'function', 'table' }, true)
363  validate('on_init', config.on_init, { 'function', 'table' }, true)
364  validate('on_attach', config.on_attach, { 'function', 'table' }, true)
365  validate('settings', config.settings, 'table', true)
366  validate('commands', config.commands, 'table', true)
367  validate('before_init', config.before_init, { 'function', 'table' }, true)
368  validate('offset_encoding', config.offset_encoding, 'string', true)
369  validate('flags', config.flags, 'table', true)
370  validate('get_language_id', config.get_language_id, 'function', true)
371
372  assert(
373    (
374      not config.flags
375      or not config.flags.debounce_text_changes
376      or type(config.flags.debounce_text_changes) == 'number'
377    ),
378    'flags.debounce_text_changes must be a number with the debounce time in milliseconds'
379  )
380end
381
382--- @param trace string?
383--- @return 'off'|'messages'|'verbose'
384local function get_trace(trace)
385  local valid_traces = {
386    off = 'off',
387    messages = 'messages',
388    verbose = 'verbose',
389  }
390  return trace and valid_traces[trace] or 'off'
391end
392
393--- @param id integer
394--- @param config vim.lsp.ClientConfig
395--- @return string
396local function get_name(id, config)
397  local name = config.name
398  if name then
399    return name
400  end
401
402  if type(config.cmd) == 'table' and config.cmd[1] then
403    return vim.fs.basename(config.cmd[1])
404  end
405
406  return tostring(id)
407end
408
409--- @nodoc
410--- @param config vim.lsp.ClientConfig
411--- @return vim.lsp.Client?
412function Client.create(config)
413  validate_config(config)
414
415  client_index = client_index + 1
416  local id = client_index
417  local name = get_name(id, config)
418
419  --- @type vim.lsp.Client
420  local self = setmetatable({
421    id = id,
422    config = config,
423    handlers = config.handlers or {},
424    offset_encoding = validate_encoding(config.offset_encoding),
425    name = name,
426    _log_prefix = string.format('LSP[%s]', name),
427    _glob_cache = {},
428    requests = {},
429    attached_buffers = {},
430    server_capabilities = {},
431    registrations = {},
432    commands = config.commands or {},
433    settings = config.settings or {},
434    flags = config.flags or {},
435    exit_timeout = config.exit_timeout or false,
436    get_language_id = config.get_language_id or default_get_language_id,
437    capabilities = config.capabilities,
438    workspace_folders = lsp._get_workspace_folders(config.workspace_folders or config.root_dir),
439    root_dir = config.root_dir,
440    _is_stopping = false,
441    _before_init_cb = config.before_init,
442    _on_init_cbs = vim._ensure_list(config.on_init),
443    _on_exit_cbs = vim._ensure_list(config.on_exit),
444    _on_attach_cbs = vim._ensure_list(config.on_attach),
445    _on_error_cb = config.on_error,
446    _trace = get_trace(config.trace),
447
448    --- Contains $/progress report messages.
449    --- They have the format {token: integer|string, value: any}
450    --- For "work done progress", value will be one of:
451    --- - lsp.WorkDoneProgressBegin,
452    --- - lsp.WorkDoneProgressReport (extended with title from Begin)
453    --- - lsp.WorkDoneProgressEnd    (extended with title from Begin)
454    progress = vim.ringbuf(50) --[[@as vim.lsp.Client.Progress]],
455
456    --- @deprecated use client.progress instead
457    messages = { name = name, messages = {}, progress = {}, status = {} },
458  }, Client)
459
460  self.capabilities =
461    vim.tbl_deep_extend('force', lsp.protocol.make_client_capabilities(), self.capabilities or {})
462
463  --- @class lsp.DynamicCapabilities
464  --- @nodoc
465  self.dynamic_capabilities = {
466    capabilities = self.registrations,
467    client_id = id,
468    register = function(_, registrations)
469      return self:_register_dynamic(registrations)
470    end,
471    unregister = function(_, unregistrations)
472      return self:_unregister_dynamic(unregistrations)
473    end,
474    get = function(_, method, opts)
475      return self:_get_registrations(method, opts and opts.bufnr)
476    end,
477    supports_registration = function(_, method)
478      return self:_supports_registration(method)
479    end,
480    supports = function(_, method, opts)
481      return self:_get_registrations(method, opts and opts.bufnr) ~= nil
482    end,
483  }
484
485  ---@type table <vim.lsp.capability.Name, boolean?>
486  self._enabled_capabilities = {}
487
488  --- @type table<string|integer, string> title of unfinished progress sequences by token
489  self.progress.pending = {}
490
491  --- @type vim.lsp.rpc.Dispatchers
492  local dispatchers = {
493    notification = function(...)
494      self:_notification(...)
495    end,
496    server_request = function(...)
497      return self:_server_request(...)
498    end,
499    on_error = function(...)
500      self:_on_error(...)
501    end,
502    on_exit = function(...)
503      self:_on_exit(...)
504    end,
505  }
506
507  -- Start the RPC client.
508  local config_cmd = config.cmd
509  if type(config_cmd) == 'function' then
510    self.rpc = config_cmd(dispatchers, config)
511  else
512    self.rpc = lsp.rpc.start(config_cmd, dispatchers, {
513      cwd = config.cmd_cwd or config.root_dir,
514      env = config.cmd_env,
515      detached = config.detached,
516    })
517  end
518
519  method_wrapper(self, Client, 'request')
520  method_wrapper(self, Client, 'request_sync')
521  method_wrapper(self, Client, 'notify')
522  method_wrapper(self, Client, 'cancel_request')
523  method_wrapper(self, Client, 'stop')
524  method_wrapper(self, Client, 'is_stopped')
525  method_wrapper(self, Client, 'on_attach')
526  method_wrapper(self, Client, 'supports_method')
527
528  return self
529end
530
531--- @private
532--- @param cbs function[]
533--- @param error_id integer
534--- @param ... any
535function Client:_run_callbacks(cbs, error_id, ...)
536  for _, cb in pairs(cbs) do
537    --- @type boolean, string?
538    local status, err = pcall(cb, ...)
539    if not status then
540      self:write_error(error_id, err)
541    end
542  end
543end
544
545--- @nodoc
546function Client:initialize()
547  -- Register all initialized clients.
548  all_clients[self.id] = self
549
550  local config = self.config
551
552  local root_uri --- @type string?
553  local root_path --- @type string?
554  local workspace_folder = self.workspace_folders and self.workspace_folders[1]
555  if workspace_folder then
556    root_uri = workspace_folder.uri
557    root_path = vim.uri_to_fname(root_uri)
558  end
559
560  -- HACK: Capability modules must be loaded
561  require('vim.lsp._folding_range')
562  require('vim.lsp.diagnostic')
563  require('vim.lsp.document_color')
564  require('vim.lsp.inlay_hint')
565  require('vim.lsp.inline_completion')
566  require('vim.lsp.linked_editing_range')
567  require('vim.lsp.semantic_tokens')
568
569  local init_params = {
570    -- The process Id of the parent process that started the server. Is null if
571    -- the process has not been started by another process.  If the parent
572    -- process is not alive then the server should exit (see exit notification)
573    -- its process.
574    processId = uv.os_getpid(),
575    -- Information about the client
576    -- since 3.15.0
577    clientInfo = {
578      name = 'Neovim',
579      version = tostring(vim.version()),
580    },
581    -- The rootPath of the workspace. Is null if no folder is open.
582    --
583    -- @deprecated in favour of rootUri.
584    rootPath = root_path or vim.NIL,
585    -- The rootUri of the workspace. Is null if no folder is open. If both
586    -- `rootPath` and `rootUri` are set `rootUri` wins.
587    rootUri = root_uri or vim.NIL,
588    workspaceFolders = self.workspace_folders or vim.NIL,
589    -- User provided initialization options.
590    initializationOptions = config.init_options,
591    capabilities = self.capabilities,
592    trace = self._trace,
593    workDoneToken = '1',
594  }
595
596  self:_run_callbacks(
597    { self._before_init_cb },
598    lsp.client_errors.BEFORE_INIT_CALLBACK_ERROR,
599    init_params,
600    config
601  )
602
603  log.trace(self._log_prefix, 'init_params', init_params)
604
605  local rpc = self.rpc
606
607  rpc.request('initialize', init_params, function(init_err, result)
608    if init_err then
609      error(lsp.rpc.format_rpc_error(init_err))
610    end
611    assert(result, 'server sent empty result')
612    rpc.notify('initialized', vim.empty_dict())
613    self.initialized = true
614
615    -- These are the cleaned up capabilities we use for dynamically deciding
616    -- when to send certain events to clients.
617    self.server_capabilities =
618      assert(result.capabilities, "initialize result doesn't contain capabilities")
619    self.server_capabilities = assert(lsp.protocol.resolve_capabilities(self.server_capabilities))
620
621    self:_process_static_registrations()
622
623    if self.server_capabilities.positionEncoding then
624      self.offset_encoding = self.server_capabilities.positionEncoding
625    end
626
627    self.server_info = result.serverInfo
628
629    if next(self.settings) then
630      self:notify('workspace/didChangeConfiguration', { settings = self.settings })
631    end
632
633    -- If server is being restarted, make sure to re-attach to any previously attached buffers.
634    -- Save which buffers before on_init in case new buffers are attached.
635    local reattach_bufs = vim.deepcopy(self.attached_buffers)
636
637    self:_run_callbacks(self._on_init_cbs, lsp.client_errors.ON_INIT_CALLBACK_ERROR, self, result)
638
639    for buf in pairs(reattach_bufs) do
640      -- The buffer may have been detached in the on_init callback.
641      if self.attached_buffers[buf] then
642        self:on_attach(buf)
643      end
644    end
645
646    log.info(
647      self._log_prefix,
648      'server_capabilities',
649      { server_capabilities = self.server_capabilities }
650    )
651  end)
652end
653
654--- @private
655function Client:_process_static_registrations()
656  local static_registrations = {} ---@type lsp.Registration[]
657
658  for method in pairs(lsp.protocol._method_supports_static_registration) do
659    local capability = lsp.protocol._request_name_to_server_capability[method]
660    local provider = self:_registration_provider(method)
661    local cap = is_nested_server_capability_provider(provider, capability)
662        and vim.tbl_get(self.server_capabilities, unpack(capability))
663      or vim.tbl_get(self.server_capabilities, capability[1])
664    if type(cap) == 'table' and cap.id then
665      static_registrations[#static_registrations + 1] = {
666        id = cap.id,
667        method = method,
668        registerOptions = cap or {},
669      }
670    end
671  end
672
673  if next(static_registrations) then
674    self:_register_dynamic(static_registrations)
675  end
676end
677
678--- @private
679--- Returns the handler associated with an LSP method.
680--- Returns the default handler if the user hasn't set a custom one.
681---
682--- @param method string LSP method name
683--- @return lsp.Handler? handler for the given method, if defined, or the default from |vim.lsp.handlers|
684function Client:_resolve_handler(method)
685  return self.handlers[method] or lsp.handlers[method]
686end
687
688--- @private
689--- @param id integer
690--- @param req_type 'pending'|'complete'|'cancel'
691--- @param bufnr? integer (only required for req_type='pending')
692--- @param method? vim.lsp.protocol.Method (only required for req_type='pending')
693function Client:_process_request(id, req_type, bufnr, method)
694  local pending = req_type == 'pending'
695
696  validate('id', id, 'number')
697  if pending then
698    validate('bufnr', bufnr, 'number')
699    validate('method', method, 'string')
700  end
701
702  local cur_request = self.requests[id]
703
704  if pending and cur_request then
705    log.error(
706      self._log_prefix,
707      ('Cannot create request with id %d as one already exists'):format(id)
708    )
709    return
710  elseif not pending and not cur_request then
711    log.error(
712      self._log_prefix,
713      ('Cannot find request with id %d whilst attempting to %s'):format(id, req_type)
714    )
715    return
716  end
717
718  if cur_request then
719    bufnr = cur_request.bufnr
720    method = cur_request.method
721  end
722
723  assert(bufnr and method)
724
725  local request = { type = req_type, bufnr = bufnr, method = method }
726
727  -- Clear 'complete' requests
728  -- Note 'pending' and 'cancelled' requests are cleared when the server sends a response
729  -- which is processed via the notify_reply_callback argument to rpc.request.
730  self.requests[id] = req_type ~= 'complete' and request or nil
731
732  api.nvim_exec_autocmds('LspRequest', {
733    buf = api.nvim_buf_is_valid(bufnr) and bufnr or nil,
734    modeline = false,
735    data = { client_id = self.id, request_id = id, request = request },
736  })
737end
738
739--- Sends a request to the server.
740---
741--- This is a thin wrapper around {client.rpc.request} with some additional
742--- checks for capabilities and handler availability.
743---
744--- @param method vim.lsp.protocol.Method.ClientToServer.Request LSP method name.
745--- @param params? table LSP request params.
746--- @param handler? lsp.Handler Response |lsp-handler| for this method.
747--- @param bufnr? integer (default: 0) Buffer handle, or 0 for current.
748--- @return boolean status indicates whether the request was successful.
749---     If it is `false`, then it will always be `false` (the client has shutdown).
750--- @return integer? request_id Can be used with |Client:cancel_request()|.
751---                             `nil` is request failed.
752--- to cancel the-request.
753--- @see |vim.lsp.buf_request_all()|
754function Client:request(method, params, handler, bufnr)
755  if not handler then
756    handler = self:_resolve_handler(method)
757      or error(('not found: %q request handler for client %q.'):format(method, self.name))
758  end
759  -- Ensure pending didChange notifications are sent so that the server doesn't operate on a stale state
760  changetracking.flush(self, bufnr)
761  bufnr = vim._resolve_bufnr(bufnr)
762  local version = lsp.util.buf_versions[bufnr]
763  log.debug(self._log_prefix, 'client.request', self.id, method, params, handler, bufnr)
764
765  -- Detect if request resolved synchronously (only possible with in-process servers).
766  local already_responded = false
767  local request_registered = false
768
769  -- NOTE: rpc.request might call an in-process (Lua) server, thus may be synchronous.
770  local success, request_id = self.rpc.request(method, params, function(err, result, id)
771    handler(err, result, {
772      method = method,
773      client_id = self.id,
774      request_id = id,
775      bufnr = bufnr,
776      params = params,
777      version = version,
778    })
779  end, function(id)
780    -- Called when the server sends a response to the request (including cancelled acknowledgment).
781    if request_registered then
782      self:_process_request(id, 'complete')
783    end
784    already_responded = true
785  end)
786
787  if success and request_id and not already_responded then
788    self:_process_request(request_id, 'pending', bufnr, method)
789    request_registered = true
790  end
791
792  return success, request_id
793end
794
795-- TODO(lewis6991): duplicated from lsp.lua
796local wait_result_reason = { [-1] = 'timeout', [-2] = 'interrupted', [-3] = 'error' }
797
798--- Concatenates and writes a list of strings to the Vim error buffer.
799---
800--- @param ... string|number List to write to the buffer
801local function err_message(...)
802  local chunks = { { table.concat(vim.iter({ ... }):flatten():totable()) } }
803  if vim.in_fast_event() then
804    vim.schedule(function()
805      api.nvim_echo(chunks, true, { err = true })
806      api.nvim_command('redraw')
807    end)
808  else
809    api.nvim_echo(chunks, true, { err = true })
810    api.nvim_command('redraw')
811  end
812end
813
814--- Sends a request to the server and synchronously waits for the response.
815---
816--- This is a wrapper around |Client:request()|
817---
818--- @param method vim.lsp.protocol.Method.ClientToServer.Request LSP method name.
819--- @param params table LSP request params.
820--- @param timeout_ms integer? Maximum time in milliseconds to wait for
821---                                a result. Defaults to 1000
822--- @param bufnr? integer (default: 0) Buffer handle, or 0 for current.
823--- @return {err: lsp.ResponseError?, result:any}? `result` and `err` from the |lsp-handler|.
824---                 `nil` is the request was unsuccessful
825--- @return string? err On timeout, cancel or error, where `err` is a
826---                 string describing the failure reason.
827--- @see |vim.lsp.buf_request_sync()|
828function Client:request_sync(method, params, timeout_ms, bufnr)
829  local request_result = nil
830  --- @param err lsp.ResponseError?
831  --- @param result any
832  local function _sync_handler(err, result)
833    request_result = { err = err, result = result }
834  end
835
836  local success, request_id = self:request(method, params, _sync_handler, bufnr)
837  if not success then
838    return nil
839  end
840
841  local wait_result, reason = vim.wait(timeout_ms or 1000, function()
842    return request_result ~= nil
843  end, 10)
844
845  if not wait_result then
846    if request_id then
847      self:cancel_request(request_id)
848    end
849    return nil, wait_result_reason[reason]
850  end
851  return request_result
852end
853
854--- Sends a notification to an LSP server.
855---
856--- @param method vim.lsp.protocol.Method.ClientToServer.Notification LSP method name.
857--- @param params table? LSP request params.
858--- @param bufnr integer? Buffer associated with notification.
859--- @return boolean status indicating if the notification was successful.
860---                        If it is false, then the client has shutdown.
861function Client:notify(method, params, bufnr)
862  if method ~= 'textDocument/didChange' then
863    changetracking.flush(self)
864  end
865
866  local client_active = self.rpc.notify(method, params)
867
868  if client_active then
869    vim.schedule(function()
870      if not self:is_stopped() and (not bufnr or self.attached_buffers[bufnr]) then
871        api.nvim_exec_autocmds('LspNotify', {
872          buf = bufnr,
873          modeline = false,
874          data = {
875            client_id = self.id,
876            method = method,
877            params = params,
878          },
879        })
880      end
881    end)
882  end
883
884  return client_active
885end
886
887--- Cancels a request with a given request id.
888---
889--- @param id integer id of request to cancel
890--- @return boolean status indicating if the notification was successful.
891--- @see |Client:notify()|
892function Client:cancel_request(id)
893  self:_process_request(id, 'cancel')
894  return self.rpc.notify('$/cancelRequest', { id = id })
895end
896
897--- Stops a client, optionally with force after a timeout.
898---
899--- By default this sends a "shutdown" request to the server, escalating to force-stop if the server
900--- has not exited after `self.exit_timeout` milliseconds (unless `exit_timeout=false`).
901--- Calling stop() on a client that was previously requested to shutdown, will escalate to
902--- force-stop immediately, regardless of `force` (or `self.exit_timeout` if `force=nil`).
903---
904--- Note: Forcing shutdown while a server is busy writing out project or index files can lead to
905--- file corruption.
906---
907--- @param force? integer|boolean (default: `self.exit_timeout`) Decides whether to force-stop the server.
908--- - `false`: Do not force-stop after "shutdown" request.
909--- - `nil`: Defaults to `exit_timeout` from |vim.lsp.ClientConfig|.
910--- - `true`: Force-stop after "shutdown" request.
911--- - number: Wait up to `force` milliseconds before force-stop.
912function Client:stop(force)
913  validate('force', force, { 'number', 'boolean' }, true)
914
915  if force == nil then
916    force = self.exit_timeout
917  end
918
919  local rpc = self.rpc
920  if rpc.is_closing() then
921    return
922  end
923
924  self._is_stopping = true
925
926  lsp._watchfiles.cancel(self.id)
927
928  if force == true or not self.initialized or self._graceful_shutdown_failed then
929    rpc.terminate()
930    return
931  end
932
933  if type(force) == 'number' then
934    self._shutdown_timer = vim.defer_fn(function()
935      self._shutdown_timer = nil
936      self:stop(true)
937    end, force)
938  end
939
940  -- Sending a signal after a process has exited is acceptable.
941  rpc.request('shutdown', nil, function(err, _, _)
942    if err == nil then
943      rpc.notify('exit')
944    else
945      -- If there was an error in the shutdown request, then terminate to be safe.
946      rpc.terminate()
947      self._graceful_shutdown_failed = true
948    end
949  end)
950end
951
952--- Stops a client, then starts a new client with the same config and attached
953--- buffers.
954---
955--- @param force? integer|boolean See [Client:stop()] for details.
956---                               (default: `self.exit_timeout`)
957function Client:_restart(force)
958  validate('force', force, { 'number', 'boolean' }, true)
959
960  self._handle_restart = function()
961    --- @type integer[]
962    local attached_buffers = vim.tbl_keys(self.attached_buffers)
963
964    vim.schedule(function()
965      local new_client_id = lsp.start(self.config, { attach = false })
966      if new_client_id then
967        for _, buffer in ipairs(attached_buffers) do
968          lsp.buf_attach_client(buffer, new_client_id)
969        end
970      end
971    end)
972  end
973
974  self:stop(force)
975end
976
977--- Get options for a method that is registered dynamically.
978--- @param method vim.lsp.protocol.Method | vim.lsp.protocol.Method.Registration
979function Client:_supports_registration(method)
980  if lsp.protocol._methods_with_no_registration_options[method] then
981    return true
982  end
983  local provider = self:_registration_provider(method)
984  local capability_path = lsp.protocol._provider_to_client_registration[provider]
985  if not capability_path then
986    -- If we don't know about the method, assume the client supports dynamic registration for it.
987    return true
988  end
989  local capability = vim.tbl_get(self.capabilities, unpack(capability_path))
990  return type(capability) == 'table' and capability.dynamicRegistration == true
991end
992
993--- Get provider for a method to be registered dynamically.
994--- @param method vim.lsp.protocol.Method | vim.lsp.protocol.Method.Registration
995function Client._registration_provider(_, method)
996  return lsp.protocol._request_name_to_registration_provider[method] or method
997end
998
999--- @private
1000--- @param registrations lsp.Registration[]
1001function Client:_register_dynamic(registrations)
1002  -- remove duplicates
1003  self:_unregister_dynamic(registrations)
1004  for _, reg in ipairs(registrations) do
1005    local provider = self:_registration_provider(reg.method)
1006    if not self.registrations[provider] then
1007      self.registrations[provider] = {}
1008    end
1009    table.insert(self.registrations[provider], reg)
1010  end
1011end
1012
1013--- @param registrations lsp.Registration[]
1014function Client:_register(registrations)
1015  self:_register_dynamic(registrations)
1016
1017  local unsupported = {} --- @type string[]
1018
1019  for _, reg in ipairs(registrations) do
1020    local method = reg.method
1021    if method == 'workspace/didChangeWatchedFiles' then
1022      lsp._watchfiles.register(reg, self.id)
1023    elseif not self:_supports_registration(method) then
1024      unsupported[#unsupported + 1] = method
1025    end
1026  end
1027
1028  if #unsupported > 0 then
1029    local warning_tpl = 'The language server %s triggers a registerCapability '
1030      .. 'handler for %s despite dynamicRegistration set to false. '
1031      .. 'Report upstream, this warning is harmless'
1032    log.warn(string.format(warning_tpl, self.name, table.concat(unsupported, ', ')))
1033  end
1034end
1035
1036--- @private
1037--- @param unregistrations lsp.Unregistration[]|lsp.Registration[]
1038function Client:_unregister_dynamic(unregistrations)
1039  for _, unreg in ipairs(unregistrations) do
1040    local provider = self:_registration_provider(unreg.method)
1041    local sreg = self.registrations[provider]
1042    -- Unegister dynamic capability
1043    for i, reg in ipairs(sreg or {}) do
1044      if reg.id == unreg.id then
1045        table.remove(sreg, i)
1046        break
1047      end
1048    end
1049  end
1050end
1051
1052--- @param unregistrations lsp.Unregistration[]
1053function Client:_unregister(unregistrations)
1054  self:_unregister_dynamic(unregistrations)
1055  for _, unreg in ipairs(unregistrations) do
1056    if unreg.method == 'workspace/didChangeWatchedFiles' then
1057      lsp._watchfiles.unregister(unreg.id, self.id)
1058    end
1059  end
1060end
1061
1062--- @private
1063--- @param bufnr integer
1064function Client:_get_language_id(bufnr)
1065  return self.get_language_id(bufnr, vim.bo[bufnr].filetype)
1066end
1067
1068--- @private
1069--- @param pattern string
1070--- @param fname string
1071--- @return boolean
1072function Client:_glob_matches(pattern, fname)
1073  local pat = self._glob_cache[pattern]
1074  if pat == nil then
1075    local ok, res = pcall(vim.glob.to_lpeg, pattern)
1076    pat = ok and res or false
1077    self._glob_cache[pattern] = pat
1078    if not ok then
1079      log.error(self._log_prefix, 'skipping invalid documentSelector pattern', pattern, res)
1080    end
1081  end
1082  return pat ~= false and pat:match(fname) ~= nil
1083end
1084
1085--- @param provider string
1086--- @param bufnr? integer
1087--- @return lsp.Registration[]?
1088function Client:_get_registrations(provider, bufnr)
1089  bufnr = vim._resolve_bufnr(bufnr)
1090  local matched_regs = {} --- @type lsp.Registration[]
1091  for _, reg in ipairs(self.registrations[provider] or {}) do
1092    local regoptions = reg.registerOptions --[[@as {documentSelector:lsp.DocumentSelector|lsp.null}]]
1093    if
1094      not regoptions
1095      or regoptions == vim.NIL
1096      or not regoptions.documentSelector
1097      or regoptions.documentSelector == vim.NIL
1098    then
1099      matched_regs[#matched_regs + 1] = reg
1100    else
1101      local language = self:_get_language_id(bufnr)
1102      local uri = vim.uri_from_bufnr(bufnr)
1103      local fname = vim.uri_to_fname(uri)
1104      for _, filter in ipairs(regoptions.documentSelector) do
1105        local flang, fscheme, fpat = filter.language, filter.scheme, filter.pattern
1106        if
1107          not (flang and language ~= flang)
1108          and not (fscheme and not vim.startswith(uri, fscheme .. ':'))
1109          and not (type(fpat) == 'string' and not self:_glob_matches(fpat, fname))
1110        then
1111          matched_regs[#matched_regs + 1] = reg
1112        end
1113      end
1114    end
1115  end
1116  return #matched_regs > 0 and matched_regs or nil
1117end
1118
1119--- Checks whether a client is stopped.
1120---
1121--- @return boolean # true if client is stopped or in the process of being
1122--- stopped; false otherwise
1123function Client:is_stopped()
1124  return self.rpc.is_closing() or self._is_stopping
1125end
1126
1127--- Execute a lsp command, either via client command function (if available)
1128--- or via workspace/executeCommand (if supported by the server)
1129---
1130--- @param cmd lsp.Command
1131--- @param context? {bufnr?: integer}
1132--- @param handler? lsp.Handler only called if a server command
1133function Client:exec_cmd(cmd, context, handler)
1134  context = vim.deepcopy(context or {}, true) --[[@as lsp.HandlerContext]]
1135  context.bufnr = vim._resolve_bufnr(context.bufnr)
1136  context.client_id = self.id
1137  local cmdname = cmd.command
1138  local fn = self.commands[cmdname] or lsp.commands[cmdname]
1139  if fn then
1140    fn(cmd, context)
1141    return
1142  end
1143
1144  local command_provider = self.server_capabilities.executeCommandProvider
1145  local commands = type(command_provider) == 'table' and command_provider.commands or {}
1146
1147  if not vim.list_contains(commands, cmdname) then
1148    vim.notify_once(
1149      string.format(
1150        'Language server `%s` does not support command `%s`. This command may require a client extension.',
1151        self.name,
1152        cmdname
1153      ),
1154      vim.log.levels.WARN
1155    )
1156    return
1157  end
1158  -- Not using cmd directly to exclude extra properties,
1159  -- see https://github.com/python-lsp/python-lsp-server/issues/146
1160  --- @type lsp.ExecuteCommandParams
1161  local params = {
1162    command = cmdname,
1163    arguments = cmd.arguments,
1164  }
1165  self:request('workspace/executeCommand', params, handler, context.bufnr)
1166end
1167
1168--- Default handler for the 'textDocument/didClose' LSP notification.
1169---
1170--- @param bufnr integer Number of the buffer, or 0 for current
1171function Client:_text_document_did_close_handler(bufnr)
1172  if not self:supports_method('textDocument/didClose') then
1173    return
1174  end
1175  local uri = vim.uri_from_bufnr(bufnr)
1176  local params = { textDocument = { uri = uri } }
1177  self:notify('textDocument/didClose', params, bufnr)
1178end
1179
1180--- Default handler for the 'textDocument/didOpen' LSP notification.
1181---
1182--- @param bufnr integer Number of the buffer, or 0 for current
1183function Client:_text_document_did_open_handler(bufnr)
1184  changetracking.init(self, bufnr)
1185  if not self:supports_method('textDocument/didOpen') then
1186    return
1187  end
1188  if not api.nvim_buf_is_loaded(bufnr) then
1189    return
1190  end
1191
1192  self:notify('textDocument/didOpen', {
1193    textDocument = {
1194      version = lsp.util.buf_versions[bufnr],
1195      uri = vim.uri_from_bufnr(bufnr),
1196      languageId = self:_get_language_id(bufnr),
1197      text = lsp._buf_get_full_text(bufnr),
1198    },
1199  }, bufnr)
1200
1201  -- Next chance we get, we should re-do the diagnostics
1202  vim.schedule(function()
1203    -- Protect against a race where the buffer disappears
1204    -- between `did_open_handler` and the scheduled function firing.
1205    if api.nvim_buf_is_valid(bufnr) then
1206      local namespace = lsp.diagnostic.get_namespace(self.id)
1207      vim.diagnostic.show(namespace, bufnr)
1208    end
1209  end)
1210end
1211
1212--- Runs the on_attach function from the client's config if it was defined.
1213--- Useful for buffer-local setup.
1214--- @param bufnr integer Buffer number
1215function Client:on_attach(bufnr)
1216  lsp._set_defaults(self, bufnr)
1217
1218  self:_text_document_did_open_handler(bufnr)
1219
1220  api.nvim_exec_autocmds('LspAttach', {
1221    buf = bufnr,
1222    modeline = false,
1223    data = { client_id = self.id },
1224  })
1225
1226  self:_run_callbacks(self._on_attach_cbs, lsp.client_errors.ON_ATTACH_ERROR, self, bufnr)
1227
1228  -- schedule the initialization of capabilities to give the above on_attach and LspAttach callbacks
1229  -- the ability to enable or disable them
1230  vim.schedule(function()
1231    if not api.nvim_buf_is_valid(bufnr) then
1232      return
1233    end
1234    for _, Capability in pairs(lsp._capability.all) do
1235      if
1236        self:supports_method(Capability.method)
1237        and lsp._capability.is_enabled(Capability.name, {
1238          bufnr = bufnr,
1239          client_id = self.id,
1240        })
1241      then
1242        local capability = Capability.active[bufnr] or Capability:new(bufnr)
1243        capability:on_attach(self.id)
1244      end
1245    end
1246  end)
1247
1248  self.attached_buffers[bufnr] = self:_get_language_id(bufnr)
1249end
1250
1251--- @private
1252--- Logs the given error to the LSP log and to the error buffer.
1253--- @param code integer Error code
1254--- @param err any Error arguments
1255function Client:write_error(code, err)
1256  local client_error = lsp.client_errors[code] --- @type string|integer
1257  log.error(self._log_prefix, 'on_error', { code = client_error, err = err })
1258  err_message(self._log_prefix, ': Error ', client_error, ': ', vim.inspect(err))
1259end
1260
1261--- Checks if a client supports a given method.
1262--- Always returns true for unknown off-spec methods.
1263---
1264--- Note: Some language server capabilities can be file specific.
1265--- @param method vim.lsp.protocol.Method.ClientToServer | vim.lsp.protocol.Method.Registration
1266--- @param bufnr? integer
1267--- @return boolean
1268function Client:supports_method(method, bufnr)
1269  -- Deprecated form
1270  if type(bufnr) == 'table' then
1271    --- @diagnostic disable-next-line:no-unknown
1272    bufnr = bufnr.bufnr
1273  end
1274  local required_capability = lsp.protocol._request_name_to_server_capability[method]
1275  local has_subcap = required_capability and #required_capability > 1
1276  local is_self_mapping = required_capability
1277    and #required_capability == 1
1278    and required_capability[1] == method
1279
1280  if
1281    not is_self_mapping
1282    and required_capability
1283    and vim.tbl_get(self.server_capabilities, unpack(required_capability))
1284  then
1285    return true
1286  end
1287
1288  local provider = self:_registration_provider(method)
1289  local has_subprovider = is_nested_server_capability_provider(provider, required_capability)
1290  local regs = self:_get_registrations(provider, bufnr)
1291  if lsp.protocol._method_supports_dynamic_registration[method] and not regs then
1292    return false
1293  end
1294  if regs then
1295    for _, reg in ipairs(regs or {}) do
1296      if has_subprovider then
1297        if
1298          vim.tbl_get(reg, 'registerOptions')
1299          or lsp.protocol._methods_with_no_registration_options[method]
1300        then
1301          return self:_supports_registration(reg.method)
1302        end
1303      elseif has_subcap then
1304        if vim.tbl_get(reg, 'registerOptions', unpack(required_capability, 2)) then
1305          return self:_supports_registration(reg.method)
1306        end
1307        if lsp.protocol._methods_with_no_registration_options[method] then
1308          return true
1309        end
1310      else
1311        return self:_supports_registration(reg.method)
1312      end
1313    end
1314    return false
1315  end
1316
1317  if required_capability == nil and next(self.registrations[method] or {}) ~= nil then
1318    return false
1319  end
1320
1321  -- If we don't know about the method, or if it is a self-mapping(method=required_capability)
1322  -- assume that the client supports it.
1323  -- This needs to be at the end, so that dynamic_capabilities are checked first.
1324  return required_capability == nil or is_self_mapping
1325end
1326
1327--- Executes callback fn for all registrations for a given LSP method.
1328---
1329--- This handles both static capabilities (declared in server_capabilities during
1330--- initialization) and dynamic registrations (registered at runtime via
1331--- `client/registerCapability`).
1332---
1333--- Some methods may have multiple registrations (e.g., different documentSelectors
1334--- or configurations). The callback is invoked once for each registration.
1335---
1336--- Example: Getting diagnostic identifiers from all registrations
1337---     client:_provider_foreach('textDocument/diagnostic', function(cap)
1338---       print(cap.identifier)  -- "static-id", "dynamic-id-1", "dynamic-id-2"
1339---     end)
1340---
1341--- Note: Some capabilities alias to different providers. For example,
1342--- `workspace/diagnostic` uses the same `diagnosticProvider` as `textDocument/diagnostic`.
1343---
1344---@param method vim.lsp.protocol.Method.ClientToServer | vim.lsp.protocol.Method.Registration LSP method name
1345---@param fn fun(capability_value: lsp.LSPAny) Callback invoked for each matching capability
1346function Client:_provider_foreach(method, fn)
1347  local provider = self:_registration_provider(method)
1348  local required_capability = lsp.protocol._request_name_to_server_capability[method]
1349  local dynamic_regs = self:_get_registrations(provider)
1350  local has_subcap = required_capability and #required_capability > 1
1351  local has_subprovider = is_nested_server_capability_provider(provider, required_capability)
1352  if not dynamic_regs then
1353    -- First check static capabilities
1354    local static_reg = has_subprovider
1355        and vim.tbl_get(self.server_capabilities, unpack(required_capability))
1356      or vim.tbl_get(self.server_capabilities, provider)
1357    if static_reg then
1358      if
1359        has_subprovider
1360        or not has_subcap
1361        or vim.tbl_get(static_reg, unpack(required_capability, 2))
1362      then
1363        fn(static_reg)
1364      end
1365    end
1366  else
1367    for _, reg in ipairs(dynamic_regs) do
1368      local regoptions = vim.tbl_get(reg, 'registerOptions')
1369      if
1370        (
1371          has_subprovider
1372          and (regoptions or lsp.protocol._methods_with_no_registration_options[method])
1373        )
1374        or not has_subcap
1375        or vim.tbl_get(regoptions, unpack(required_capability, 2))
1376      then
1377        fn(regoptions or {})
1378      end
1379    end
1380  end
1381end
1382
1383--- @private
1384--- Handles a notification sent by an LSP server by invoking the
1385--- corresponding handler.
1386---
1387--- @param method string LSP method name
1388--- @param params table The parameters for that method.
1389function Client:_notification(method, params)
1390  log.trace('notification', method, params)
1391  local handler = self:_resolve_handler(method)
1392  if handler then
1393    -- Method name is provided here for convenience.
1394    handler(nil, params, { method = method, client_id = self.id })
1395  end
1396end
1397
1398--- @private
1399--- Handles a request from an LSP server by invoking the corresponding handler.
1400---
1401--- @param method string LSP method name
1402--- @param params (table) The parameters for that method
1403--- @return any result
1404--- @return lsp.ResponseError? error code and message set in case an exception happens during the request.
1405function Client:_server_request(method, params)
1406  log.trace('server_request', method, params)
1407  local handler = self:_resolve_handler(method)
1408  if handler then
1409    log.trace('server_request: found handler for', method)
1410    return handler(nil, params, { method = method, client_id = self.id })
1411  end
1412  log.warn('server_request: no handler found for', method)
1413  return nil, lsp.rpc_response_error(lsp.protocol.ErrorCodes.MethodNotFound)
1414end
1415
1416--- @private
1417--- Invoked when the client operation throws an error.
1418---
1419--- @param code integer Error code
1420--- @param err any Other arguments may be passed depending on the error kind
1421--- @see vim.lsp.rpc.client_errors for possible errors. Use
1422--- `vim.lsp.rpc.client_errors[code]` to get a human-friendly name.
1423function Client:_on_error(code, err)
1424  self:write_error(code, err)
1425  if self._on_error_cb then
1426    local status, usererr = pcall(self._on_error_cb, code, err)
1427    if not status then
1428      log.error(self._log_prefix, 'user on_error failed', { err = usererr })
1429      err_message(self._log_prefix, ' user on_error failed: ', tostring(usererr))
1430    end
1431  end
1432end
1433
1434---@param bufnr integer resolved buffer
1435function Client:_on_detach(bufnr)
1436  if self.attached_buffers[bufnr] and api.nvim_buf_is_valid(bufnr) then
1437    api.nvim_exec_autocmds('LspDetach', {
1438      buf = bufnr,
1439      modeline = false,
1440      data = { client_id = self.id },
1441    })
1442  end
1443
1444  for _, Capability in pairs(lsp._capability.all) do
1445    if
1446      self:supports_method(Capability.method)
1447      and lsp._capability.is_enabled(Capability.name, {
1448        bufnr = bufnr,
1449        client_id = self.id,
1450      })
1451    then
1452      local capability = Capability.active[bufnr]
1453      if capability then
1454        capability:on_detach(self.id)
1455        if next(capability.client_state) == nil then
1456          capability:destroy()
1457        end
1458      end
1459    end
1460  end
1461
1462  vim.diagnostic.reset(lsp.diagnostic.get_namespace(self.id, false), bufnr)
1463
1464  changetracking.reset_buf(self, bufnr)
1465
1466  self:_text_document_did_close_handler(bufnr)
1467
1468  self.attached_buffers[bufnr] = nil
1469end
1470
1471--- Reset defaults set by `set_defaults`.
1472--- Must only be called if the last client attached to a buffer exits.
1473--- @param bufnr integer
1474local function reset_defaults(bufnr)
1475  if vim.bo[bufnr].tagfunc == lsp.tagfunc then
1476    vim.bo[bufnr].tagfunc = nil
1477  end
1478  if vim.bo[bufnr].omnifunc == lsp.omnifunc then
1479    vim.bo[bufnr].omnifunc = nil
1480  end
1481  if vim.bo[bufnr].formatexpr == 'v:lua.vim.lsp.formatexpr()' then
1482    vim.bo[bufnr].formatexpr = nil
1483  end
1484  vim._with({ buf = bufnr }, function()
1485    local keymap = vim.fn.maparg('K', 'n', false, true)
1486    if keymap and keymap.callback == lsp.buf.hover and keymap.buffer == 1 then
1487      vim.keymap.del('n', 'K', { buf = bufnr })
1488    end
1489  end)
1490end
1491
1492--- @private
1493--- Invoked on client exit.
1494---
1495--- @param code integer) exit code of the process
1496--- @param signal integer the signal used to terminate (if any)
1497function Client:_on_exit(code, signal)
1498  if self._shutdown_timer and not self._shutdown_timer:is_closing() then
1499    self._shutdown_timer:close()
1500    self._shutdown_timer = nil
1501  end
1502
1503  vim.schedule(function()
1504    for bufnr in pairs(self.attached_buffers) do
1505      self:_on_detach(bufnr)
1506      if #lsp.get_clients({ bufnr = bufnr, _uninitialized = true }) == 0 then
1507        reset_defaults(bufnr)
1508      end
1509    end
1510
1511    -- Schedule the deletion of the client object
1512    -- so that it exists in the execution of autocommands
1513    vim.schedule(function()
1514      all_clients[self.id] = nil
1515
1516      -- Client can be absent if executable starts, but initialize fails
1517      -- init/attach won't have happened
1518      if self then
1519        changetracking.reset(self)
1520      end
1521      if code ~= 0 or (signal ~= 0 and signal ~= 15) then
1522        local msg = string.format(
1523          'Client %s quit with exit code %s and signal %s. Check log for errors: %s',
1524          self and self.name or 'unknown',
1525          code,
1526          signal,
1527          log.get_filename()
1528        )
1529        vim.notify(msg, vim.log.levels.WARN)
1530      end
1531    end)
1532  end)
1533
1534  if self._handle_restart ~= nil then
1535    self._handle_restart()
1536    self._handle_restart = nil
1537  end
1538
1539  self:_run_callbacks(
1540    self._on_exit_cbs,
1541    lsp.client_errors.ON_EXIT_CALLBACK_ERROR,
1542    code,
1543    signal,
1544    self.id
1545  )
1546end
1547
1548--- Add a directory to the workspace folders.
1549--- @param dir string?
1550function Client:_add_workspace_folder(dir)
1551  for _, folder in pairs(self.workspace_folders or {}) do
1552    if folder.name == dir then
1553      print(dir, 'is already part of this workspace')
1554      return
1555    end
1556  end
1557
1558  local wf = assert(lsp._get_workspace_folders(dir))
1559
1560  self:notify('workspace/didChangeWorkspaceFolders', {
1561    event = { added = wf, removed = {} },
1562  })
1563
1564  if not self.workspace_folders then
1565    self.workspace_folders = {}
1566  end
1567  vim.list_extend(self.workspace_folders, wf)
1568end
1569
1570--- Remove a directory to the workspace folders.
1571--- @param dir string?
1572function Client:_remove_workspace_folder(dir)
1573  local wf = assert(lsp._get_workspace_folders(dir))
1574
1575  self:notify('workspace/didChangeWorkspaceFolders', {
1576    event = { added = {}, removed = wf },
1577  })
1578
1579  if self.workspace_folders then
1580    for idx, folder in pairs(self.workspace_folders) do
1581      if folder.name == dir then
1582        table.remove(self.workspace_folders, idx)
1583        break
1584      end
1585    end
1586  end
1587end
1588
1589-- Export for internal use only.
1590Client._all = all_clients
1591
1592return Client