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