lsp.lua 48 KB

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