lsp.lua 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546
  1. local api = vim.api
  2. local validate = vim.validate
  3. local lsp = vim._defer_require('vim.lsp', {
  4. _changetracking = ..., --- @module 'vim.lsp._changetracking'
  5. _folding_range = ..., --- @module 'vim.lsp._folding_range'
  6. _snippet_grammar = ..., --- @module 'vim.lsp._snippet_grammar'
  7. _tagfunc = ..., --- @module 'vim.lsp._tagfunc'
  8. _watchfiles = ..., --- @module 'vim.lsp._watchfiles'
  9. buf = ..., --- @module 'vim.lsp.buf'
  10. client = ..., --- @module 'vim.lsp.client'
  11. codelens = ..., --- @module 'vim.lsp.codelens'
  12. completion = ..., --- @module 'vim.lsp.completion'
  13. diagnostic = ..., --- @module 'vim.lsp.diagnostic'
  14. handlers = ..., --- @module 'vim.lsp.handlers'
  15. inlay_hint = ..., --- @module 'vim.lsp.inlay_hint'
  16. log = ..., --- @module 'vim.lsp.log'
  17. protocol = ..., --- @module 'vim.lsp.protocol'
  18. rpc = ..., --- @module 'vim.lsp.rpc'
  19. semantic_tokens = ..., --- @module 'vim.lsp.semantic_tokens'
  20. util = ..., --- @module 'vim.lsp.util'
  21. })
  22. local log = lsp.log
  23. local protocol = lsp.protocol
  24. local ms = protocol.Methods
  25. local util = lsp.util
  26. local changetracking = lsp._changetracking
  27. -- Export these directly from rpc.
  28. ---@nodoc
  29. lsp.rpc_response_error = lsp.rpc.rpc_response_error
  30. lsp._resolve_to_request = {
  31. [ms.codeAction_resolve] = ms.textDocument_codeAction,
  32. [ms.codeLens_resolve] = ms.textDocument_codeLens,
  33. [ms.documentLink_resolve] = ms.textDocument_documentLink,
  34. [ms.inlayHint_resolve] = ms.textDocument_inlayHint,
  35. }
  36. -- maps request name to the required server_capability in the client.
  37. lsp._request_name_to_capability = {
  38. [ms.callHierarchy_incomingCalls] = { 'callHierarchyProvider' },
  39. [ms.callHierarchy_outgoingCalls] = { 'callHierarchyProvider' },
  40. [ms.codeAction_resolve] = { 'codeActionProvider', 'resolveProvider' },
  41. [ms.codeLens_resolve] = { 'codeLensProvider', 'resolveProvider' },
  42. [ms.documentLink_resolve] = { 'documentLinkProvider', 'resolveProvider' },
  43. [ms.inlayHint_resolve] = { 'inlayHintProvider', 'resolveProvider' },
  44. [ms.textDocument_codeAction] = { 'codeActionProvider' },
  45. [ms.textDocument_codeLens] = { 'codeLensProvider' },
  46. [ms.textDocument_completion] = { 'completionProvider' },
  47. [ms.textDocument_declaration] = { 'declarationProvider' },
  48. [ms.textDocument_definition] = { 'definitionProvider' },
  49. [ms.textDocument_diagnostic] = { 'diagnosticProvider' },
  50. [ms.textDocument_didClose] = { 'textDocumentSync', 'openClose' },
  51. [ms.textDocument_didOpen] = { 'textDocumentSync', 'openClose' },
  52. [ms.textDocument_documentColor] = { 'colorProvider' },
  53. [ms.textDocument_documentHighlight] = { 'documentHighlightProvider' },
  54. [ms.textDocument_documentLink] = { 'documentLinkProvider' },
  55. [ms.textDocument_documentSymbol] = { 'documentSymbolProvider' },
  56. [ms.textDocument_foldingRange] = { 'foldingRangeProvider' },
  57. [ms.textDocument_formatting] = { 'documentFormattingProvider' },
  58. [ms.textDocument_hover] = { 'hoverProvider' },
  59. [ms.textDocument_implementation] = { 'implementationProvider' },
  60. [ms.textDocument_inlayHint] = { 'inlayHintProvider' },
  61. [ms.textDocument_inlineValue] = { 'inlineValueProvider' },
  62. [ms.textDocument_linkedEditingRange] = { 'linkedEditingRangeProvider' },
  63. [ms.textDocument_moniker] = { 'monikerProvider' },
  64. [ms.textDocument_onTypeFormatting] = { 'documentOnTypeFormattingProvider' },
  65. [ms.textDocument_prepareCallHierarchy] = { 'callHierarchyProvider' },
  66. [ms.textDocument_prepareRename] = { 'renameProvider', 'prepareProvider' },
  67. [ms.textDocument_prepareTypeHierarchy] = { 'typeHierarchyProvider' },
  68. [ms.textDocument_rangeFormatting] = { 'documentRangeFormattingProvider' },
  69. [ms.textDocument_rangesFormatting] = { 'documentRangeFormattingProvider', 'rangesSupport' },
  70. [ms.textDocument_references] = { 'referencesProvider' },
  71. [ms.textDocument_rename] = { 'renameProvider' },
  72. [ms.textDocument_selectionRange] = { 'selectionRangeProvider' },
  73. [ms.textDocument_semanticTokens_full] = { 'semanticTokensProvider' },
  74. [ms.textDocument_semanticTokens_full_delta] = { 'semanticTokensProvider' },
  75. [ms.textDocument_signatureHelp] = { 'signatureHelpProvider' },
  76. [ms.textDocument_typeDefinition] = { 'typeDefinitionProvider' },
  77. [ms.textDocument_willSaveWaitUntil] = { 'textDocumentSync', 'willSaveWaitUntil' },
  78. [ms.textDocument_willSave] = { 'textDocumentSync', 'willSave' },
  79. [ms.typeHierarchy_subtypes] = { 'typeHierarchyProvider' },
  80. [ms.typeHierarchy_supertypes] = { 'typeHierarchyProvider' },
  81. [ms.workspace_executeCommand] = { 'executeCommandProvider' },
  82. [ms.workspace_symbol] = { 'workspaceSymbolProvider' },
  83. }
  84. -- TODO improve handling of scratch buffers with LSP attached.
  85. ---@private
  86. --- Called by the client when trying to call a method that's not
  87. --- supported in any of the servers registered for the current buffer.
  88. ---@param method (string) name of the method
  89. function lsp._unsupported_method(method)
  90. local msg = string.format(
  91. 'method %s is not supported by any of the servers registered for the current buffer',
  92. method
  93. )
  94. log.warn(msg)
  95. return msg
  96. end
  97. ---@private
  98. ---@param workspace_folders string|lsp.WorkspaceFolder[]?
  99. ---@return lsp.WorkspaceFolder[]?
  100. function lsp._get_workspace_folders(workspace_folders)
  101. if type(workspace_folders) == 'table' then
  102. return workspace_folders
  103. elseif type(workspace_folders) == 'string' then
  104. return {
  105. {
  106. uri = vim.uri_from_fname(workspace_folders),
  107. name = workspace_folders,
  108. },
  109. }
  110. end
  111. end
  112. local wait_result_reason = { [-1] = 'timeout', [-2] = 'interrupted', [-3] = 'error' }
  113. local format_line_ending = {
  114. ['unix'] = '\n',
  115. ['dos'] = '\r\n',
  116. ['mac'] = '\r',
  117. }
  118. ---@private
  119. ---@param bufnr (number)
  120. ---@return string
  121. function lsp._buf_get_line_ending(bufnr)
  122. return format_line_ending[vim.bo[bufnr].fileformat] or '\n'
  123. end
  124. -- Tracks all clients created via lsp.start_client
  125. local all_clients = {} --- @type table<integer,vim.lsp.Client>
  126. local client_errors_base = table.maxn(lsp.rpc.client_errors)
  127. local client_errors_offset = 0
  128. local function client_error(name)
  129. client_errors_offset = client_errors_offset + 1
  130. local index = client_errors_base + client_errors_offset
  131. return { [name] = index, [index] = name }
  132. end
  133. --- Error codes to be used with `on_error` from |vim.lsp.start_client|.
  134. --- Can be used to look up the string from a the number or the number
  135. --- from the string.
  136. --- @nodoc
  137. lsp.client_errors = vim.tbl_extend(
  138. 'error',
  139. lsp.rpc.client_errors,
  140. client_error('BEFORE_INIT_CALLBACK_ERROR'),
  141. client_error('ON_INIT_CALLBACK_ERROR'),
  142. client_error('ON_ATTACH_ERROR'),
  143. client_error('ON_EXIT_CALLBACK_ERROR')
  144. )
  145. ---@private
  146. --- Returns full text of buffer {bufnr} as a string.
  147. ---
  148. ---@param bufnr (number) Buffer handle, or 0 for current.
  149. ---@return string # Buffer text as string.
  150. function lsp._buf_get_full_text(bufnr)
  151. local line_ending = lsp._buf_get_line_ending(bufnr)
  152. local text = table.concat(api.nvim_buf_get_lines(bufnr, 0, -1, true), line_ending)
  153. if vim.bo[bufnr].eol then
  154. text = text .. line_ending
  155. end
  156. return text
  157. end
  158. --- Memoizes a function. On first run, the function return value is saved and
  159. --- immediately returned on subsequent runs. If the function returns a multival,
  160. --- only the first returned value will be memoized and returned. The function will only be run once,
  161. --- even if it has side effects.
  162. ---
  163. ---@generic T: function
  164. ---@param fn (T) Function to run
  165. ---@return T
  166. local function once(fn)
  167. local value --- @type function
  168. local ran = false
  169. return function(...)
  170. if not ran then
  171. value = fn(...) --- @type function
  172. ran = true
  173. end
  174. return value
  175. end
  176. end
  177. --- @param client vim.lsp.Client
  178. --- @param config vim.lsp.ClientConfig
  179. --- @return boolean
  180. local function reuse_client_default(client, config)
  181. if client.name ~= config.name then
  182. return false
  183. end
  184. local config_folders = lsp._get_workspace_folders(config.workspace_folders or config.root_dir)
  185. if not config_folders or not next(config_folders) then
  186. -- Reuse if the client was configured with no workspace folders
  187. local client_config_folders =
  188. lsp._get_workspace_folders(client.config.workspace_folders or client.config.root_dir)
  189. return not client_config_folders or not next(client_config_folders)
  190. end
  191. for _, config_folder in ipairs(config_folders) do
  192. local found = false
  193. for _, client_folder in ipairs(client.workspace_folders or {}) do
  194. if config_folder.uri == client_folder.uri then
  195. found = true
  196. break
  197. end
  198. end
  199. if not found then
  200. return false
  201. end
  202. end
  203. return true
  204. end
  205. --- Reset defaults set by `set_defaults`.
  206. --- Must only be called if the last client attached to a buffer exits.
  207. local function reset_defaults(bufnr)
  208. if vim.bo[bufnr].tagfunc == 'v:lua.vim.lsp.tagfunc' then
  209. vim.bo[bufnr].tagfunc = nil
  210. end
  211. if vim.bo[bufnr].omnifunc == 'v:lua.vim.lsp.omnifunc' then
  212. vim.bo[bufnr].omnifunc = nil
  213. end
  214. if vim.bo[bufnr].formatexpr == 'v:lua.vim.lsp.formatexpr()' then
  215. vim.bo[bufnr].formatexpr = nil
  216. end
  217. vim._with({ buf = bufnr }, function()
  218. local keymap = vim.fn.maparg('K', 'n', false, true)
  219. if keymap and keymap.callback == vim.lsp.buf.hover and keymap.buffer == 1 then
  220. vim.keymap.del('n', 'K', { buffer = bufnr })
  221. end
  222. end)
  223. end
  224. --- @param code integer
  225. --- @param signal integer
  226. --- @param client_id integer
  227. local function on_client_exit(code, signal, client_id)
  228. local client = all_clients[client_id]
  229. vim.schedule(function()
  230. for bufnr in pairs(client.attached_buffers) do
  231. if client and client.attached_buffers[bufnr] and api.nvim_buf_is_valid(bufnr) then
  232. api.nvim_exec_autocmds('LspDetach', {
  233. buffer = bufnr,
  234. modeline = false,
  235. data = { client_id = client_id },
  236. })
  237. end
  238. client.attached_buffers[bufnr] = nil
  239. if #lsp.get_clients({ bufnr = bufnr, _uninitialized = true }) == 0 then
  240. reset_defaults(bufnr)
  241. end
  242. end
  243. local namespace = vim.lsp.diagnostic.get_namespace(client_id)
  244. vim.diagnostic.reset(namespace)
  245. end)
  246. local name = client.name or 'unknown'
  247. -- Schedule the deletion of the client object so that it exists in the execution of LspDetach
  248. -- autocommands
  249. vim.schedule(function()
  250. all_clients[client_id] = nil
  251. -- Client can be absent if executable starts, but initialize fails
  252. -- init/attach won't have happened
  253. if client then
  254. changetracking.reset(client)
  255. end
  256. if code ~= 0 or (signal ~= 0 and signal ~= 15) then
  257. local msg = string.format(
  258. 'Client %s quit with exit code %s and signal %s. Check log for errors: %s',
  259. name,
  260. code,
  261. signal,
  262. lsp.get_log_path()
  263. )
  264. vim.notify(msg, vim.log.levels.WARN)
  265. end
  266. end)
  267. end
  268. --- Creates and initializes a client with the given configuration.
  269. --- @param config vim.lsp.ClientConfig Configuration for the server.
  270. --- @return integer? client_id |vim.lsp.get_client_by_id()| Note: client may not be
  271. --- fully initialized. Use `on_init` to do any actions once
  272. --- the client has been initialized.
  273. --- @return string? # Error message, if any
  274. local function create_and_initialize_client(config)
  275. local ok, res = pcall(require('vim.lsp.client').create, config)
  276. if not ok then
  277. return nil, res --[[@as string]]
  278. end
  279. local client = assert(res)
  280. --- @diagnostic disable-next-line: invisible
  281. table.insert(client._on_exit_cbs, on_client_exit)
  282. all_clients[client.id] = client
  283. client:initialize()
  284. return client.id, nil
  285. end
  286. --- @class vim.lsp.Config : vim.lsp.ClientConfig
  287. ---
  288. --- See `cmd` in [vim.lsp.ClientConfig].
  289. --- @field cmd? string[]|fun(dispatchers: vim.lsp.rpc.Dispatchers): vim.lsp.rpc.PublicClient
  290. ---
  291. --- Filetypes the client will attach to, if activated by `vim.lsp.enable()`.
  292. --- If not provided, then the client will attach to all filetypes.
  293. --- @field filetypes? string[]
  294. ---
  295. --- Directory markers (.e.g. '.git/') where the LSP server will base its workspaceFolders,
  296. --- rootUri, and rootPath on initialization. Unused if `root_dir` is provided.
  297. --- @field root_markers? string[]
  298. ---
  299. --- Predicate used to decide if a client should be re-used. Used on all
  300. --- running clients. The default implementation re-uses a client if name and
  301. --- root_dir matches.
  302. --- @field reuse_client? fun(client: vim.lsp.Client, config: vim.lsp.ClientConfig): boolean
  303. --- Update the configuration for an LSP client.
  304. ---
  305. --- Use name '*' to set default configuration for all clients.
  306. ---
  307. --- Can also be table-assigned to redefine the configuration for a client.
  308. ---
  309. --- Examples:
  310. ---
  311. --- - Add a root marker for all clients:
  312. --- ```lua
  313. --- vim.lsp.config('*', {
  314. --- root_markers = { '.git' },
  315. --- })
  316. --- ```
  317. --- - Add additional capabilities to all clients:
  318. --- ```lua
  319. --- vim.lsp.config('*', {
  320. --- capabilities = {
  321. --- textDocument = {
  322. --- semanticTokens = {
  323. --- multilineTokenSupport = true,
  324. --- }
  325. --- }
  326. --- }
  327. --- })
  328. --- ```
  329. --- - (Re-)define the configuration for clangd:
  330. --- ```lua
  331. --- vim.lsp.config.clangd = {
  332. --- cmd = {
  333. --- 'clangd',
  334. --- '--clang-tidy',
  335. --- '--background-index',
  336. --- '--offset-encoding=utf-8',
  337. --- },
  338. --- root_markers = { '.clangd', 'compile_commands.json' },
  339. --- filetypes = { 'c', 'cpp' },
  340. --- }
  341. --- ```
  342. --- - Get configuration for luals:
  343. --- ```lua
  344. --- local cfg = vim.lsp.config.luals
  345. --- ```
  346. ---
  347. --- @param name string
  348. --- @param cfg vim.lsp.Config
  349. --- @diagnostic disable-next-line:assign-type-mismatch
  350. function lsp.config(name, cfg)
  351. local _, _ = name, cfg -- ignore unused
  352. -- dummy proto for docs
  353. end
  354. lsp._enabled_configs = {} --- @type table<string,{resolved_config:vim.lsp.Config?}>
  355. --- If a config in vim.lsp.config() is accessed then the resolved config becomes invalid.
  356. --- @param name string
  357. local function invalidate_enabled_config(name)
  358. if name == '*' then
  359. for _, v in pairs(lsp._enabled_configs) do
  360. v.resolved_config = nil
  361. end
  362. elseif lsp._enabled_configs[name] then
  363. lsp._enabled_configs[name].resolved_config = nil
  364. end
  365. end
  366. --- @nodoc
  367. --- @class vim.lsp.config
  368. --- @field [string] vim.lsp.Config
  369. --- @field package _configs table<string,vim.lsp.Config>
  370. lsp.config = setmetatable({ _configs = {} }, {
  371. --- @param self vim.lsp.config
  372. --- @param name string
  373. --- @return vim.lsp.Config
  374. __index = function(self, name)
  375. validate('name', name, 'string')
  376. invalidate_enabled_config(name)
  377. self._configs[name] = self._configs[name] or {}
  378. return self._configs[name]
  379. end,
  380. --- @param self vim.lsp.config
  381. --- @param name string
  382. --- @param cfg vim.lsp.Config
  383. __newindex = function(self, name, cfg)
  384. validate('name', name, 'string')
  385. validate('cfg', cfg, 'table')
  386. invalidate_enabled_config(name)
  387. self._configs[name] = cfg
  388. end,
  389. --- @param self vim.lsp.config
  390. --- @param name string
  391. --- @param cfg vim.lsp.Config
  392. __call = function(self, name, cfg)
  393. validate('name', name, 'string')
  394. validate('cfg', cfg, 'table')
  395. invalidate_enabled_config(name)
  396. self[name] = vim.tbl_deep_extend('force', self._configs[name] or {}, cfg)
  397. end,
  398. })
  399. --- @private
  400. --- @param name string
  401. --- @return vim.lsp.Config
  402. function lsp._resolve_config(name)
  403. local econfig = lsp._enabled_configs[name] or {}
  404. if not econfig.resolved_config then
  405. -- Resolve configs from lsp/*.lua
  406. -- Calls to vim.lsp.config in lsp/* have a lower precedence than calls from other sites.
  407. local rtp_config = {} ---@type vim.lsp.Config
  408. for _, v in ipairs(api.nvim_get_runtime_file(('lsp/%s.lua'):format(name), true)) do
  409. local config = assert(loadfile(v))() ---@type any?
  410. if type(config) == 'table' then
  411. rtp_config = vim.tbl_deep_extend('force', rtp_config, config)
  412. else
  413. log.warn(string.format('%s does not return a table, ignoring', v))
  414. end
  415. end
  416. local config = vim.tbl_deep_extend(
  417. 'force',
  418. lsp.config._configs['*'] or {},
  419. rtp_config,
  420. lsp.config._configs[name] or {}
  421. )
  422. config.name = name
  423. validate('cmd', config.cmd, { 'function', 'table' })
  424. validate('cmd', config.reuse_client, 'function', true)
  425. -- All other fields are validated in client.create
  426. econfig.resolved_config = config
  427. end
  428. return assert(econfig.resolved_config)
  429. end
  430. local lsp_enable_autocmd_id --- @type integer?
  431. --- @param bufnr integer
  432. local function lsp_enable_callback(bufnr)
  433. -- Only ever attach to buffers that represent an actual file.
  434. if vim.bo[bufnr].buftype ~= '' then
  435. return
  436. end
  437. --- @param config vim.lsp.Config
  438. local function can_start(config)
  439. if config.filetypes and not vim.tbl_contains(config.filetypes, vim.bo[bufnr].filetype) then
  440. return false
  441. elseif type(config.cmd) == 'table' and vim.fn.executable(config.cmd[1]) == 0 then
  442. return false
  443. end
  444. return true
  445. end
  446. for name in vim.spairs(lsp._enabled_configs) do
  447. local config = lsp._resolve_config(name)
  448. if can_start(config) then
  449. -- Deepcopy config so changes done in the client
  450. -- do not propagate back to the enabled configs.
  451. config = vim.deepcopy(config)
  452. vim.lsp.start(config, {
  453. bufnr = bufnr,
  454. reuse_client = config.reuse_client,
  455. _root_markers = config.root_markers,
  456. })
  457. end
  458. end
  459. end
  460. --- Enable an LSP server to automatically start when opening a buffer.
  461. ---
  462. --- Uses configuration defined with `vim.lsp.config`.
  463. ---
  464. --- Examples:
  465. ---
  466. --- ```lua
  467. --- vim.lsp.enable('clangd')
  468. ---
  469. --- vim.lsp.enable({'luals', 'pyright'})
  470. --- ```
  471. ---
  472. --- @param name string|string[] Name(s) of client(s) to enable.
  473. --- @param enable? boolean `true|nil` to enable, `false` to disable.
  474. function lsp.enable(name, enable)
  475. validate('name', name, { 'string', 'table' })
  476. local names = vim._ensure_list(name) --[[@as string[] ]]
  477. for _, nm in ipairs(names) do
  478. if nm == '*' then
  479. error('Invalid name')
  480. end
  481. lsp._enabled_configs[nm] = enable == false and nil or {}
  482. end
  483. if not next(lsp._enabled_configs) then
  484. if lsp_enable_autocmd_id then
  485. api.nvim_del_autocmd(lsp_enable_autocmd_id)
  486. lsp_enable_autocmd_id = nil
  487. end
  488. return
  489. end
  490. -- Only ever create autocmd once to reuse computation of config merging.
  491. lsp_enable_autocmd_id = lsp_enable_autocmd_id
  492. or api.nvim_create_autocmd('FileType', {
  493. group = api.nvim_create_augroup('nvim.lsp.enable', {}),
  494. callback = function(args)
  495. lsp_enable_callback(args.buf)
  496. end,
  497. })
  498. end
  499. --- @class vim.lsp.start.Opts
  500. --- @inlinedoc
  501. ---
  502. --- Predicate used to decide if a client should be re-used. Used on all
  503. --- running clients. The default implementation re-uses a client if it has the
  504. --- same name and if the given workspace folders (or root_dir) are all included
  505. --- in the client's workspace folders.
  506. --- @field reuse_client? fun(client: vim.lsp.Client, config: vim.lsp.ClientConfig): boolean
  507. ---
  508. --- Buffer handle to attach to if starting or re-using a client (0 for current).
  509. --- @field bufnr? integer
  510. ---
  511. --- Whether to attach the client to a buffer (default true).
  512. --- If set to `false`, `reuse_client` and `bufnr` will be ignored.
  513. --- @field attach? boolean
  514. ---
  515. --- Suppress error reporting if the LSP server fails to start (default false).
  516. --- @field silent? boolean
  517. ---
  518. --- @field package _root_markers? string[]
  519. --- Create a new LSP client and start a language server or reuses an already
  520. --- running client if one is found matching `name` and `root_dir`.
  521. --- Attaches the current buffer to the client.
  522. ---
  523. --- Example:
  524. ---
  525. --- ```lua
  526. --- vim.lsp.start({
  527. --- name = 'my-server-name',
  528. --- cmd = {'name-of-language-server-executable'},
  529. --- root_dir = vim.fs.root(0, {'pyproject.toml', 'setup.py'}),
  530. --- })
  531. --- ```
  532. ---
  533. --- See |vim.lsp.ClientConfig| for all available options. The most important are:
  534. ---
  535. --- - `name` arbitrary name for the LSP client. Should be unique per language server.
  536. --- - `cmd` command string[] or function.
  537. --- - `root_dir` path to the project root. By default this is used to decide if an existing client
  538. --- should be re-used. The example above uses |vim.fs.root()| to detect the root by traversing
  539. --- the file system upwards starting from the current directory until either a `pyproject.toml`
  540. --- or `setup.py` file is found.
  541. --- - `workspace_folders` list of `{ uri:string, name: string }` tables specifying the project root
  542. --- folders used by the language server. If `nil` the property is derived from `root_dir` for
  543. --- convenience.
  544. ---
  545. --- Language servers use this information to discover metadata like the
  546. --- dependencies of your project and they tend to index the contents within the
  547. --- project folder.
  548. ---
  549. ---
  550. --- To ensure a language server is only started for languages it can handle,
  551. --- make sure to call |vim.lsp.start()| within a |FileType| autocmd.
  552. --- Either use |:au|, |nvim_create_autocmd()| or put the call in a
  553. --- `ftplugin/<filetype_name>.lua` (See |ftplugin-name|)
  554. ---
  555. --- @param config vim.lsp.ClientConfig Configuration for the server.
  556. --- @param opts vim.lsp.start.Opts? Optional keyword arguments.
  557. --- @return integer? client_id
  558. function lsp.start(config, opts)
  559. opts = opts or {}
  560. local reuse_client = opts.reuse_client or reuse_client_default
  561. local bufnr = vim._resolve_bufnr(opts.bufnr)
  562. if not config.root_dir and opts._root_markers then
  563. config = vim.deepcopy(config)
  564. config.root_dir = vim.fs.root(bufnr, opts._root_markers)
  565. end
  566. for _, client in pairs(all_clients) do
  567. if reuse_client(client, config) then
  568. if opts.attach == false then
  569. return client.id
  570. end
  571. if lsp.buf_attach_client(bufnr, client.id) then
  572. return client.id
  573. end
  574. return
  575. end
  576. end
  577. local client_id, err = create_and_initialize_client(config)
  578. if err then
  579. if not opts.silent then
  580. vim.notify(err, vim.log.levels.WARN)
  581. end
  582. return
  583. end
  584. if opts.attach == false then
  585. return client_id
  586. end
  587. if client_id and lsp.buf_attach_client(bufnr, client_id) then
  588. return client_id
  589. end
  590. end
  591. --- Consumes the latest progress messages from all clients and formats them as a string.
  592. --- Empty if there are no clients or if no new messages
  593. ---
  594. ---@return string
  595. function lsp.status()
  596. local percentage = nil
  597. local messages = {} --- @type string[]
  598. for _, client in ipairs(vim.lsp.get_clients()) do
  599. --- @diagnostic disable-next-line:no-unknown
  600. for progress in client.progress do
  601. --- @cast progress {token: lsp.ProgressToken, value: lsp.LSPAny}
  602. local value = progress.value
  603. if type(value) == 'table' and value.kind then
  604. local message = value.message and (value.title .. ': ' .. value.message) or value.title
  605. messages[#messages + 1] = message
  606. if value.percentage then
  607. percentage = math.max(percentage or 0, value.percentage)
  608. end
  609. end
  610. -- else: Doesn't look like work done progress and can be in any format
  611. -- Just ignore it as there is no sensible way to display it
  612. end
  613. end
  614. local message = table.concat(messages, ', ')
  615. if percentage then
  616. return string.format('%3d%%: %s', percentage, message)
  617. end
  618. return message
  619. end
  620. -- Determines whether the given option can be set by `set_defaults`.
  621. ---@param bufnr integer
  622. ---@param option string
  623. ---@return boolean
  624. local function is_empty_or_default(bufnr, option)
  625. if vim.bo[bufnr][option] == '' then
  626. return true
  627. end
  628. local info = api.nvim_get_option_info2(option, { buf = bufnr })
  629. ---@param e vim.fn.getscriptinfo.ret
  630. local scriptinfo = vim.tbl_filter(function(e)
  631. return e.sid == info.last_set_sid
  632. end, vim.fn.getscriptinfo())
  633. if #scriptinfo ~= 1 then
  634. return false
  635. end
  636. return vim.startswith(scriptinfo[1].name, vim.fn.expand('$VIMRUNTIME'))
  637. end
  638. ---@private
  639. ---@param client vim.lsp.Client
  640. ---@param bufnr integer
  641. function lsp._set_defaults(client, bufnr)
  642. if
  643. client:supports_method(ms.textDocument_definition) and is_empty_or_default(bufnr, 'tagfunc')
  644. then
  645. vim.bo[bufnr].tagfunc = 'v:lua.vim.lsp.tagfunc'
  646. end
  647. if
  648. client:supports_method(ms.textDocument_completion) and is_empty_or_default(bufnr, 'omnifunc')
  649. then
  650. vim.bo[bufnr].omnifunc = 'v:lua.vim.lsp.omnifunc'
  651. end
  652. if
  653. client:supports_method(ms.textDocument_rangeFormatting)
  654. and is_empty_or_default(bufnr, 'formatprg')
  655. and is_empty_or_default(bufnr, 'formatexpr')
  656. then
  657. vim.bo[bufnr].formatexpr = 'v:lua.vim.lsp.formatexpr()'
  658. end
  659. vim._with({ buf = bufnr }, function()
  660. if
  661. client:supports_method(ms.textDocument_hover)
  662. and is_empty_or_default(bufnr, 'keywordprg')
  663. and vim.fn.maparg('K', 'n', false, false) == ''
  664. then
  665. vim.keymap.set('n', 'K', function()
  666. vim.lsp.buf.hover()
  667. end, { buffer = bufnr, desc = 'vim.lsp.buf.hover()' })
  668. end
  669. end)
  670. if client:supports_method(ms.textDocument_diagnostic) then
  671. lsp.diagnostic._enable(bufnr)
  672. end
  673. end
  674. --- @deprecated
  675. --- Starts and initializes a client with the given configuration.
  676. --- @param config vim.lsp.ClientConfig Configuration for the server.
  677. --- @return integer? client_id |vim.lsp.get_client_by_id()| Note: client may not be
  678. --- fully initialized. Use `on_init` to do any actions once
  679. --- the client has been initialized.
  680. --- @return string? # Error message, if any
  681. function lsp.start_client(config)
  682. vim.deprecate('vim.lsp.start_client()', 'vim.lsp.start()', '0.13')
  683. return create_and_initialize_client(config)
  684. end
  685. ---Buffer lifecycle handler for textDocument/didSave
  686. --- @param bufnr integer
  687. local function text_document_did_save_handler(bufnr)
  688. bufnr = vim._resolve_bufnr(bufnr)
  689. local uri = vim.uri_from_bufnr(bufnr)
  690. local text = once(lsp._buf_get_full_text)
  691. for _, client in ipairs(lsp.get_clients({ bufnr = bufnr })) do
  692. local name = api.nvim_buf_get_name(bufnr)
  693. local old_name = changetracking._get_and_set_name(client, bufnr, name)
  694. if old_name and name ~= old_name then
  695. client:notify(ms.textDocument_didClose, {
  696. textDocument = {
  697. uri = vim.uri_from_fname(old_name),
  698. },
  699. })
  700. client:notify(ms.textDocument_didOpen, {
  701. textDocument = {
  702. version = 0,
  703. uri = uri,
  704. languageId = client.get_language_id(bufnr, vim.bo[bufnr].filetype),
  705. text = lsp._buf_get_full_text(bufnr),
  706. },
  707. })
  708. util.buf_versions[bufnr] = 0
  709. end
  710. local save_capability = vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'save')
  711. if save_capability then
  712. local included_text --- @type string?
  713. if type(save_capability) == 'table' and save_capability.includeText then
  714. included_text = text(bufnr)
  715. end
  716. client:notify(ms.textDocument_didSave, {
  717. textDocument = {
  718. uri = uri,
  719. },
  720. text = included_text,
  721. })
  722. end
  723. end
  724. end
  725. ---@param bufnr integer resolved buffer
  726. ---@param client vim.lsp.Client
  727. local function buf_detach_client(bufnr, client)
  728. api.nvim_exec_autocmds('LspDetach', {
  729. buffer = bufnr,
  730. modeline = false,
  731. data = { client_id = client.id },
  732. })
  733. changetracking.reset_buf(client, bufnr)
  734. if client:supports_method(ms.textDocument_didClose) then
  735. local uri = vim.uri_from_bufnr(bufnr)
  736. local params = { textDocument = { uri = uri } }
  737. client:notify(ms.textDocument_didClose, params)
  738. end
  739. client.attached_buffers[bufnr] = nil
  740. local namespace = lsp.diagnostic.get_namespace(client.id)
  741. vim.diagnostic.reset(namespace, bufnr)
  742. end
  743. --- @type table<integer,true>
  744. local attached_buffers = {}
  745. --- @param bufnr integer
  746. local function buf_attach(bufnr)
  747. if attached_buffers[bufnr] then
  748. return
  749. end
  750. attached_buffers[bufnr] = true
  751. local uri = vim.uri_from_bufnr(bufnr)
  752. local augroup = ('lsp_b_%d_save'):format(bufnr)
  753. local group = api.nvim_create_augroup(augroup, { clear = true })
  754. api.nvim_create_autocmd('BufWritePre', {
  755. group = group,
  756. buffer = bufnr,
  757. desc = 'vim.lsp: textDocument/willSave',
  758. callback = function(ctx)
  759. for _, client in ipairs(lsp.get_clients({ bufnr = ctx.buf })) do
  760. local params = {
  761. textDocument = {
  762. uri = uri,
  763. },
  764. reason = protocol.TextDocumentSaveReason.Manual, ---@type integer
  765. }
  766. if client:supports_method(ms.textDocument_willSave) then
  767. client:notify(ms.textDocument_willSave, params)
  768. end
  769. if client:supports_method(ms.textDocument_willSaveWaitUntil) then
  770. local result, err =
  771. client:request_sync(ms.textDocument_willSaveWaitUntil, params, 1000, ctx.buf)
  772. if result and result.result then
  773. util.apply_text_edits(result.result, ctx.buf, client.offset_encoding)
  774. elseif err then
  775. log.error(vim.inspect(err))
  776. end
  777. end
  778. end
  779. end,
  780. })
  781. api.nvim_create_autocmd('BufWritePost', {
  782. group = group,
  783. buffer = bufnr,
  784. desc = 'vim.lsp: textDocument/didSave handler',
  785. callback = function(ctx)
  786. text_document_did_save_handler(ctx.buf)
  787. end,
  788. })
  789. -- First time, so attach and set up stuff.
  790. api.nvim_buf_attach(bufnr, false, {
  791. on_lines = function(_, _, changedtick, firstline, lastline, new_lastline)
  792. if #lsp.get_clients({ bufnr = bufnr }) == 0 then
  793. -- detach if there are no clients
  794. return #lsp.get_clients({ bufnr = bufnr, _uninitialized = true }) == 0
  795. end
  796. util.buf_versions[bufnr] = changedtick
  797. changetracking.send_changes(bufnr, firstline, lastline, new_lastline)
  798. end,
  799. on_reload = function()
  800. local clients = lsp.get_clients({ bufnr = bufnr })
  801. local params = { textDocument = { uri = uri } }
  802. for _, client in ipairs(clients) do
  803. changetracking.reset_buf(client, bufnr)
  804. if client:supports_method(ms.textDocument_didClose) then
  805. client:notify(ms.textDocument_didClose, params)
  806. end
  807. end
  808. for _, client in ipairs(clients) do
  809. client:_text_document_did_open_handler(bufnr)
  810. end
  811. end,
  812. on_detach = function()
  813. local clients = lsp.get_clients({ bufnr = bufnr, _uninitialized = true })
  814. for _, client in ipairs(clients) do
  815. buf_detach_client(bufnr, client)
  816. end
  817. attached_buffers[bufnr] = nil
  818. util.buf_versions[bufnr] = nil
  819. end,
  820. -- TODO if we know all of the potential clients ahead of time, then we
  821. -- could conditionally set this.
  822. -- utf_sizes = size_index > 1;
  823. utf_sizes = true,
  824. })
  825. end
  826. --- Implements the `textDocument/did…` notifications required to track a buffer
  827. --- for any language server.
  828. ---
  829. --- Without calling this, the server won't be notified of changes to a buffer.
  830. ---
  831. ---@param bufnr (integer) Buffer handle, or 0 for current
  832. ---@param client_id (integer) Client id
  833. ---@return boolean success `true` if client was attached successfully; `false` otherwise
  834. function lsp.buf_attach_client(bufnr, client_id)
  835. validate('bufnr', bufnr, 'number', true)
  836. validate('client_id', client_id, 'number')
  837. bufnr = vim._resolve_bufnr(bufnr)
  838. if not api.nvim_buf_is_loaded(bufnr) then
  839. log.warn(string.format('buf_attach_client called on unloaded buffer (id: %d): ', bufnr))
  840. return false
  841. end
  842. local client = lsp.get_client_by_id(client_id)
  843. if not client then
  844. return false
  845. end
  846. buf_attach(bufnr)
  847. if client.attached_buffers[bufnr] then
  848. return true
  849. end
  850. client.attached_buffers[bufnr] = true
  851. -- This is our first time attaching this client to this buffer.
  852. -- Send didOpen for the client if it is initialized. If it isn't initialized
  853. -- then it will send didOpen on initialize.
  854. if client.initialized then
  855. client:on_attach(bufnr)
  856. end
  857. return true
  858. end
  859. --- Detaches client from the specified buffer.
  860. --- Note: While the server is notified that the text document (buffer)
  861. --- was closed, it is still able to send notifications should it ignore this notification.
  862. ---
  863. ---@param bufnr integer Buffer handle, or 0 for current
  864. ---@param client_id integer Client id
  865. function lsp.buf_detach_client(bufnr, client_id)
  866. validate('bufnr', bufnr, 'number', true)
  867. validate('client_id', client_id, 'number')
  868. bufnr = vim._resolve_bufnr(bufnr)
  869. local client = all_clients[client_id]
  870. if not client or not client.attached_buffers[bufnr] then
  871. vim.notify(
  872. string.format(
  873. 'Buffer (id: %d) is not attached to client (id: %d). Cannot detach.',
  874. bufnr,
  875. client_id
  876. )
  877. )
  878. return
  879. else
  880. buf_detach_client(bufnr, client)
  881. end
  882. end
  883. --- Checks if a buffer is attached for a particular client.
  884. ---
  885. ---@param bufnr (integer) Buffer handle, or 0 for current
  886. ---@param client_id (integer) the client id
  887. function lsp.buf_is_attached(bufnr, client_id)
  888. return lsp.get_clients({ bufnr = bufnr, id = client_id, _uninitialized = true })[1] ~= nil
  889. end
  890. --- Gets a client by id, or nil if the id is invalid.
  891. --- The returned client may not yet be fully initialized.
  892. ---
  893. ---@param client_id integer client id
  894. ---
  895. ---@return (nil|vim.lsp.Client) client rpc object
  896. function lsp.get_client_by_id(client_id)
  897. return all_clients[client_id]
  898. end
  899. --- Returns list of buffers attached to client_id.
  900. ---
  901. ---@param client_id integer client id
  902. ---@return integer[] buffers list of buffer ids
  903. function lsp.get_buffers_by_client_id(client_id)
  904. local client = all_clients[client_id]
  905. return client and vim.tbl_keys(client.attached_buffers) or {}
  906. end
  907. --- Stops a client(s).
  908. ---
  909. --- You can also use the `stop()` function on a |vim.lsp.Client| object.
  910. --- To stop all clients:
  911. ---
  912. --- ```lua
  913. --- vim.lsp.stop_client(vim.lsp.get_clients())
  914. --- ```
  915. ---
  916. --- By default asks the server to shutdown, unless stop was requested
  917. --- already for this client, then force-shutdown is attempted.
  918. ---
  919. ---@param client_id integer|integer[]|vim.lsp.Client[] id, list of id's, or list of |vim.lsp.Client| objects
  920. ---@param force? boolean shutdown forcefully
  921. function lsp.stop_client(client_id, force)
  922. --- @type integer[]|vim.lsp.Client[]
  923. local ids = type(client_id) == 'table' and client_id or { client_id }
  924. for _, id in ipairs(ids) do
  925. if type(id) == 'table' then
  926. if id.stop then
  927. id:stop(force)
  928. end
  929. else
  930. --- @cast id -vim.lsp.Client
  931. local client = all_clients[id]
  932. if client then
  933. client:stop(force)
  934. end
  935. end
  936. end
  937. end
  938. --- Key-value pairs used to filter the returned clients.
  939. --- @class vim.lsp.get_clients.Filter
  940. --- @inlinedoc
  941. ---
  942. --- Only return clients with the given id
  943. --- @field id? integer
  944. ---
  945. --- Only return clients attached to this buffer
  946. --- @field bufnr? integer
  947. ---
  948. --- Only return clients with the given name
  949. --- @field name? string
  950. ---
  951. --- Only return clients supporting the given method
  952. --- @field method? string
  953. ---
  954. --- Also return uninitialized clients.
  955. --- @field package _uninitialized? boolean
  956. --- Get active clients.
  957. ---
  958. ---@param filter? vim.lsp.get_clients.Filter
  959. ---@return vim.lsp.Client[]: List of |vim.lsp.Client| objects
  960. function lsp.get_clients(filter)
  961. validate('filter', filter, 'table', true)
  962. filter = filter or {}
  963. local clients = {} --- @type vim.lsp.Client[]
  964. local bufnr = filter.bufnr and vim._resolve_bufnr(filter.bufnr)
  965. for _, client in pairs(all_clients) do
  966. if
  967. client
  968. and (filter.id == nil or client.id == filter.id)
  969. and (filter.bufnr == nil or client.attached_buffers[bufnr])
  970. and (filter.name == nil or client.name == filter.name)
  971. and (filter.method == nil or client:supports_method(filter.method, filter.bufnr))
  972. and (filter._uninitialized or client.initialized)
  973. then
  974. clients[#clients + 1] = client
  975. end
  976. end
  977. return clients
  978. end
  979. ---@private
  980. ---@deprecated
  981. function lsp.get_active_clients(filter)
  982. vim.deprecate('vim.lsp.get_active_clients()', 'vim.lsp.get_clients()', '0.12')
  983. return lsp.get_clients(filter)
  984. end
  985. api.nvim_create_autocmd('VimLeavePre', {
  986. desc = 'vim.lsp: exit handler',
  987. callback = function()
  988. local active_clients = lsp.get_clients()
  989. log.info('exit_handler', active_clients)
  990. for _, client in pairs(all_clients) do
  991. client:stop()
  992. end
  993. local timeouts = {} --- @type table<integer,integer>
  994. local max_timeout = 0
  995. local send_kill = false
  996. for client_id, client in pairs(active_clients) do
  997. local timeout = client.flags.exit_timeout
  998. if timeout then
  999. send_kill = true
  1000. timeouts[client_id] = timeout
  1001. max_timeout = math.max(timeout, max_timeout)
  1002. end
  1003. end
  1004. local poll_time = 50
  1005. local function check_clients_closed()
  1006. for client_id, timeout in pairs(timeouts) do
  1007. timeouts[client_id] = timeout - poll_time
  1008. end
  1009. for client_id, _ in pairs(active_clients) do
  1010. if timeouts[client_id] ~= nil and timeouts[client_id] > 0 then
  1011. return false
  1012. end
  1013. end
  1014. return true
  1015. end
  1016. if send_kill then
  1017. if not vim.wait(max_timeout, check_clients_closed, poll_time) then
  1018. for client_id, client in pairs(active_clients) do
  1019. if timeouts[client_id] ~= nil then
  1020. client:stop(true)
  1021. end
  1022. end
  1023. end
  1024. end
  1025. end,
  1026. })
  1027. ---@private
  1028. --- Sends an async request for all active clients attached to the
  1029. --- buffer.
  1030. ---
  1031. ---@param bufnr (integer) Buffer handle, or 0 for current.
  1032. ---@param method (string) LSP method name
  1033. ---@param params? table|(fun(client: vim.lsp.Client, bufnr: integer): table?) Parameters to send to the server
  1034. ---@param handler? lsp.Handler See |lsp-handler|
  1035. --- If nil, follows resolution strategy defined in |lsp-handler-configuration|
  1036. ---@param on_unsupported? fun()
  1037. --- The function to call when the buffer has no clients that support the given method.
  1038. --- Defaults to an `ERROR` level notification.
  1039. ---@return table<integer, integer> client_request_ids Map of client-id:request-id pairs
  1040. ---for all successful requests.
  1041. ---@return function _cancel_all_requests Function which can be used to
  1042. ---cancel all the requests. You could instead
  1043. ---iterate all clients and call their `cancel_request()` methods.
  1044. function lsp.buf_request(bufnr, method, params, handler, on_unsupported)
  1045. validate('bufnr', bufnr, 'number', true)
  1046. validate('method', method, 'string')
  1047. validate('handler', handler, 'function', true)
  1048. validate('on_unsupported', on_unsupported, 'function', true)
  1049. bufnr = vim._resolve_bufnr(bufnr)
  1050. local method_supported = false
  1051. local clients = lsp.get_clients({ bufnr = bufnr })
  1052. local client_request_ids = {} --- @type table<integer,integer>
  1053. for _, client in ipairs(clients) do
  1054. if client:supports_method(method, bufnr) then
  1055. method_supported = true
  1056. local cparams = type(params) == 'function' and params(client, bufnr) or params --[[@as table?]]
  1057. local request_success, request_id = client:request(method, cparams, handler, bufnr)
  1058. -- This could only fail if the client shut down in the time since we looked
  1059. -- it up and we did the request, which should be rare.
  1060. if request_success then
  1061. client_request_ids[client.id] = request_id
  1062. end
  1063. end
  1064. end
  1065. -- if has client but no clients support the given method, notify the user
  1066. if next(clients) and not method_supported then
  1067. if on_unsupported == nil then
  1068. vim.notify(lsp._unsupported_method(method), vim.log.levels.ERROR)
  1069. else
  1070. on_unsupported()
  1071. end
  1072. vim.cmd.redraw()
  1073. return {}, function() end
  1074. end
  1075. local function _cancel_all_requests()
  1076. for client_id, request_id in pairs(client_request_ids) do
  1077. local client = all_clients[client_id]
  1078. client:cancel_request(request_id)
  1079. end
  1080. end
  1081. return client_request_ids, _cancel_all_requests
  1082. end
  1083. --- Sends an async request for all active clients attached to the buffer and executes the `handler`
  1084. --- callback with the combined result.
  1085. ---
  1086. ---@param bufnr (integer) Buffer handle, or 0 for current.
  1087. ---@param method (string) LSP method name
  1088. ---@param params? table|(fun(client: vim.lsp.Client, bufnr: integer): table?) Parameters to send to the server.
  1089. --- Can also be passed as a function that returns the params table for cases where
  1090. --- parameters are specific to the client.
  1091. ---@param handler lsp.MultiHandler (function)
  1092. --- Handler called after all requests are completed. Server results are passed as
  1093. --- a `client_id:result` map.
  1094. ---@return function cancel Function that cancels all requests.
  1095. function lsp.buf_request_all(bufnr, method, params, handler)
  1096. local results = {} --- @type table<integer,{err: lsp.ResponseError?, result: any}>
  1097. local remaining --- @type integer?
  1098. local _, cancel = lsp.buf_request(bufnr, method, params, function(err, result, ctx, config)
  1099. if not remaining then
  1100. -- Calculate as late as possible in case a client is removed during the request
  1101. remaining = #lsp.get_clients({ bufnr = bufnr, method = method })
  1102. end
  1103. -- The error key is deprecated and will be removed in 0.13
  1104. results[ctx.client_id] = { err = err, error = err, result = result }
  1105. remaining = remaining - 1
  1106. if remaining == 0 then
  1107. handler(results, ctx, config)
  1108. end
  1109. end)
  1110. return cancel
  1111. end
  1112. --- Sends a request to all server and waits for the response of all of them.
  1113. ---
  1114. --- Calls |vim.lsp.buf_request_all()| but blocks Nvim while awaiting the result.
  1115. --- Parameters are the same as |vim.lsp.buf_request_all()| but the result is
  1116. --- different. Waits a maximum of {timeout_ms}.
  1117. ---
  1118. ---@param bufnr integer Buffer handle, or 0 for current.
  1119. ---@param method string LSP method name
  1120. ---@param params table? Parameters to send to the server
  1121. ---@param timeout_ms integer? Maximum time in milliseconds to wait for a result.
  1122. --- (default: `1000`)
  1123. ---@return table<integer, {error: lsp.ResponseError?, result: any}>? result Map of client_id:request_result.
  1124. ---@return string? err On timeout, cancel, or error, `err` is a string describing the failure reason, and `result` is nil.
  1125. function lsp.buf_request_sync(bufnr, method, params, timeout_ms)
  1126. local request_results ---@type table
  1127. local cancel = lsp.buf_request_all(bufnr, method, params, function(it)
  1128. request_results = it
  1129. end)
  1130. local wait_result, reason = vim.wait(timeout_ms or 1000, function()
  1131. return request_results ~= nil
  1132. end, 10)
  1133. if not wait_result then
  1134. cancel()
  1135. return nil, wait_result_reason[reason]
  1136. end
  1137. return request_results
  1138. end
  1139. --- Send a notification to a server
  1140. ---@param bufnr (integer|nil) The number of the buffer
  1141. ---@param method (string) Name of the request method
  1142. ---@param params (any) Arguments to send to the server
  1143. ---
  1144. ---@return boolean success true if any client returns true; false otherwise
  1145. function lsp.buf_notify(bufnr, method, params)
  1146. validate('bufnr', bufnr, 'number', true)
  1147. validate('method', method, 'string')
  1148. local resp = false
  1149. for _, client in ipairs(lsp.get_clients({ bufnr = bufnr })) do
  1150. if client.rpc.notify(method, params) then
  1151. resp = true
  1152. end
  1153. end
  1154. return resp
  1155. end
  1156. --- Implements 'omnifunc' compatible LSP completion.
  1157. ---
  1158. ---@see |complete-functions|
  1159. ---@see |complete-items|
  1160. ---@see |CompleteDone|
  1161. ---
  1162. ---@param findstart integer 0 or 1, decides behavior
  1163. ---@param base integer findstart=0, text to match against
  1164. ---
  1165. ---@return integer|table Decided by {findstart}:
  1166. --- - findstart=0: column where the completion starts, or -2 or -3
  1167. --- - findstart=1: list of matches (actually just calls |complete()|)
  1168. function lsp.omnifunc(findstart, base)
  1169. return vim.lsp.completion._omnifunc(findstart, base)
  1170. end
  1171. --- @class vim.lsp.formatexpr.Opts
  1172. --- @inlinedoc
  1173. ---
  1174. --- The timeout period for the formatting request.
  1175. --- (default: 500ms).
  1176. --- @field timeout_ms integer
  1177. --- Provides an interface between the built-in client and a `formatexpr` function.
  1178. ---
  1179. --- Currently only supports a single client. This can be set via
  1180. --- `setlocal formatexpr=v:lua.vim.lsp.formatexpr()` or (more typically) in `on_attach`
  1181. --- via `vim.bo[bufnr].formatexpr = 'v:lua.vim.lsp.formatexpr(#{timeout_ms:250})'`.
  1182. ---
  1183. ---@param opts? vim.lsp.formatexpr.Opts
  1184. function lsp.formatexpr(opts)
  1185. opts = opts or {}
  1186. local timeout_ms = opts.timeout_ms or 500
  1187. if vim.list_contains({ 'i', 'R', 'ic', 'ix' }, vim.fn.mode()) then
  1188. -- `formatexpr` is also called when exceeding `textwidth` in insert mode
  1189. -- fall back to internal formatting
  1190. return 1
  1191. end
  1192. local start_lnum = vim.v.lnum
  1193. local end_lnum = start_lnum + vim.v.count - 1
  1194. if start_lnum <= 0 or end_lnum <= 0 then
  1195. return 0
  1196. end
  1197. local bufnr = api.nvim_get_current_buf()
  1198. for _, client in pairs(lsp.get_clients({ bufnr = bufnr })) do
  1199. if client:supports_method(ms.textDocument_rangeFormatting) then
  1200. local params = util.make_formatting_params()
  1201. local end_line = vim.fn.getline(end_lnum) --[[@as string]]
  1202. local end_col = vim.str_utfindex(end_line, client.offset_encoding)
  1203. --- @cast params +lsp.DocumentRangeFormattingParams
  1204. params.range = {
  1205. start = {
  1206. line = start_lnum - 1,
  1207. character = 0,
  1208. },
  1209. ['end'] = {
  1210. line = end_lnum - 1,
  1211. character = end_col,
  1212. },
  1213. }
  1214. local response =
  1215. client:request_sync(ms.textDocument_rangeFormatting, params, timeout_ms, bufnr)
  1216. if response and response.result then
  1217. lsp.util.apply_text_edits(response.result, bufnr, client.offset_encoding)
  1218. return 0
  1219. end
  1220. end
  1221. end
  1222. -- do not run builtin formatter.
  1223. return 0
  1224. end
  1225. --- Provides an interface between the built-in client and 'tagfunc'.
  1226. ---
  1227. --- When used with normal mode commands (e.g. |CTRL-]|) this will invoke
  1228. --- the "textDocument/definition" LSP method to find the tag under the cursor.
  1229. --- Otherwise, uses "workspace/symbol". If no results are returned from
  1230. --- any LSP servers, falls back to using built-in tags.
  1231. ---
  1232. ---@param pattern string Pattern used to find a workspace symbol
  1233. ---@param flags string See |tag-function|
  1234. ---
  1235. ---@return table[] tags A list of matching tags
  1236. function lsp.tagfunc(pattern, flags)
  1237. return vim.lsp._tagfunc(pattern, flags)
  1238. end
  1239. --- Provides an interface between the built-in client and a `foldexpr` function.
  1240. ---
  1241. --- To use, check for the "textDocument/foldingRange" capability in an
  1242. --- |LspAttach| autocommand. Example:
  1243. ---
  1244. --- ```lua
  1245. --- vim.api.nvim_create_autocommand('LspAttach', {
  1246. --- callback = function(args)
  1247. --- local client = vim.lsp.get_client_by_id(args.data.client_id)
  1248. --- if client:supports_method('textDocument/foldingRange') then
  1249. --- vim.wo.foldmethod = 'expr'
  1250. --- vim.wo.foldexpr = 'v:lua.vim.lsp.foldexpr()'
  1251. --- end
  1252. --- end,
  1253. --- })
  1254. --- ```
  1255. ---
  1256. ---@param lnum integer line number
  1257. function lsp.foldexpr(lnum)
  1258. return vim.lsp._folding_range.foldexpr(lnum)
  1259. end
  1260. --- Close all {kind} of folds in the the window with {winid}.
  1261. ---
  1262. --- To automatically fold imports when opening a file, you can use an autocmd:
  1263. ---
  1264. --- ```lua
  1265. --- vim.api.nvim_create_autocmd('LspNotify', {
  1266. --- callback = function(args)
  1267. --- if args.data.method == 'textDocument/didOpen' then
  1268. --- vim.lsp.foldclose('imports', vim.fn.bufwinid(args.buf))
  1269. --- end
  1270. --- end,
  1271. --- })
  1272. --- ```
  1273. ---
  1274. ---@param kind lsp.FoldingRangeKind Kind to close, one of "comment", "imports" or "region".
  1275. ---@param winid? integer Defaults to the current window.
  1276. function lsp.foldclose(kind, winid)
  1277. return vim.lsp._folding_range.foldclose(kind, winid)
  1278. end
  1279. --- Provides a `foldtext` function that shows the `collapsedText` retrieved,
  1280. --- defaults to the first folded line if `collapsedText` is not provided.
  1281. function lsp.foldtext()
  1282. return vim.lsp._folding_range.foldtext()
  1283. end
  1284. ---Checks whether a client is stopped.
  1285. ---
  1286. ---@param client_id (integer)
  1287. ---@return boolean stopped true if client is stopped, false otherwise.
  1288. function lsp.client_is_stopped(client_id)
  1289. assert(client_id, 'missing client_id param')
  1290. return not all_clients[client_id]
  1291. end
  1292. --- Gets a map of client_id:client pairs for the given buffer, where each value
  1293. --- is a |vim.lsp.Client| object.
  1294. ---
  1295. ---@param bufnr (integer|nil): Buffer handle, or 0 for current
  1296. ---@return table result is table of (client_id, client) pairs
  1297. ---@deprecated Use |vim.lsp.get_clients()| instead.
  1298. function lsp.buf_get_clients(bufnr)
  1299. vim.deprecate('vim.lsp.buf_get_clients()', 'vim.lsp.get_clients()', '0.12')
  1300. local result = {} --- @type table<integer,vim.lsp.Client>
  1301. for _, client in ipairs(lsp.get_clients({ bufnr = vim._resolve_bufnr(bufnr) })) do
  1302. result[client.id] = client
  1303. end
  1304. return result
  1305. end
  1306. --- Log level dictionary with reverse lookup as well.
  1307. ---
  1308. --- Can be used to lookup the number from the name or the
  1309. --- name from the number.
  1310. --- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF"
  1311. --- Level numbers begin with "TRACE" at 0
  1312. --- @nodoc
  1313. lsp.log_levels = log.levels
  1314. --- Sets the global log level for LSP logging.
  1315. ---
  1316. --- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF"
  1317. ---
  1318. --- Level numbers begin with "TRACE" at 0
  1319. ---
  1320. --- Use `lsp.log_levels` for reverse lookup.
  1321. ---
  1322. ---@see |vim.lsp.log_levels|
  1323. ---
  1324. ---@param level (integer|string) the case insensitive level name or number
  1325. function lsp.set_log_level(level)
  1326. if type(level) == 'string' or type(level) == 'number' then
  1327. log.set_level(level)
  1328. else
  1329. error(string.format('Invalid log level: %q', level))
  1330. end
  1331. end
  1332. --- Gets the path of the logfile used by the LSP client.
  1333. ---@return string path to log file
  1334. function lsp.get_log_path()
  1335. return log.get_filename()
  1336. end
  1337. ---@private
  1338. --- Invokes a function for each LSP client attached to a buffer.
  1339. ---
  1340. ---@param bufnr integer Buffer number
  1341. ---@param fn function Function to run on each client attached to buffer
  1342. --- {bufnr}. The function takes the client, client ID, and
  1343. --- buffer number as arguments.
  1344. ---@deprecated use lsp.get_clients({ bufnr = bufnr }) with regular loop
  1345. function lsp.for_each_buffer_client(bufnr, fn)
  1346. vim.deprecate(
  1347. 'vim.lsp.for_each_buffer_client()',
  1348. 'lsp.get_clients({ bufnr = bufnr }) with regular loop',
  1349. '0.12'
  1350. )
  1351. bufnr = vim._resolve_bufnr(bufnr)
  1352. for _, client in pairs(lsp.get_clients({ bufnr = bufnr })) do
  1353. fn(client, client.id, bufnr)
  1354. end
  1355. end
  1356. --- @deprecated
  1357. --- Function to manage overriding defaults for LSP handlers.
  1358. ---@param handler (lsp.Handler) See |lsp-handler|
  1359. ---@param override_config (table) Table containing the keys to override behavior of the {handler}
  1360. function lsp.with(handler, override_config)
  1361. return function(err, result, ctx, config)
  1362. return handler(err, result, ctx, vim.tbl_deep_extend('force', config or {}, override_config))
  1363. end
  1364. end
  1365. --- Registry for client side commands.
  1366. --- This is an extension point for plugins to handle custom commands which are
  1367. --- not part of the core language server protocol specification.
  1368. ---
  1369. --- The registry is a table where the key is a unique command name,
  1370. --- and the value is a function which is called if any LSP action
  1371. --- (code action, code lenses, ...) triggers the command.
  1372. ---
  1373. --- If an LSP response contains a command for which no matching entry is
  1374. --- available in this registry, the command will be executed via the LSP server
  1375. --- using `workspace/executeCommand`.
  1376. ---
  1377. --- The first argument to the function will be the `Command`:
  1378. --- Command
  1379. --- title: String
  1380. --- command: String
  1381. --- arguments?: any[]
  1382. ---
  1383. --- The second argument is the `ctx` of |lsp-handler|
  1384. --- @type table<string,function>
  1385. lsp.commands = setmetatable({}, {
  1386. __newindex = function(tbl, key, value)
  1387. assert(type(key) == 'string', 'The key for commands in `vim.lsp.commands` must be a string')
  1388. assert(type(value) == 'function', 'Command added to `vim.lsp.commands` must be a function')
  1389. rawset(tbl, key, value)
  1390. end,
  1391. })
  1392. return lsp