lsp.lua 50 KB

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