robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 ) 15return 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 ) 280local meth =assert ( cls [ name ]) --[[@as function]] 281obj [ name ] =function ( ... ) 282local arg =select ( 1 , ... ) 283if arg and getmetatable ( arg ) == cls then 284-- First argument is self, call meth directly 285return meth ( ... ) 286end 287vim . deprecate ( 'client.' .. name , 'client:' .. name , '0.13' ) 288-- First argument is not self, insert it 289return meth ( obj , ... ) 290end 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 ) 299validate ( 'filename' , filename , 'string' ) 300local stat =uv . fs_stat ( filename ) 301return 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 ) 317validate ( 'encoding' , encoding , 'string' , true ) 318if not encoding then 319return valid_encodings . utf16 320end 321return valid_encodings [ encoding : lower ()] 322or error ( 323string . format ( 324"Invalid position encoding %q. Must be one of: 'utf-8', 'utf-16', 'utf-32'" , 325encoding 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 ) 336return function ( v ) 337return v == nil or fn ( v ) 338end 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 ) 347return 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 ) 353validate ( 'config' , config , 'table' ) 354validate ( 'handlers' , config . handlers , 'table' , true ) 355validate ( 'capabilities' , config . capabilities , 'table' , true ) 356validate ( 'cmd_cwd' , config . cmd_cwd , optional_validator ( is_dir ), 'directory' ) 357validate ( 'cmd_env' , config . cmd_env , 'table' , true ) 358validate ( 'detached' , config . detached , 'boolean' , true ) 359validate ( 'exit_timeout' , config . exit_timeout , { 'number' , 'boolean' } , true ) 360validate ( 'name' , config . name , 'string' , true ) 361validate ( 'on_error' , config . on_error , 'function' , true ) 362validate ( 'on_exit' , config . on_exit , { 'function' , 'table' } , true ) 363validate ( 'on_init' , config . on_init , { 'function' , 'table' } , true ) 364validate ( 'on_attach' , config . on_attach , { 'function' , 'table' } , true ) 365validate ( 'settings' , config . settings , 'table' , true ) 366validate ( 'commands' , config . commands , 'table' , true ) 367validate ( 'before_init' , config . before_init , { 'function' , 'table' } , true ) 368validate ( 'offset_encoding' , config . offset_encoding , 'string' , true ) 369validate ( 'flags' , config . flags , 'table' , true ) 370validate ( 'get_language_id' , config . get_language_id , 'function' , true ) 371 372assert ( 373( 374not config . flags 375or not config . flags . debounce_text_changes 376or 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 ) 385local valid_traces ={ 386off ='off' , 387messages ='messages' , 388verbose ='verbose' , 389} 390return 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 ) 397local name =config . name 398if name then 399return name 400end 401 402if type ( config . cmd ) == 'table' and config . cmd [ 1 ] then 403return vim . fs . basename ( config . cmd [ 1 ]) 404end 405 406return tostring ( id ) 407end 408 409--- @nodoc 410--- @param config vim.lsp.ClientConfig 411--- @return vim.lsp.Client? 412function Client . create ( config ) 413validate_config ( config ) 414 415client_index =client_index + 1 416local id =client_index 417local name =get_name ( id , config ) 418 419--- @type vim.lsp.Client 420local self =setmetatable ( { 421id =id , 422config =config , 423handlers =config . handlers or {} , 424offset_encoding =validate_encoding ( config . offset_encoding ), 425name =name , 426_log_prefix =string . format ( 'LSP[%s]' , name ), 427_glob_cache ={} , 428requests ={} , 429attached_buffers ={} , 430server_capabilities ={} , 431registrations ={} , 432commands =config . commands or {} , 433settings =config . settings or {} , 434flags =config . flags or {} , 435exit_timeout =config . exit_timeout or false , 436get_language_id =config . get_language_id or default_get_language_id , 437capabilities =config . capabilities , 438workspace_folders =lsp . _get_workspace_folders ( config . workspace_folders or config . root_dir ), 439root_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) 454progress =vim . ringbuf ( 50 ) --[[@as vim.lsp.Client.Progress]] , 455 456--- @deprecated use client.progress instead 457messages ={ name =name , messages ={} , progress ={} , status ={} } , 458} , Client ) 459 460self . capabilities = 461vim . tbl_deep_extend ( 'force' , lsp . protocol . make_client_capabilities (), self . capabilities or {} ) 462 463--- @class lsp.DynamicCapabilities 464--- @nodoc 465self . dynamic_capabilities ={ 466capabilities =self . registrations , 467client_id =id , 468register =function ( _ , registrations ) 469return self : _register_dynamic ( registrations ) 470end , 471unregister =function ( _ , unregistrations ) 472return self : _unregister_dynamic ( unregistrations ) 473end , 474get =function ( _ , method , opts ) 475return self : _get_registrations ( method , opts and opts . bufnr ) 476end , 477supports_registration =function ( _ , method ) 478return self : _supports_registration ( method ) 479end , 480supports =function ( _ , method , opts ) 481return self : _get_registrations ( method , opts and opts . bufnr ) ~= nil 482end , 483} 484 485---@type table <vim.lsp.capability.Name, boolean?> 486self . _enabled_capabilities ={} 487 488--- @type table<string|integer, string> title of unfinished progress sequences by token 489self . progress . pending ={} 490 491--- @type vim.lsp.rpc.Dispatchers 492local dispatchers ={ 493notification =function ( ... ) 494self : _notification ( ... ) 495end , 496server_request =function ( ... ) 497return self : _server_request ( ... ) 498end , 499on_error =function ( ... ) 500self : _on_error ( ... ) 501end , 502on_exit =function ( ... ) 503self : _on_exit ( ... ) 504end , 505} 506 507-- Start the RPC client. 508local config_cmd =config . cmd 509if type ( config_cmd ) == 'function' then 510self . rpc =config_cmd ( dispatchers , config ) 511else 512self . rpc =lsp . rpc . start ( config_cmd , dispatchers , { 513cwd =config . cmd_cwd or config . root_dir , 514env =config . cmd_env , 515detached =config . detached , 516} ) 517end 518 519method_wrapper ( self , Client , 'request' ) 520method_wrapper ( self , Client , 'request_sync' ) 521method_wrapper ( self , Client , 'notify' ) 522method_wrapper ( self , Client , 'cancel_request' ) 523method_wrapper ( self , Client , 'stop' ) 524method_wrapper ( self , Client , 'is_stopped' ) 525method_wrapper ( self , Client , 'on_attach' ) 526method_wrapper ( self , Client , 'supports_method' ) 527 528return self 529end 530 531--- @private 532--- @param cbs function[] 533--- @param error_id integer 534--- @param ... any 535function Client : _run_callbacks ( cbs , error_id , ... ) 536for _ , cb in pairs ( cbs ) do 537--- @type boolean, string? 538local status , err =pcall ( cb , ... ) 539if not status then 540self : write_error ( error_id , err ) 541end 542end 543end 544 545--- @nodoc 546function Client : initialize () 547-- Register all initialized clients. 548all_clients [ self . id ] =self 549 550local config =self . config 551 552local root_uri --- @type string? 553local root_path --- @type string? 554local workspace_folder =self . workspace_folders and self . workspace_folders [ 1 ] 555if workspace_folder then 556root_uri =workspace_folder . uri 557root_path =vim . uri_to_fname ( root_uri ) 558end 559 560-- HACK: Capability modules must be loaded 561require ( 'vim.lsp._folding_range' ) 562require ( 'vim.lsp.diagnostic' ) 563require ( 'vim.lsp.document_color' ) 564require ( 'vim.lsp.inlay_hint' ) 565require ( 'vim.lsp.inline_completion' ) 566require ( 'vim.lsp.linked_editing_range' ) 567require ( 'vim.lsp.semantic_tokens' ) 568 569local 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. 574processId =uv . os_getpid (), 575-- Information about the client 576-- since 3.15.0 577clientInfo ={ 578name ='Neovim' , 579version =tostring ( vim . version ()), 580} , 581-- The rootPath of the workspace. Is null if no folder is open. 582-- 583-- @deprecated in favour of rootUri. 584rootPath =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. 587rootUri =root_uri or vim . NIL , 588workspaceFolders =self . workspace_folders or vim . NIL , 589-- User provided initialization options. 590initializationOptions =config . init_options , 591capabilities =self . capabilities , 592trace =self . _trace , 593workDoneToken ='1' , 594} 595 596self : _run_callbacks ( 597{ self . _before_init_cb } , 598lsp . client_errors . BEFORE_INIT_CALLBACK_ERROR , 599init_params , 600config 601) 602 603log . trace ( self . _log_prefix , 'init_params' , init_params ) 604 605local rpc =self . rpc 606 607rpc . request ( 'initialize' , init_params , function ( init_err , result ) 608if init_err then 609error ( lsp . rpc . format_rpc_error ( init_err )) 610end 611assert ( result , 'server sent empty result' ) 612rpc . notify ( 'initialized' , vim . empty_dict ()) 613self . initialized =true 614 615-- These are the cleaned up capabilities we use for dynamically deciding 616-- when to send certain events to clients. 617self . server_capabilities = 618assert ( result . capabilities , "initialize result doesn't contain capabilities" ) 619self . server_capabilities =assert ( lsp . protocol . resolve_capabilities ( self . server_capabilities )) 620 621self : _process_static_registrations () 622 623if self . server_capabilities . positionEncoding then 624self . offset_encoding =self . server_capabilities . positionEncoding 625end 626 627self . server_info =result . serverInfo 628 629if next ( self . settings ) then 630self : notify ( 'workspace/didChangeConfiguration' , { settings =self . settings } ) 631end 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. 635local reattach_bufs =vim . deepcopy ( self . attached_buffers ) 636 637self : _run_callbacks ( self . _on_init_cbs , lsp . client_errors . ON_INIT_CALLBACK_ERROR , self , result ) 638 639for buf in pairs ( reattach_bufs ) do 640-- The buffer may have been detached in the on_init callback. 641if self . attached_buffers [ buf ] then 642self : on_attach ( buf ) 643end 644end 645 646log . info ( 647self . _log_prefix , 648'server_capabilities' , 649{ server_capabilities =self . server_capabilities } 650) 651end ) 652end 653 654--- @private 655function Client : _process_static_registrations () 656local static_registrations ={} ---@type lsp.Registration[] 657 658for method in pairs ( lsp . protocol . _method_supports_static_registration ) do 659local capability =lsp . protocol . _request_name_to_server_capability [ method ] 660local provider =self : _registration_provider ( method ) 661local cap =is_nested_server_capability_provider ( provider , capability ) 662and vim . tbl_get ( self . server_capabilities , unpack ( capability )) 663or vim . tbl_get ( self . server_capabilities , capability [ 1 ]) 664if type ( cap ) == 'table' and cap . id then 665static_registrations [ # static_registrations + 1 ] ={ 666id =cap . id , 667method =method , 668registerOptions =cap or {} , 669} 670end 671end 672 673if next ( static_registrations ) then 674self : _register_dynamic ( static_registrations ) 675end 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 ) 685return 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 ) 694local pending =req_type == 'pending' 695 696validate ( 'id' , id , 'number' ) 697if pending then 698validate ( 'bufnr' , bufnr , 'number' ) 699validate ( 'method' , method , 'string' ) 700end 701 702local cur_request =self . requests [ id ] 703 704if pending and cur_request then 705log . error ( 706self . _log_prefix , 707( 'Cannot create request with id %d as one already exists' ): format ( id ) 708) 709return 710elseif not pending and not cur_request then 711log . error ( 712self . _log_prefix , 713( 'Cannot find request with id %d whilst attempting to %s' ): format ( id , req_type ) 714) 715return 716end 717 718if cur_request then 719bufnr =cur_request . bufnr 720method =cur_request . method 721end 722 723assert ( bufnr and method ) 724 725local 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. 730self . requests [ id ] =req_type ~= 'complete' and request or nil 731 732api . nvim_exec_autocmds ( 'LspRequest' , { 733buf =api . nvim_buf_is_valid ( bufnr ) and bufnr or nil , 734modeline =false , 735data ={ 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 ) 755if not handler then 756handler =self : _resolve_handler ( method ) 757or error (( 'not found: %q request handler for client %q.' ): format ( method , self . name )) 758end 759-- Ensure pending didChange notifications are sent so that the server doesn't operate on a stale state 760changetracking . flush ( self , bufnr ) 761bufnr =vim . _resolve_bufnr ( bufnr ) 762local version =lsp . util . buf_versions [ bufnr ] 763log . 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). 766local already_responded =false 767local request_registered =false 768 769-- NOTE: rpc.request might call an in-process (Lua) server, thus may be synchronous. 770local success , request_id =self . rpc . request ( method , params , function ( err , result , id ) 771handler ( err , result , { 772method =method , 773client_id =self . id , 774request_id =id , 775bufnr =bufnr , 776params =params , 777version =version , 778} ) 779end , function ( id ) 780-- Called when the server sends a response to the request (including cancelled acknowledgment). 781if request_registered then 782self : _process_request ( id , 'complete' ) 783end 784already_responded =true 785end ) 786 787if success and request_id and not already_responded then 788self : _process_request ( request_id , 'pending' , bufnr , method ) 789request_registered =true 790end 791 792return 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 ( ... ) 802local chunks ={ { table . concat ( vim . iter ( { ... } ): flatten (): totable ()) } } 803if vim . in_fast_event () then 804vim . schedule ( function () 805api . nvim_echo ( chunks , true , { err =true } ) 806api . nvim_command ( 'redraw' ) 807end ) 808else 809api . nvim_echo ( chunks , true , { err =true } ) 810api . nvim_command ( 'redraw' ) 811end 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 ) 829local request_result =nil 830--- @param err lsp.ResponseError? 831--- @param result any 832local function _sync_handler ( err , result ) 833request_result ={ err =err , result =result } 834end 835 836local success , request_id =self : request ( method , params , _sync_handler , bufnr ) 837if not success then 838return nil 839end 840 841local wait_result , reason =vim . wait ( timeout_ms or 1000 , function () 842return request_result ~= nil 843end , 10 ) 844 845if not wait_result then 846if request_id then 847self : cancel_request ( request_id ) 848end 849return nil , wait_result_reason [ reason ] 850end 851return 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 ) 862if method ~= 'textDocument/didChange' then 863changetracking . flush ( self ) 864end 865 866local client_active =self . rpc . notify ( method , params ) 867 868if client_active then 869vim . schedule ( function () 870if not self : is_stopped () and ( not bufnr or self . attached_buffers [ bufnr ]) then 871api . nvim_exec_autocmds ( 'LspNotify' , { 872buf =bufnr , 873modeline =false , 874data ={ 875client_id =self . id , 876method =method , 877params =params , 878} , 879} ) 880end 881end ) 882end 883 884return 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 ) 893self : _process_request ( id , 'cancel' ) 894return 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 ) 913validate ( 'force' , force , { 'number' , 'boolean' } , true ) 914 915if force == nil then 916force =self . exit_timeout 917end 918 919local rpc =self . rpc 920if rpc . is_closing () then 921return 922end 923 924self . _is_stopping =true 925 926lsp . _watchfiles . cancel ( self . id ) 927 928if force == true or not self . initialized or self . _graceful_shutdown_failed then 929rpc . terminate () 930return 931end 932 933if type ( force ) == 'number' then 934self . _shutdown_timer =vim . defer_fn ( function () 935self . _shutdown_timer =nil 936self : stop ( true ) 937end , force ) 938end 939 940-- Sending a signal after a process has exited is acceptable. 941rpc . request ( 'shutdown' , nil , function ( err , _ , _ ) 942if err == nil then 943rpc . notify ( 'exit' ) 944else 945-- If there was an error in the shutdown request, then terminate to be safe. 946rpc . terminate () 947self . _graceful_shutdown_failed =true 948end 949end ) 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 ) 958validate ( 'force' , force , { 'number' , 'boolean' } , true ) 959 960self . _handle_restart =function () 961--- @type integer[] 962local attached_buffers =vim . tbl_keys ( self . attached_buffers ) 963 964vim . schedule ( function () 965local new_client_id =lsp . start ( self . config , { attach =false } ) 966if new_client_id then 967for _ , buffer in ipairs ( attached_buffers ) do 968lsp . buf_attach_client ( buffer , new_client_id ) 969end 970end 971end ) 972end 973 974self : 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 ) 980if lsp . protocol . _methods_with_no_registration_options [ method ] then 981return true 982end 983local provider =self : _registration_provider ( method ) 984local capability_path =lsp . protocol . _provider_to_client_registration [ provider ] 985if not capability_path then 986-- If we don't know about the method, assume the client supports dynamic registration for it. 987return true 988end 989local capability =vim . tbl_get ( self . capabilities , unpack ( capability_path )) 990return 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 ) 996return 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 1003self : _unregister_dynamic ( registrations ) 1004for _ , reg in ipairs ( registrations ) do 1005local provider =self : _registration_provider ( reg . method ) 1006if not self . registrations [ provider ] then 1007self . registrations [ provider ] ={} 1008end 1009table . insert ( self . registrations [ provider ], reg ) 1010end 1011end 1012 1013--- @param registrations lsp.Registration[] 1014function Client : _register ( registrations ) 1015self : _register_dynamic ( registrations ) 1016 1017local unsupported ={} --- @type string[] 1018 1019for _ , reg in ipairs ( registrations ) do 1020local method =reg . method 1021if method == 'workspace/didChangeWatchedFiles' then 1022lsp . _watchfiles . register ( reg , self . id ) 1023elseif not self : _supports_registration ( method ) then 1024unsupported [ # unsupported + 1 ] =method 1025end 1026end 1027 1028if # unsupported > 0 then 1029local 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' 1032log . warn ( string . format ( warning_tpl , self . name , table . concat ( unsupported , ', ' ))) 1033end 1034end 1035 1036--- @private 1037--- @param unregistrations lsp.Unregistration[]|lsp.Registration[] 1038function Client : _unregister_dynamic ( unregistrations ) 1039for _ , unreg in ipairs ( unregistrations ) do 1040local provider =self : _registration_provider ( unreg . method ) 1041local sreg =self . registrations [ provider ] 1042-- Unegister dynamic capability 1043for i , reg in ipairs ( sreg or {} ) do 1044if reg . id == unreg . id then 1045table . remove ( sreg , i ) 1046break 1047end 1048end 1049end 1050end 1051 1052--- @param unregistrations lsp.Unregistration[] 1053function Client : _unregister ( unregistrations ) 1054self : _unregister_dynamic ( unregistrations ) 1055for _ , unreg in ipairs ( unregistrations ) do 1056if unreg . method == 'workspace/didChangeWatchedFiles' then 1057lsp . _watchfiles . unregister ( unreg . id , self . id ) 1058end 1059end 1060end 1061 1062--- @private 1063--- @param bufnr integer 1064function Client : _get_language_id ( bufnr ) 1065return 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 ) 1073local pat =self . _glob_cache [ pattern ] 1074if pat == nil then 1075local ok , res =pcall ( vim . glob . to_lpeg , pattern ) 1076pat =ok and res or false 1077self . _glob_cache [ pattern ] =pat 1078if not ok then 1079log . error ( self . _log_prefix , 'skipping invalid documentSelector pattern' , pattern , res ) 1080end 1081end 1082return 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 ) 1089bufnr =vim . _resolve_bufnr ( bufnr ) 1090local matched_regs ={} --- @type lsp.Registration[] 1091for _ , reg in ipairs ( self . registrations [ provider ] or {} ) do 1092local regoptions =reg . registerOptions --[[@as {documentSelector:lsp.DocumentSelector|lsp.null}]] 1093if 1094not regoptions 1095or regoptions == vim . NIL 1096or not regoptions . documentSelector 1097or regoptions . documentSelector == vim . NIL 1098then 1099matched_regs [ # matched_regs + 1 ] =reg 1100else 1101local language =self : _get_language_id ( bufnr ) 1102local uri =vim . uri_from_bufnr ( bufnr ) 1103local fname =vim . uri_to_fname ( uri ) 1104for _ , filter in ipairs ( regoptions . documentSelector ) do 1105local flang , fscheme , fpat =filter . language , filter . scheme , filter . pattern 1106if 1107not ( flang and language ~= flang ) 1108and not ( fscheme and not vim . startswith ( uri , fscheme .. ':' )) 1109and not ( type ( fpat ) == 'string' and not self : _glob_matches ( fpat , fname )) 1110then 1111matched_regs [ # matched_regs + 1 ] =reg 1112end 1113end 1114end 1115end 1116return # 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 () 1124return 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 ) 1134context =vim . deepcopy ( context or {} , true ) --[[@as lsp.HandlerContext]] 1135context . bufnr =vim . _resolve_bufnr ( context . bufnr ) 1136context . client_id =self . id 1137local cmdname =cmd . command 1138local fn =self . commands [ cmdname ] or lsp . commands [ cmdname ] 1139if fn then 1140fn ( cmd , context ) 1141return 1142end 1143 1144local command_provider =self . server_capabilities . executeCommandProvider 1145local commands =type ( command_provider ) == 'table' and command_provider . commands or {} 1146 1147if not vim . list_contains ( commands , cmdname ) then 1148vim . notify_once ( 1149string . format ( 1150'Language server `%s` does not support command `%s`. This command may require a client extension.' , 1151self . name , 1152cmdname 1153), 1154vim . log . levels . WARN 1155) 1156return 1157end 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 1161local params ={ 1162command =cmdname , 1163arguments =cmd . arguments , 1164} 1165self : 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 ) 1172if not self : supports_method ( 'textDocument/didClose' ) then 1173return 1174end 1175local uri =vim . uri_from_bufnr ( bufnr ) 1176local params ={ textDocument ={ uri =uri } } 1177self : 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 ) 1184changetracking . init ( self , bufnr ) 1185if not self : supports_method ( 'textDocument/didOpen' ) then 1186return 1187end 1188if not api . nvim_buf_is_loaded ( bufnr ) then 1189return 1190end 1191 1192self : notify ( 'textDocument/didOpen' , { 1193textDocument ={ 1194version =lsp . util . buf_versions [ bufnr ], 1195uri =vim . uri_from_bufnr ( bufnr ), 1196languageId =self : _get_language_id ( bufnr ), 1197text =lsp . _buf_get_full_text ( bufnr ), 1198} , 1199} , bufnr ) 1200 1201-- Next chance we get, we should re-do the diagnostics 1202vim . schedule ( function () 1203-- Protect against a race where the buffer disappears 1204-- between `did_open_handler` and the scheduled function firing. 1205if api . nvim_buf_is_valid ( bufnr ) then 1206local namespace =lsp . diagnostic . get_namespace ( self . id ) 1207vim . diagnostic . show ( namespace , bufnr ) 1208end 1209end ) 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 ) 1216lsp . _set_defaults ( self , bufnr ) 1217 1218self : _text_document_did_open_handler ( bufnr ) 1219 1220api . nvim_exec_autocmds ( 'LspAttach' , { 1221buf =bufnr , 1222modeline =false , 1223data ={ client_id =self . id } , 1224} ) 1225 1226self : _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 1230vim . schedule ( function () 1231if not api . nvim_buf_is_valid ( bufnr ) then 1232return 1233end 1234for _ , Capability in pairs ( lsp . _capability . all ) do 1235if 1236self : supports_method ( Capability . method ) 1237and lsp . _capability . is_enabled ( Capability . name , { 1238bufnr =bufnr , 1239client_id =self . id , 1240} ) 1241then 1242local capability =Capability . active [ bufnr ] or Capability : new ( bufnr ) 1243capability : on_attach ( self . id ) 1244end 1245end 1246end ) 1247 1248self . 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 ) 1256local client_error =lsp . client_errors [ code ] --- @type string|integer 1257log . error ( self . _log_prefix , 'on_error' , { code =client_error , err =err } ) 1258err_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 1270if type ( bufnr ) == 'table' then 1271--- @diagnostic disable-next-line:no-unknown 1272bufnr =bufnr . bufnr 1273end 1274local required_capability =lsp . protocol . _request_name_to_server_capability [ method ] 1275local has_subcap =required_capability and # required_capability > 1 1276local is_self_mapping =required_capability 1277and # required_capability == 1 1278and required_capability [ 1 ] == method 1279 1280if 1281not is_self_mapping 1282and required_capability 1283and vim . tbl_get ( self . server_capabilities , unpack ( required_capability )) 1284then 1285return true 1286end 1287 1288local provider =self : _registration_provider ( method ) 1289local has_subprovider =is_nested_server_capability_provider ( provider , required_capability ) 1290local regs =self : _get_registrations ( provider , bufnr ) 1291if lsp . protocol . _method_supports_dynamic_registration [ method ] and not regs then 1292return false 1293end 1294if regs then 1295for _ , reg in ipairs ( regs or {} ) do 1296if has_subprovider then 1297if 1298vim . tbl_get ( reg , 'registerOptions' ) 1299or lsp . protocol . _methods_with_no_registration_options [ method ] 1300then 1301return self : _supports_registration ( reg . method ) 1302end 1303elseif has_subcap then 1304if vim . tbl_get ( reg , 'registerOptions' , unpack ( required_capability , 2 )) then 1305return self : _supports_registration ( reg . method ) 1306end 1307if lsp . protocol . _methods_with_no_registration_options [ method ] then 1308return true 1309end 1310else 1311return self : _supports_registration ( reg . method ) 1312end 1313end 1314return false 1315end 1316 1317if required_capability == nil and next ( self . registrations [ method ] or {} ) ~= nil then 1318return false 1319end 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. 1324return 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 ) 1347local provider =self : _registration_provider ( method ) 1348local required_capability =lsp . protocol . _request_name_to_server_capability [ method ] 1349local dynamic_regs =self : _get_registrations ( provider ) 1350local has_subcap =required_capability and # required_capability > 1 1351local has_subprovider =is_nested_server_capability_provider ( provider , required_capability ) 1352if not dynamic_regs then 1353-- First check static capabilities 1354local static_reg =has_subprovider 1355and vim . tbl_get ( self . server_capabilities , unpack ( required_capability )) 1356or vim . tbl_get ( self . server_capabilities , provider ) 1357if static_reg then 1358if 1359has_subprovider 1360or not has_subcap 1361or vim . tbl_get ( static_reg , unpack ( required_capability , 2 )) 1362then 1363fn ( static_reg ) 1364end 1365end 1366else 1367for _ , reg in ipairs ( dynamic_regs ) do 1368local regoptions =vim . tbl_get ( reg , 'registerOptions' ) 1369if 1370( 1371has_subprovider 1372and ( regoptions or lsp . protocol . _methods_with_no_registration_options [ method ]) 1373) 1374or not has_subcap 1375or vim . tbl_get ( regoptions , unpack ( required_capability , 2 )) 1376then 1377fn ( regoptions or {} ) 1378end 1379end 1380end 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 ) 1390log . trace ( 'notification' , method , params ) 1391local handler =self : _resolve_handler ( method ) 1392if handler then 1393-- Method name is provided here for convenience. 1394handler ( nil , params , { method =method , client_id =self . id } ) 1395end 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 ) 1406log . trace ( 'server_request' , method , params ) 1407local handler =self : _resolve_handler ( method ) 1408if handler then 1409log . trace ( 'server_request: found handler for' , method ) 1410return handler ( nil , params , { method =method , client_id =self . id } ) 1411end 1412log . warn ( 'server_request: no handler found for' , method ) 1413return 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 ) 1424self : write_error ( code , err ) 1425if self . _on_error_cb then 1426local status , usererr =pcall ( self . _on_error_cb , code , err ) 1427if not status then 1428log . error ( self . _log_prefix , 'user on_error failed' , { err =usererr } ) 1429err_message ( self . _log_prefix , ' user on_error failed: ' , tostring ( usererr )) 1430end 1431end 1432end 1433 1434---@param bufnr integer resolved buffer 1435function Client : _on_detach ( bufnr ) 1436if self . attached_buffers [ bufnr ] and api . nvim_buf_is_valid ( bufnr ) then 1437api . nvim_exec_autocmds ( 'LspDetach' , { 1438buf =bufnr , 1439modeline =false , 1440data ={ client_id =self . id } , 1441} ) 1442end 1443 1444for _ , Capability in pairs ( lsp . _capability . all ) do 1445if 1446self : supports_method ( Capability . method ) 1447and lsp . _capability . is_enabled ( Capability . name , { 1448bufnr =bufnr , 1449client_id =self . id , 1450} ) 1451then 1452local capability =Capability . active [ bufnr ] 1453if capability then 1454capability : on_detach ( self . id ) 1455if next ( capability . client_state ) == nil then 1456capability : destroy () 1457end 1458end 1459end 1460end 1461 1462vim . diagnostic . reset ( lsp . diagnostic . get_namespace ( self . id , false ), bufnr ) 1463 1464changetracking . reset_buf ( self , bufnr ) 1465 1466self : _text_document_did_close_handler ( bufnr ) 1467 1468self . 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 ) 1475if vim . bo [ bufnr ]. tagfunc == lsp . tagfunc then 1476vim . bo [ bufnr ]. tagfunc =nil 1477end 1478if vim . bo [ bufnr ]. omnifunc == lsp . omnifunc then 1479vim . bo [ bufnr ]. omnifunc =nil 1480end 1481if vim . bo [ bufnr ]. formatexpr == 'v:lua.vim.lsp.formatexpr()' then 1482vim . bo [ bufnr ]. formatexpr =nil 1483end 1484vim . _with ( { buf =bufnr } , function () 1485local keymap =vim . fn . maparg ( 'K' , 'n' , false , true ) 1486if keymap and keymap . callback == lsp . buf . hover and keymap . buffer == 1 then 1487vim . keymap . del ( 'n' , 'K' , { buf =bufnr } ) 1488end 1489end ) 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 ) 1498if self . _shutdown_timer and not self . _shutdown_timer : is_closing () then 1499self . _shutdown_timer : close () 1500self . _shutdown_timer =nil 1501end 1502 1503vim . schedule ( function () 1504for bufnr in pairs ( self . attached_buffers ) do 1505self : _on_detach ( bufnr ) 1506if # lsp . get_clients ( { bufnr =bufnr , _uninitialized =true } ) == 0 then 1507reset_defaults ( bufnr ) 1508end 1509end 1510 1511-- Schedule the deletion of the client object 1512-- so that it exists in the execution of autocommands 1513vim . schedule ( function () 1514all_clients [ self . id ] =nil 1515 1516-- Client can be absent if executable starts, but initialize fails 1517-- init/attach won't have happened 1518if self then 1519changetracking . reset ( self ) 1520end 1521if code ~= 0 or ( signal ~= 0 and signal ~= 15 ) then 1522local msg =string . format ( 1523'Client %s quit with exit code %s and signal %s. Check log for errors: %s' , 1524self and self . name or 'unknown' , 1525code , 1526signal , 1527log . get_filename () 1528) 1529vim . notify ( msg , vim . log . levels . WARN ) 1530end 1531end ) 1532end ) 1533 1534if self . _handle_restart ~= nil then 1535self . _handle_restart () 1536self . _handle_restart =nil 1537end 1538 1539self : _run_callbacks ( 1540self . _on_exit_cbs , 1541lsp . client_errors . ON_EXIT_CALLBACK_ERROR , 1542code , 1543signal , 1544self . id 1545) 1546end 1547 1548--- Add a directory to the workspace folders. 1549--- @param dir string? 1550function Client : _add_workspace_folder ( dir ) 1551for _ , folder in pairs ( self . workspace_folders or {} ) do 1552if folder . name == dir then 1553( dir , 'is already part of this workspace' ) 1554return 1555end 1556end 1557 1558local wf =assert ( lsp . _get_workspace_folders ( dir )) 1559 1560self : notify ( 'workspace/didChangeWorkspaceFolders' , { 1561event ={ added =wf , removed ={} } , 1562} ) 1563 1564if not self . workspace_folders then 1565self . workspace_folders ={} 1566end 1567vim . 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 ) 1573local wf =assert ( lsp . _get_workspace_folders ( dir )) 1574 1575self : notify ( 'workspace/didChangeWorkspaceFolders' , { 1576event ={ added ={} , removed =wf } , 1577} ) 1578 1579if self . workspace_folders then 1580for idx , folder in pairs ( self . workspace_folders ) do 1581if folder . name == dir then 1582table . remove ( self . workspace_folders , idx ) 1583break 1584end 1585end 1586end 1587end 1588 1589-- Export for internal use only. 1590Client . _all =all_clients 1591 1592return Client