lsp.lua 51 KB

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