lsp.lua 41 KB

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