lsp.lua 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888
  1. local if_nil = vim.F.if_nil
  2. local default_handlers = require 'vim.lsp.handlers'
  3. local log = require 'vim.lsp.log'
  4. local lsp_rpc = require 'vim.lsp.rpc'
  5. local protocol = require 'vim.lsp.protocol'
  6. local util = require 'vim.lsp.util'
  7. local sync = require 'vim.lsp.sync'
  8. local vim = vim
  9. local nvim_err_writeln, nvim_buf_get_lines, nvim_command, nvim_buf_get_option
  10. = vim.api.nvim_err_writeln, vim.api.nvim_buf_get_lines, vim.api.nvim_command, vim.api.nvim_buf_get_option
  11. local uv = vim.loop
  12. local tbl_isempty, tbl_extend = vim.tbl_isempty, vim.tbl_extend
  13. local validate = vim.validate
  14. local lsp = {
  15. protocol = protocol;
  16. handlers = default_handlers;
  17. buf = require'vim.lsp.buf';
  18. diagnostic = require'vim.lsp.diagnostic';
  19. codelens = require'vim.lsp.codelens';
  20. util = util;
  21. -- Allow raw RPC access.
  22. rpc = lsp_rpc;
  23. -- Export these directly from rpc.
  24. rpc_response_error = lsp_rpc.rpc_response_error;
  25. }
  26. -- maps request name to the required resolved_capability in the client.
  27. lsp._request_name_to_capability = {
  28. ['textDocument/hover'] = 'hover';
  29. ['textDocument/signatureHelp'] = 'signature_help';
  30. ['textDocument/definition'] = 'goto_definition';
  31. ['textDocument/implementation'] = 'implementation';
  32. ['textDocument/declaration'] = 'declaration';
  33. ['textDocument/typeDefinition'] = 'type_definition';
  34. ['textDocument/documentSymbol'] = 'document_symbol';
  35. ['textDocument/prepareCallHierarchy'] = 'call_hierarchy';
  36. ['textDocument/rename'] = 'rename';
  37. ['textDocument/prepareRename'] = 'rename';
  38. ['textDocument/codeAction'] = 'code_action';
  39. ['textDocument/codeLens'] = 'code_lens';
  40. ['codeLens/resolve'] = 'code_lens_resolve';
  41. ['workspace/executeCommand'] = 'execute_command';
  42. ['workspace/symbol'] = 'workspace_symbol';
  43. ['textDocument/references'] = 'find_references';
  44. ['textDocument/rangeFormatting'] = 'document_range_formatting';
  45. ['textDocument/formatting'] = 'document_formatting';
  46. ['textDocument/completion'] = 'completion';
  47. ['textDocument/documentHighlight'] = 'document_highlight';
  48. }
  49. -- TODO improve handling of scratch buffers with LSP attached.
  50. ---@private
  51. --- Concatenates and writes a list of strings to the Vim error buffer.
  52. ---
  53. ---@param {...} (List of strings) List to write to the buffer
  54. local function err_message(...)
  55. nvim_err_writeln(table.concat(vim.tbl_flatten{...}))
  56. nvim_command("redraw")
  57. end
  58. ---@private
  59. --- Returns the buffer number for the given {bufnr}.
  60. ---
  61. ---@param bufnr (number) Buffer number to resolve. Defaults to the current
  62. ---buffer if not given.
  63. ---@returns bufnr (number) Number of requested buffer
  64. local function resolve_bufnr(bufnr)
  65. validate { bufnr = { bufnr, 'n', true } }
  66. if bufnr == nil or bufnr == 0 then
  67. return vim.api.nvim_get_current_buf()
  68. end
  69. return bufnr
  70. end
  71. ---@private
  72. --- Called by the client when trying to call a method that's not
  73. --- supported in any of the servers registered for the current buffer.
  74. ---@param method (string) name of the method
  75. function lsp._unsupported_method(method)
  76. local msg = string.format("method %s is not supported by any of the servers registered for the current buffer", method)
  77. log.warn(msg)
  78. return msg
  79. end
  80. ---@private
  81. --- Checks whether a given path is a directory.
  82. ---
  83. ---@param filename (string) path to check
  84. ---@returns true if {filename} exists and is a directory, false otherwise
  85. local function is_dir(filename)
  86. validate{filename={filename,'s'}}
  87. local stat = uv.fs_stat(filename)
  88. return stat and stat.type == 'directory' or false
  89. end
  90. local wait_result_reason = { [-1] = "timeout"; [-2] = "interrupted"; [-3] = "error" }
  91. local valid_encodings = {
  92. ["utf-8"] = 'utf-8'; ["utf-16"] = 'utf-16'; ["utf-32"] = 'utf-32';
  93. ["utf8"] = 'utf-8'; ["utf16"] = 'utf-16'; ["utf32"] = 'utf-32';
  94. UTF8 = 'utf-8'; UTF16 = 'utf-16'; UTF32 = 'utf-32';
  95. }
  96. local format_line_ending = {
  97. ["unix"] = '\n',
  98. ["dos"] = '\r\n',
  99. ["mac"] = '\r',
  100. }
  101. ---@private
  102. ---@param bufnr (number)
  103. ---@returns (string)
  104. local function buf_get_line_ending(bufnr)
  105. return format_line_ending[nvim_buf_get_option(bufnr, 'fileformat')] or '\n'
  106. end
  107. local client_index = 0
  108. ---@private
  109. --- Returns a new, unused client id.
  110. ---
  111. ---@returns (number) client id
  112. local function next_client_id()
  113. client_index = client_index + 1
  114. return client_index
  115. end
  116. -- Tracks all clients created via lsp.start_client
  117. local active_clients = {}
  118. local all_buffer_active_clients = {}
  119. local uninitialized_clients = {}
  120. ---@private
  121. local function for_each_buffer_client(bufnr, fn, restrict_client_ids)
  122. validate {
  123. fn = { fn, 'f' };
  124. restrict_client_ids = { restrict_client_ids, 't' , true};
  125. }
  126. bufnr = resolve_bufnr(bufnr)
  127. local client_ids = all_buffer_active_clients[bufnr]
  128. if not client_ids or tbl_isempty(client_ids) then
  129. return
  130. end
  131. if restrict_client_ids and #restrict_client_ids > 0 then
  132. local filtered_client_ids = {}
  133. for client_id in pairs(client_ids) do
  134. if vim.tbl_contains(restrict_client_ids, client_id) then
  135. filtered_client_ids[client_id] = true
  136. end
  137. end
  138. client_ids = filtered_client_ids
  139. end
  140. for client_id in pairs(client_ids) do
  141. local client = active_clients[client_id]
  142. if client then
  143. fn(client, client_id, bufnr)
  144. end
  145. end
  146. end
  147. -- Error codes to be used with `on_error` from |vim.lsp.start_client|.
  148. -- Can be used to look up the string from a the number or the number
  149. -- from the string.
  150. lsp.client_errors = tbl_extend("error", lsp_rpc.client_errors, vim.tbl_add_reverse_lookup {
  151. ON_INIT_CALLBACK_ERROR = table.maxn(lsp_rpc.client_errors) + 1;
  152. })
  153. ---@private
  154. --- Normalizes {encoding} to valid LSP encoding names.
  155. ---
  156. ---@param encoding (string) Encoding to normalize
  157. ---@returns (string) normalized encoding name
  158. local function validate_encoding(encoding)
  159. validate {
  160. encoding = { encoding, 's' };
  161. }
  162. return valid_encodings[encoding:lower()]
  163. or error(string.format("Invalid offset encoding %q. Must be one of: 'utf-8', 'utf-16', 'utf-32'", encoding))
  164. end
  165. ---@internal
  166. --- Parses a command invocation into the command itself and its args. If there
  167. --- are no arguments, an empty table is returned as the second argument.
  168. ---
  169. ---@param input (List)
  170. ---@returns (string) the command
  171. ---@returns (list of strings) its arguments
  172. function lsp._cmd_parts(input)
  173. vim.validate{cmd={
  174. input,
  175. function() return vim.tbl_islist(input) end,
  176. "list"}}
  177. local cmd = input[1]
  178. local cmd_args = {}
  179. -- Don't mutate our input.
  180. for i, v in ipairs(input) do
  181. vim.validate{["cmd argument"]={v, "s"}}
  182. if i > 1 then
  183. table.insert(cmd_args, v)
  184. end
  185. end
  186. return cmd, cmd_args
  187. end
  188. ---@private
  189. --- Augments a validator function with support for optional (nil) values.
  190. ---
  191. ---@param fn (function(v)) The original validator function; should return a
  192. ---bool.
  193. ---@returns (function(v)) The augmented function. Also returns true if {v} is
  194. ---`nil`.
  195. local function optional_validator(fn)
  196. return function(v)
  197. return v == nil or fn(v)
  198. end
  199. end
  200. ---@private
  201. --- Validates a client configuration as given to |vim.lsp.start_client()|.
  202. ---
  203. ---@param config (table)
  204. ---@returns (table) "Cleaned" config, containing only the command, its
  205. ---arguments, and a valid encoding.
  206. ---
  207. ---@see |vim.lsp.start_client()|
  208. local function validate_client_config(config)
  209. validate {
  210. config = { config, 't' };
  211. }
  212. validate {
  213. handlers = { config.handlers, "t", true };
  214. capabilities = { config.capabilities, "t", true };
  215. cmd_cwd = { config.cmd_cwd, optional_validator(is_dir), "directory" };
  216. cmd_env = { config.cmd_env, "t", true };
  217. name = { config.name, 's', true };
  218. on_error = { config.on_error, "f", true };
  219. on_exit = { config.on_exit, "f", true };
  220. on_init = { config.on_init, "f", true };
  221. settings = { config.settings, "t", true };
  222. commands = { config.commands, 't', true };
  223. before_init = { config.before_init, "f", true };
  224. offset_encoding = { config.offset_encoding, "s", true };
  225. flags = { config.flags, "t", true };
  226. get_language_id = { config.get_language_id, "f", true };
  227. }
  228. assert(
  229. (not config.flags
  230. or not config.flags.debounce_text_changes
  231. or type(config.flags.debounce_text_changes) == 'number'),
  232. "flags.debounce_text_changes must be a number with the debounce time in milliseconds"
  233. )
  234. local cmd, cmd_args = lsp._cmd_parts(config.cmd)
  235. local offset_encoding = valid_encodings.UTF16
  236. if config.offset_encoding then
  237. offset_encoding = validate_encoding(config.offset_encoding)
  238. end
  239. return {
  240. cmd = cmd;
  241. cmd_args = cmd_args;
  242. offset_encoding = offset_encoding;
  243. }
  244. end
  245. ---@private
  246. --- Returns full text of buffer {bufnr} as a string.
  247. ---
  248. ---@param bufnr (number) Buffer handle, or 0 for current.
  249. ---@returns Buffer text as string.
  250. local function buf_get_full_text(bufnr)
  251. local line_ending = buf_get_line_ending(bufnr)
  252. local text = table.concat(nvim_buf_get_lines(bufnr, 0, -1, true), line_ending)
  253. if nvim_buf_get_option(bufnr, 'eol') then
  254. text = text .. line_ending
  255. end
  256. return text
  257. end
  258. ---@private
  259. --- Memoizes a function. On first run, the function return value is saved and
  260. --- immediately returned on subsequent runs. If the function returns a multival,
  261. --- only the first returned value will be memoized and returned. The function will only be run once,
  262. --- even if it has side effects.
  263. ---
  264. ---@param fn (function) Function to run
  265. ---@returns (function) Memoized function
  266. local function once(fn)
  267. local value
  268. local ran = false
  269. return function(...)
  270. if not ran then
  271. value = fn(...)
  272. ran = true
  273. end
  274. return value
  275. end
  276. end
  277. local changetracking = {}
  278. do
  279. --@private
  280. --- client_id → state
  281. ---
  282. --- state
  283. --- use_incremental_sync: bool
  284. --- buffers: bufnr -> buffer_state
  285. ---
  286. --- buffer_state
  287. --- pending_change?: function that the timer starts to trigger didChange
  288. --- pending_changes: table (uri -> list of pending changeset tables));
  289. --- Only set if incremental_sync is used
  290. ---
  291. --- timer?: uv_timer
  292. --- lines: table
  293. local state_by_client = {}
  294. ---@private
  295. function changetracking.init(client, bufnr)
  296. local use_incremental_sync = (
  297. if_nil(client.config.flags.allow_incremental_sync, true)
  298. and client.resolved_capabilities.text_document_did_change == protocol.TextDocumentSyncKind.Incremental
  299. )
  300. local state = state_by_client[client.id]
  301. if not state then
  302. state = {
  303. buffers = {};
  304. debounce = client.config.flags.debounce_text_changes or 150,
  305. use_incremental_sync = use_incremental_sync;
  306. }
  307. state_by_client[client.id] = state
  308. end
  309. if not state.buffers[bufnr] then
  310. local buf_state = {}
  311. state.buffers[bufnr] = buf_state
  312. if use_incremental_sync then
  313. buf_state.lines = nvim_buf_get_lines(bufnr, 0, -1, true)
  314. buf_state.lines_tmp = {}
  315. buf_state.pending_changes = {}
  316. end
  317. end
  318. end
  319. ---@private
  320. function changetracking.reset_buf(client, bufnr)
  321. changetracking.flush(client, bufnr)
  322. local state = state_by_client[client.id]
  323. if state and state.buffers then
  324. local buf_state = state.buffers[bufnr]
  325. state.buffers[bufnr] = nil
  326. if buf_state and buf_state.timer then
  327. buf_state.timer:stop()
  328. buf_state.timer:close()
  329. buf_state.timer = nil
  330. end
  331. end
  332. end
  333. ---@private
  334. function changetracking.reset(client_id)
  335. local state = state_by_client[client_id]
  336. if not state then
  337. return
  338. end
  339. for _, buf_state in pairs(state.buffers) do
  340. if buf_state.timer then
  341. buf_state.timer:stop()
  342. buf_state.timer:close()
  343. buf_state.timer = nil
  344. end
  345. end
  346. state.buffers = {}
  347. end
  348. ---@private
  349. --
  350. -- Adjust debounce time by taking time of last didChange notification into
  351. -- consideration. If the last didChange happened more than `debounce` time ago,
  352. -- debounce can be skipped and otherwise maybe reduced.
  353. --
  354. -- This turns the debounce into a kind of client rate limiting
  355. local function next_debounce(debounce, buf_state)
  356. if debounce == 0 then
  357. return 0
  358. end
  359. local ns_to_ms = 0.000001
  360. if not buf_state.last_flush then
  361. return debounce
  362. end
  363. local now = uv.hrtime()
  364. local ms_since_last_flush = (now - buf_state.last_flush) * ns_to_ms
  365. return math.max(debounce - ms_since_last_flush, 0)
  366. end
  367. ---@private
  368. function changetracking.prepare(bufnr, firstline, lastline, new_lastline)
  369. local incremental_changes = function(client, buf_state)
  370. local prev_lines = buf_state.lines
  371. local curr_lines = buf_state.lines_tmp
  372. local changed_lines = nvim_buf_get_lines(bufnr, firstline, new_lastline, true)
  373. for i = 1, firstline do
  374. curr_lines[i] = prev_lines[i]
  375. end
  376. for i = firstline + 1, new_lastline do
  377. curr_lines[i] = changed_lines[i - firstline]
  378. end
  379. for i = lastline + 1, #prev_lines do
  380. curr_lines[i - lastline + new_lastline] = prev_lines[i]
  381. end
  382. if tbl_isempty(curr_lines) then
  383. -- Can happen when deleting the entire contents of a buffer, see https://github.com/neovim/neovim/issues/16259.
  384. curr_lines[1] = ''
  385. end
  386. local line_ending = buf_get_line_ending(bufnr)
  387. local incremental_change = sync.compute_diff(
  388. buf_state.lines, curr_lines, firstline, lastline, new_lastline, client.offset_encoding or 'utf-16', line_ending)
  389. -- Double-buffering of lines tables is used to reduce the load on the garbage collector.
  390. -- At this point the prev_lines table is useless, but its internal storage has already been allocated,
  391. -- so let's keep it around for the next didChange event, in which it will become the next
  392. -- curr_lines table. Note that setting elements to nil doesn't actually deallocate slots in the
  393. -- internal storage - it merely marks them as free, for the GC to deallocate them.
  394. for i in ipairs(prev_lines) do
  395. prev_lines[i] = nil
  396. end
  397. buf_state.lines = curr_lines
  398. buf_state.lines_tmp = prev_lines
  399. return incremental_change
  400. end
  401. local full_changes = once(function()
  402. return {
  403. text = buf_get_full_text(bufnr);
  404. };
  405. end)
  406. local uri = vim.uri_from_bufnr(bufnr)
  407. return function(client)
  408. if client.resolved_capabilities.text_document_did_change == protocol.TextDocumentSyncKind.None then
  409. return
  410. end
  411. local state = state_by_client[client.id]
  412. local buf_state = state.buffers[bufnr]
  413. changetracking._reset_timer(buf_state)
  414. local debounce = next_debounce(state.debounce, buf_state)
  415. if state.use_incremental_sync then
  416. -- This must be done immediately and cannot be delayed
  417. -- The contents would further change and startline/endline may no longer fit
  418. table.insert(buf_state.pending_changes, incremental_changes(client, buf_state))
  419. end
  420. buf_state.pending_change = function()
  421. buf_state.pending_change = nil
  422. buf_state.last_flush = uv.hrtime()
  423. if client.is_stopped() or not vim.api.nvim_buf_is_valid(bufnr) then
  424. return
  425. end
  426. local changes = state.use_incremental_sync and buf_state.pending_changes or { full_changes() }
  427. client.notify("textDocument/didChange", {
  428. textDocument = {
  429. uri = uri,
  430. version = util.buf_versions[bufnr],
  431. },
  432. contentChanges = changes,
  433. })
  434. buf_state.pending_changes = {}
  435. end
  436. if debounce == 0 then
  437. buf_state.pending_change()
  438. else
  439. local timer = vim.loop.new_timer()
  440. buf_state.timer = timer
  441. -- Must use schedule_wrap because `full_changes()` calls nvim_buf_get_lines
  442. timer:start(debounce, 0, vim.schedule_wrap(buf_state.pending_change))
  443. end
  444. end
  445. end
  446. function changetracking._reset_timer(buf_state)
  447. if buf_state.timer then
  448. buf_state.timer:stop()
  449. buf_state.timer:close()
  450. buf_state.timer = nil
  451. end
  452. end
  453. --- Flushes any outstanding change notification.
  454. ---@private
  455. function changetracking.flush(client, bufnr)
  456. local state = state_by_client[client.id]
  457. if not state then
  458. return
  459. end
  460. if bufnr then
  461. local buf_state = state.buffers[bufnr] or {}
  462. changetracking._reset_timer(buf_state)
  463. if buf_state.pending_change then
  464. buf_state.pending_change()
  465. end
  466. else
  467. for _, buf_state in pairs(state.buffers) do
  468. changetracking._reset_timer(buf_state)
  469. if buf_state.pending_change then
  470. buf_state.pending_change()
  471. end
  472. end
  473. end
  474. end
  475. end
  476. ---@private
  477. --- Default handler for the 'textDocument/didOpen' LSP notification.
  478. ---
  479. ---@param bufnr (Number) Number of the buffer, or 0 for current
  480. ---@param client Client object
  481. local function text_document_did_open_handler(bufnr, client)
  482. changetracking.init(client, bufnr)
  483. if not client.resolved_capabilities.text_document_open_close then
  484. return
  485. end
  486. if not vim.api.nvim_buf_is_loaded(bufnr) then
  487. return
  488. end
  489. local filetype = nvim_buf_get_option(bufnr, 'filetype')
  490. local params = {
  491. textDocument = {
  492. version = 0;
  493. uri = vim.uri_from_bufnr(bufnr);
  494. languageId = client.config.get_language_id(bufnr, filetype);
  495. text = buf_get_full_text(bufnr);
  496. }
  497. }
  498. client.notify('textDocument/didOpen', params)
  499. util.buf_versions[bufnr] = params.textDocument.version
  500. -- Next chance we get, we should re-do the diagnostics
  501. vim.schedule(function()
  502. -- Protect against a race where the buffer disappears
  503. -- between `did_open_handler` and the scheduled function firing.
  504. if vim.api.nvim_buf_is_valid(bufnr) then
  505. local namespace = vim.lsp.diagnostic.get_namespace(client.id)
  506. vim.diagnostic.show(namespace, bufnr)
  507. end
  508. end)
  509. end
  510. -- FIXME: DOC: Shouldn't need to use a dummy function
  511. --
  512. --- LSP client object. You can get an active client object via
  513. --- |vim.lsp.get_client_by_id()| or |vim.lsp.get_active_clients()|.
  514. ---
  515. --- - Methods:
  516. ---
  517. --- - request(method, params, [handler], bufnr)
  518. --- Sends a request to the server.
  519. --- This is a thin wrapper around {client.rpc.request} with some additional
  520. --- checking.
  521. --- If {handler} is not specified, If one is not found there, then an error will occur.
  522. --- Returns: {status}, {[client_id]}. {status} is a boolean indicating if
  523. --- the notification was successful. If it is `false`, then it will always
  524. --- be `false` (the client has shutdown).
  525. --- If {status} is `true`, the function returns {request_id} as the second
  526. --- result. You can use this with `client.cancel_request(request_id)`
  527. --- to cancel the request.
  528. ---
  529. --- - request_sync(method, params, timeout_ms, bufnr)
  530. --- Sends a request to the server and synchronously waits for the response.
  531. --- This is a wrapper around {client.request}
  532. --- Returns: { err=err, result=result }, a dictionary, where `err` and `result` come from
  533. --- the |lsp-handler|. On timeout, cancel or error, returns `(nil, err)` where `err` is a
  534. --- string describing the failure reason. If the request was unsuccessful returns `nil`.
  535. ---
  536. --- - notify(method, params)
  537. --- Sends a notification to an LSP server.
  538. --- Returns: a boolean to indicate if the notification was successful. If
  539. --- it is false, then it will always be false (the client has shutdown).
  540. ---
  541. --- - cancel_request(id)
  542. --- Cancels a request with a given request id.
  543. --- Returns: same as `notify()`.
  544. ---
  545. --- - stop([force])
  546. --- Stops a client, optionally with force.
  547. --- By default, it will just ask the server to shutdown without force.
  548. --- If you request to stop a client which has previously been requested to
  549. --- shutdown, it will automatically escalate and force shutdown.
  550. ---
  551. --- - is_stopped()
  552. --- Checks whether a client is stopped.
  553. --- Returns: true if the client is fully stopped.
  554. ---
  555. --- - on_attach(client, bufnr)
  556. --- Runs the on_attach function from the client's config if it was defined.
  557. --- Useful for buffer-local setup.
  558. ---
  559. --- - Members
  560. --- - {id} (number): The id allocated to the client.
  561. ---
  562. --- - {name} (string): If a name is specified on creation, that will be
  563. --- used. Otherwise it is just the client id. This is used for
  564. --- logs and messages.
  565. ---
  566. --- - {rpc} (table): RPC client object, for low level interaction with the
  567. --- client. See |vim.lsp.rpc.start()|.
  568. ---
  569. --- - {offset_encoding} (string): The encoding used for communicating
  570. --- with the server. You can modify this in the `config`'s `on_init` method
  571. --- before text is sent to the server.
  572. ---
  573. --- - {handlers} (table): The handlers used by the client as described in |lsp-handler|.
  574. ---
  575. --- - {requests} (table): The current pending requests in flight
  576. --- to the server. Entries are key-value pairs with the key
  577. --- being the request ID while the value is a table with `type`,
  578. --- `bufnr`, and `method` key-value pairs. `type` is either "pending"
  579. --- for an active request, or "cancel" for a cancel request.
  580. ---
  581. --- - {config} (table): copy of the table that was passed by the user
  582. --- to |vim.lsp.start_client()|.
  583. ---
  584. --- - {server_capabilities} (table): Response from the server sent on
  585. --- `initialize` describing the server's capabilities.
  586. ---
  587. --- - {resolved_capabilities} (table): Normalized table of
  588. --- capabilities that we have detected based on the initialize
  589. --- response from the server in `server_capabilities`.
  590. function lsp.client()
  591. error()
  592. end
  593. -- FIXME: DOC: Currently all methods on the `vim.lsp.client` object are
  594. -- documented twice: Here, and on the methods themselves (e.g.
  595. -- `client.request()`). This is a workaround for the vimdoc generator script
  596. -- not handling method names correctly. If you change the documentation on
  597. -- either, please make sure to update the other as well.
  598. --
  599. --- Starts and initializes a client with the given configuration.
  600. ---
  601. --- Parameter `cmd` is required.
  602. ---
  603. --- The following parameters describe fields in the {config} table.
  604. ---
  605. ---
  606. ---@param cmd: (required, string or list treated like |jobstart()|) Base command
  607. --- that initiates the LSP client.
  608. ---
  609. ---@param cmd_cwd: (string, default=|getcwd()|) Directory to launch
  610. --- the `cmd` process. Not related to `root_dir`.
  611. ---
  612. ---@param cmd_env: (table) Environment flags to pass to the LSP on
  613. --- spawn. Can be specified using keys like a map or as a list with `k=v`
  614. --- pairs or both. Non-string values are coerced to string.
  615. --- Example:
  616. --- <pre>
  617. --- { "PRODUCTION=true"; "TEST=123"; PORT = 8080; HOST = "0.0.0.0"; }
  618. --- </pre>
  619. ---
  620. ---@param workspace_folders (table) List of workspace folders passed to the
  621. --- language server. For backwards compatibility rootUri and rootPath will be
  622. --- derived from the first workspace folder in this list. See `workspaceFolders` in
  623. --- the LSP spec.
  624. ---
  625. ---@param capabilities Map overriding the default capabilities defined by
  626. --- |vim.lsp.protocol.make_client_capabilities()|, passed to the language
  627. --- server on initialization. Hint: use make_client_capabilities() and modify
  628. --- its result.
  629. --- - Note: To send an empty dictionary use
  630. --- `{[vim.type_idx]=vim.types.dictionary}`, else it will be encoded as an
  631. --- array.
  632. ---
  633. ---@param handlers Map of language server method names to |lsp-handler|
  634. ---
  635. ---@param settings Map with language server specific settings. These are
  636. --- returned to the language server if requested via `workspace/configuration`.
  637. --- Keys are case-sensitive.
  638. ---
  639. ---@param commands table Table that maps string of clientside commands to user-defined functions.
  640. --- Commands passed to start_client take precedence over the global command registry. Each key
  641. --- must be a unique command name, and the value is a function which is called if any LSP action
  642. --- (code action, code lenses, ...) triggers the command.
  643. ---
  644. ---@param init_options Values to pass in the initialization request
  645. --- as `initializationOptions`. See `initialize` in the LSP spec.
  646. ---
  647. ---@param name (string, default=client-id) Name in log messages.
  648. ---
  649. ---@param get_language_id function(bufnr, filetype) -> language ID as string.
  650. --- Defaults to the filetype.
  651. ---
  652. ---@param offset_encoding (default="utf-16") One of "utf-8", "utf-16",
  653. --- or "utf-32" which is the encoding that the LSP server expects. Client does
  654. --- not verify this is correct.
  655. ---
  656. ---@param on_error Callback with parameters (code, ...), invoked
  657. --- when the client operation throws an error. `code` is a number describing
  658. --- the error. Other arguments may be passed depending on the error kind. See
  659. --- |vim.lsp.rpc.client_errors| for possible errors.
  660. --- Use `vim.lsp.rpc.client_errors[code]` to get human-friendly name.
  661. ---
  662. ---@param before_init Callback with parameters (initialize_params, config)
  663. --- invoked before the LSP "initialize" phase, where `params` contains the
  664. --- parameters being sent to the server and `config` is the config that was
  665. --- passed to |vim.lsp.start_client()|. You can use this to modify parameters before
  666. --- they are sent.
  667. ---
  668. ---@param on_init Callback (client, initialize_result) invoked after LSP
  669. --- "initialize", where `result` is a table of `capabilities` and anything else
  670. --- the server may send. For example, clangd sends
  671. --- `initialize_result.offsetEncoding` if `capabilities.offsetEncoding` was
  672. --- sent to it. You can only modify the `client.offset_encoding` here before
  673. --- any notifications are sent. Most language servers expect to be sent client specified settings after
  674. --- initialization. Neovim does not make this assumption. A
  675. --- `workspace/didChangeConfiguration` notification should be sent
  676. --- to the server during on_init.
  677. ---
  678. ---@param on_exit Callback (code, signal, client_id) invoked on client
  679. --- exit.
  680. --- - code: exit code of the process
  681. --- - signal: number describing the signal used to terminate (if any)
  682. --- - client_id: client handle
  683. ---
  684. ---@param on_attach Callback (client, bufnr) invoked when client
  685. --- attaches to a buffer.
  686. ---
  687. ---@param trace: "off" | "messages" | "verbose" | nil passed directly to the language
  688. --- server in the initialize request. Invalid/empty values will default to "off"
  689. ---@param flags: A table with flags for the client. The current (experimental) flags are:
  690. --- - allow_incremental_sync (bool, default true): Allow using incremental sync for buffer edits
  691. --- - debounce_text_changes (number, default nil): Debounce didChange
  692. --- notifications to the server by the given number in milliseconds. No debounce
  693. --- occurs if nil
  694. --- - exit_timeout (number, default 500): Milliseconds to wait for server to
  695. --- exit cleanly after sending the 'shutdown' request before sending kill -15.
  696. --- If set to false, nvim exits immediately after sending the 'shutdown' request to the server.
  697. ---
  698. ---@param root_dir string Directory where the LSP
  699. --- server will base its workspaceFolders, rootUri, and rootPath
  700. --- on initialization.
  701. ---
  702. ---@returns Client id. |vim.lsp.get_client_by_id()| Note: client may not be
  703. --- fully initialized. Use `on_init` to do any actions once
  704. --- the client has been initialized.
  705. function lsp.start_client(config)
  706. local cleaned_config = validate_client_config(config)
  707. local cmd, cmd_args, offset_encoding = cleaned_config.cmd, cleaned_config.cmd_args, cleaned_config.offset_encoding
  708. config.flags = config.flags or {}
  709. config.settings = config.settings or {}
  710. -- By default, get_language_id just returns the exact filetype it is passed.
  711. -- It is possible to pass in something that will calculate a different filetype,
  712. -- to be sent by the client.
  713. config.get_language_id = config.get_language_id or function(_, filetype) return filetype end
  714. local client_id = next_client_id()
  715. local handlers = config.handlers or {}
  716. local name = config.name or tostring(client_id)
  717. local log_prefix = string.format("LSP[%s]", name)
  718. local dispatch = {}
  719. ---@private
  720. --- Returns the handler associated with an LSP method.
  721. --- Returns the default handler if the user hasn't set a custom one.
  722. ---
  723. ---@param method (string) LSP method name
  724. ---@returns (fn) The handler for the given method, if defined, or the default from |vim.lsp.handlers|
  725. local function resolve_handler(method)
  726. return handlers[method] or default_handlers[method]
  727. end
  728. ---@private
  729. --- Handles a notification sent by an LSP server by invoking the
  730. --- corresponding handler.
  731. ---
  732. ---@param method (string) LSP method name
  733. ---@param params (table) The parameters for that method.
  734. function dispatch.notification(method, params)
  735. local _ = log.trace() and log.trace('notification', method, params)
  736. local handler = resolve_handler(method)
  737. if handler then
  738. -- Method name is provided here for convenience.
  739. handler(nil, params, {method=method, client_id=client_id})
  740. end
  741. end
  742. ---@private
  743. --- Handles a request from an LSP server by invoking the corresponding handler.
  744. ---
  745. ---@param method (string) LSP method name
  746. ---@param params (table) The parameters for that method
  747. function dispatch.server_request(method, params)
  748. local _ = log.trace() and log.trace('server_request', method, params)
  749. local handler = resolve_handler(method)
  750. if handler then
  751. local _ = log.trace() and log.trace("server_request: found handler for", method)
  752. return handler(nil, params, {method=method, client_id=client_id})
  753. end
  754. local _ = log.warn() and log.warn("server_request: no handler found for", method)
  755. return nil, lsp.rpc_response_error(protocol.ErrorCodes.MethodNotFound)
  756. end
  757. ---@private
  758. --- Invoked when the client operation throws an error.
  759. ---
  760. ---@param code (number) Error code
  761. ---@param err (...) Other arguments may be passed depending on the error kind
  762. ---@see |vim.lsp.rpc.client_errors| for possible errors. Use
  763. ---`vim.lsp.rpc.client_errors[code]` to get a human-friendly name.
  764. function dispatch.on_error(code, err)
  765. local _ = log.error() and log.error(log_prefix, "on_error", { code = lsp.client_errors[code], err = err })
  766. err_message(log_prefix, ': Error ', lsp.client_errors[code], ': ', vim.inspect(err))
  767. if config.on_error then
  768. local status, usererr = pcall(config.on_error, code, err)
  769. if not status then
  770. local _ = log.error() and log.error(log_prefix, "user on_error failed", { err = usererr })
  771. err_message(log_prefix, ' user on_error failed: ', tostring(usererr))
  772. end
  773. end
  774. end
  775. ---@private
  776. --- Invoked on client exit.
  777. ---
  778. ---@param code (number) exit code of the process
  779. ---@param signal (number) the signal used to terminate (if any)
  780. function dispatch.on_exit(code, signal)
  781. if config.on_exit then
  782. pcall(config.on_exit, code, signal, client_id)
  783. end
  784. active_clients[client_id] = nil
  785. uninitialized_clients[client_id] = nil
  786. lsp.diagnostic.reset(client_id, all_buffer_active_clients)
  787. changetracking.reset(client_id)
  788. for _, client_ids in pairs(all_buffer_active_clients) do
  789. client_ids[client_id] = nil
  790. end
  791. if code ~= 0 or (signal ~= 0 and signal ~= 15) then
  792. local msg = string.format("Client %s quit with exit code %s and signal %s", client_id, code, signal)
  793. vim.schedule(function()
  794. vim.notify(msg, vim.log.levels.WARN)
  795. end)
  796. end
  797. end
  798. -- Start the RPC client.
  799. local rpc = lsp_rpc.start(cmd, cmd_args, dispatch, {
  800. cwd = config.cmd_cwd;
  801. env = config.cmd_env;
  802. })
  803. -- Return nil if client fails to start
  804. if not rpc then return end
  805. local client = {
  806. id = client_id;
  807. name = name;
  808. rpc = rpc;
  809. offset_encoding = offset_encoding;
  810. config = config;
  811. attached_buffers = {};
  812. handlers = handlers;
  813. commands = config.commands or {};
  814. requests = {};
  815. -- for $/progress report
  816. messages = { name = name, messages = {}, progress = {}, status = {} };
  817. }
  818. -- Store the uninitialized_clients for cleanup in case we exit before initialize finishes.
  819. uninitialized_clients[client_id] = client;
  820. ---@private
  821. local function initialize()
  822. local valid_traces = {
  823. off = 'off'; messages = 'messages'; verbose = 'verbose';
  824. }
  825. local version = vim.version()
  826. local workspace_folders
  827. local root_uri
  828. local root_path
  829. if config.workspace_folders or config.root_dir then
  830. if config.root_dir and not config.workspace_folders then
  831. workspace_folders = {{
  832. uri = vim.uri_from_fname(config.root_dir);
  833. name = string.format("%s", config.root_dir);
  834. }};
  835. else
  836. workspace_folders = config.workspace_folders
  837. end
  838. root_uri = workspace_folders[1].uri
  839. root_path = vim.uri_to_fname(root_uri)
  840. else
  841. workspace_folders = nil
  842. root_uri = nil
  843. root_path = nil
  844. end
  845. local initialize_params = {
  846. -- The process Id of the parent process that started the server. Is null if
  847. -- the process has not been started by another process. If the parent
  848. -- process is not alive then the server should exit (see exit notification)
  849. -- its process.
  850. processId = uv.getpid();
  851. -- Information about the client
  852. -- since 3.15.0
  853. clientInfo = {
  854. name = "Neovim",
  855. version = string.format("%s.%s.%s", version.major, version.minor, version.patch)
  856. };
  857. -- The rootPath of the workspace. Is null if no folder is open.
  858. --
  859. -- @deprecated in favour of rootUri.
  860. rootPath = root_path or vim.NIL;
  861. -- The rootUri of the workspace. Is null if no folder is open. If both
  862. -- `rootPath` and `rootUri` are set `rootUri` wins.
  863. rootUri = root_uri or vim.NIL;
  864. -- The workspace folders configured in the client when the server starts.
  865. -- This property is only available if the client supports workspace folders.
  866. -- It can be `null` if the client supports workspace folders but none are
  867. -- configured.
  868. workspaceFolders = workspace_folders or vim.NIL;
  869. -- User provided initialization options.
  870. initializationOptions = config.init_options;
  871. -- The capabilities provided by the client (editor or tool)
  872. capabilities = config.capabilities or protocol.make_client_capabilities();
  873. -- The initial trace setting. If omitted trace is disabled ("off").
  874. -- trace = "off" | "messages" | "verbose";
  875. trace = valid_traces[config.trace] or 'off';
  876. }
  877. if config.before_init then
  878. -- TODO(ashkan) handle errors here.
  879. pcall(config.before_init, initialize_params, config)
  880. end
  881. local _ = log.trace() and log.trace(log_prefix, "initialize_params", initialize_params)
  882. rpc.request('initialize', initialize_params, function(init_err, result)
  883. assert(not init_err, tostring(init_err))
  884. assert(result, "server sent empty result")
  885. rpc.notify('initialized', vim.empty_dict())
  886. client.initialized = true
  887. uninitialized_clients[client_id] = nil
  888. client.workspace_folders = workspace_folders
  889. -- TODO(mjlbach): Backwards compatibility, to be removed in 0.7
  890. client.workspaceFolders = client.workspace_folders
  891. client.server_capabilities = assert(result.capabilities, "initialize result doesn't contain capabilities")
  892. -- These are the cleaned up capabilities we use for dynamically deciding
  893. -- when to send certain events to clients.
  894. client.resolved_capabilities = protocol.resolve_capabilities(client.server_capabilities)
  895. client.supports_method = function(method)
  896. local required_capability = lsp._request_name_to_capability[method]
  897. -- if we don't know about the method, assume that the client supports it.
  898. if not required_capability then
  899. return true
  900. end
  901. return client.resolved_capabilities[required_capability]
  902. end
  903. if config.on_init then
  904. local status, err = pcall(config.on_init, client, result)
  905. if not status then
  906. pcall(handlers.on_error, lsp.client_errors.ON_INIT_CALLBACK_ERROR, err)
  907. end
  908. end
  909. local _ = log.debug() and log.debug(log_prefix, "server_capabilities", client.server_capabilities)
  910. local _ = log.info() and log.info(log_prefix, "initialized", { resolved_capabilities = client.resolved_capabilities })
  911. -- Only assign after initialized.
  912. active_clients[client_id] = client
  913. -- If we had been registered before we start, then send didOpen This can
  914. -- happen if we attach to buffers before initialize finishes or if
  915. -- someone restarts a client.
  916. for bufnr, client_ids in pairs(all_buffer_active_clients) do
  917. if client_ids[client_id] then
  918. client._on_attach(bufnr)
  919. end
  920. end
  921. end)
  922. end
  923. ---@private
  924. --- Sends a request to the server.
  925. ---
  926. --- This is a thin wrapper around {client.rpc.request} with some additional
  927. --- checks for capabilities and handler availability.
  928. ---
  929. ---@param method (string) LSP method name.
  930. ---@param params (table) LSP request params.
  931. ---@param handler (function, optional) Response |lsp-handler| for this method.
  932. ---@param bufnr (number) Buffer handle (0 for current).
  933. ---@returns ({status}, [request_id]): {status} is a bool indicating
  934. ---whether the request was successful. If it is `false`, then it will
  935. ---always be `false` (the client has shutdown). If it was
  936. ---successful, then it will return {request_id} as the
  937. ---second result. You can use this with `client.cancel_request(request_id)`
  938. ---to cancel the-request.
  939. ---@see |vim.lsp.buf_request()|
  940. function client.request(method, params, handler, bufnr)
  941. if not handler then
  942. handler = resolve_handler(method)
  943. or error(string.format("not found: %q request handler for client %q.", method, client.name))
  944. end
  945. -- Ensure pending didChange notifications are sent so that the server doesn't operate on a stale state
  946. changetracking.flush(client, bufnr)
  947. bufnr = resolve_bufnr(bufnr)
  948. local _ = log.debug() and log.debug(log_prefix, "client.request", client_id, method, params, handler, bufnr)
  949. local success, request_id = rpc.request(method, params, function(err, result)
  950. handler(err, result, {method=method, client_id=client_id, bufnr=bufnr, params=params})
  951. end, function(request_id)
  952. client.requests[request_id] = nil
  953. nvim_command("doautocmd <nomodeline> User LspRequest")
  954. end)
  955. if success then
  956. client.requests[request_id] = { type='pending', bufnr=bufnr, method=method }
  957. nvim_command("doautocmd <nomodeline> User LspRequest")
  958. end
  959. return success, request_id
  960. end
  961. ---@private
  962. --- Sends a request to the server and synchronously waits for the response.
  963. ---
  964. --- This is a wrapper around {client.request}
  965. ---
  966. ---@param method (string) LSP method name.
  967. ---@param params (table) LSP request params.
  968. ---@param timeout_ms (number, optional, default=1000) Maximum time in
  969. ---milliseconds to wait for a result.
  970. ---@param bufnr (number) Buffer handle (0 for current).
  971. ---@returns { err=err, result=result }, a dictionary, where `err` and `result` come from the |lsp-handler|.
  972. ---On timeout, cancel or error, returns `(nil, err)` where `err` is a
  973. ---string describing the failure reason. If the request was unsuccessful
  974. ---returns `nil`.
  975. ---@see |vim.lsp.buf_request_sync()|
  976. function client.request_sync(method, params, timeout_ms, bufnr)
  977. local request_result = nil
  978. local function _sync_handler(err, result)
  979. request_result = { err = err, result = result }
  980. end
  981. local success, request_id = client.request(method, params, _sync_handler,
  982. bufnr)
  983. if not success then return nil end
  984. local wait_result, reason = vim.wait(timeout_ms or 1000, function()
  985. return request_result ~= nil
  986. end, 10)
  987. if not wait_result then
  988. client.cancel_request(request_id)
  989. return nil, wait_result_reason[reason]
  990. end
  991. return request_result
  992. end
  993. ---@private
  994. --- Sends a notification to an LSP server.
  995. ---
  996. ---@param method string LSP method name.
  997. ---@param params table|nil LSP request params.
  998. ---@returns {status} (bool) true if the notification was successful.
  999. ---If it is false, then it will always be false
  1000. ---(the client has shutdown).
  1001. function client.notify(method, params)
  1002. if method ~= 'textDocument/didChange' then
  1003. changetracking.flush(client)
  1004. end
  1005. return rpc.notify(method, params)
  1006. end
  1007. ---@private
  1008. --- Cancels a request with a given request id.
  1009. ---
  1010. ---@param id (number) id of request to cancel
  1011. ---@returns true if any client returns true; false otherwise
  1012. ---@see |vim.lsp.client.notify()|
  1013. function client.cancel_request(id)
  1014. validate{id = {id, 'n'}}
  1015. local request = client.requests[id]
  1016. if request and request.type == 'pending' then
  1017. request.type = 'cancel'
  1018. nvim_command("doautocmd <nomodeline> User LspRequest")
  1019. end
  1020. return rpc.notify("$/cancelRequest", { id = id })
  1021. end
  1022. -- Track this so that we can escalate automatically if we've already tried a
  1023. -- graceful shutdown
  1024. local graceful_shutdown_failed = false
  1025. ---@private
  1026. --- Stops a client, optionally with force.
  1027. ---
  1028. ---By default, it will just ask the - server to shutdown without force. If
  1029. --- you request to stop a client which has previously been requested to
  1030. --- shutdown, it will automatically escalate and force shutdown.
  1031. ---
  1032. ---@param force (bool, optional)
  1033. function client.stop(force)
  1034. lsp.diagnostic.reset(client_id, all_buffer_active_clients)
  1035. changetracking.reset(client_id)
  1036. for _, client_ids in pairs(all_buffer_active_clients) do
  1037. client_ids[client_id] = nil
  1038. end
  1039. local handle = rpc.handle
  1040. if handle:is_closing() then
  1041. return
  1042. end
  1043. if force or (not client.initialized) or graceful_shutdown_failed then
  1044. handle:kill(15)
  1045. return
  1046. end
  1047. -- Sending a signal after a process has exited is acceptable.
  1048. rpc.request('shutdown', nil, function(err, _)
  1049. if err == nil then
  1050. rpc.notify('exit')
  1051. else
  1052. -- If there was an error in the shutdown request, then term to be safe.
  1053. handle:kill(15)
  1054. graceful_shutdown_failed = true
  1055. end
  1056. end)
  1057. end
  1058. ---@private
  1059. --- Checks whether a client is stopped.
  1060. ---
  1061. ---@returns (bool) true if client is stopped or in the process of being
  1062. ---stopped; false otherwise
  1063. function client.is_stopped()
  1064. return rpc.handle:is_closing()
  1065. end
  1066. ---@private
  1067. --- Runs the on_attach function from the client's config if it was defined.
  1068. ---@param bufnr (number) Buffer number
  1069. function client._on_attach(bufnr)
  1070. text_document_did_open_handler(bufnr, client)
  1071. if config.on_attach then
  1072. -- TODO(ashkan) handle errors.
  1073. pcall(config.on_attach, client, bufnr)
  1074. end
  1075. client.attached_buffers[bufnr] = true
  1076. end
  1077. initialize()
  1078. return client_id
  1079. end
  1080. ---@private
  1081. ---@fn text_document_did_change_handler(_, bufnr, changedtick, firstline, lastline, new_lastline, old_byte_size, old_utf32_size, old_utf16_size)
  1082. --- Notify all attached clients that a buffer has changed.
  1083. local text_document_did_change_handler
  1084. do
  1085. text_document_did_change_handler = function(_, bufnr, changedtick, firstline, lastline, new_lastline)
  1086. -- Detach (nvim_buf_attach) via returning True to on_lines if no clients are attached
  1087. if tbl_isempty(all_buffer_active_clients[bufnr] or {}) then
  1088. return true
  1089. end
  1090. util.buf_versions[bufnr] = changedtick
  1091. local compute_change_and_notify = changetracking.prepare(bufnr, firstline, lastline, new_lastline)
  1092. for_each_buffer_client(bufnr, compute_change_and_notify)
  1093. end
  1094. end
  1095. -- Buffer lifecycle handler for textDocument/didSave
  1096. function lsp._text_document_did_save_handler(bufnr)
  1097. bufnr = resolve_bufnr(bufnr)
  1098. local uri = vim.uri_from_bufnr(bufnr)
  1099. local text = once(buf_get_full_text)
  1100. for_each_buffer_client(bufnr, function(client, _client_id)
  1101. if client.resolved_capabilities.text_document_save then
  1102. local included_text
  1103. if client.resolved_capabilities.text_document_save_include_text then
  1104. included_text = text(bufnr)
  1105. end
  1106. client.notify('textDocument/didSave', {
  1107. textDocument = {
  1108. uri = uri;
  1109. };
  1110. text = included_text;
  1111. })
  1112. end
  1113. end)
  1114. end
  1115. --- Implements the `textDocument/did…` notifications required to track a buffer
  1116. --- for any language server.
  1117. ---
  1118. --- Without calling this, the server won't be notified of changes to a buffer.
  1119. ---
  1120. ---@param bufnr (number) Buffer handle, or 0 for current
  1121. ---@param client_id (number) Client id
  1122. function lsp.buf_attach_client(bufnr, client_id)
  1123. validate {
  1124. bufnr = {bufnr, 'n', true};
  1125. client_id = {client_id, 'n'};
  1126. }
  1127. bufnr = resolve_bufnr(bufnr)
  1128. if not vim.api.nvim_buf_is_loaded(bufnr) then
  1129. local _ = log.warn() and log.warn(
  1130. string.format("buf_attach_client called on unloaded buffer (id: %d): ", bufnr)
  1131. )
  1132. return false
  1133. end
  1134. local buffer_client_ids = all_buffer_active_clients[bufnr]
  1135. -- This is our first time attaching to this buffer.
  1136. if not buffer_client_ids then
  1137. buffer_client_ids = {}
  1138. all_buffer_active_clients[bufnr] = buffer_client_ids
  1139. local uri = vim.uri_from_bufnr(bufnr)
  1140. local buf_did_save_autocommand = [=[
  1141. augroup lsp_c_%d_b_%d_did_save
  1142. au!
  1143. au BufWritePost <buffer=%d> lua vim.lsp._text_document_did_save_handler(0)
  1144. augroup END
  1145. ]=]
  1146. vim.api.nvim_exec(string.format(buf_did_save_autocommand, client_id, bufnr, bufnr), false)
  1147. -- First time, so attach and set up stuff.
  1148. vim.api.nvim_buf_attach(bufnr, false, {
  1149. on_lines = text_document_did_change_handler;
  1150. on_reload = function()
  1151. local params = { textDocument = { uri = uri; } }
  1152. for_each_buffer_client(bufnr, function(client, _)
  1153. changetracking.reset_buf(client, bufnr)
  1154. if client.resolved_capabilities.text_document_open_close then
  1155. client.notify('textDocument/didClose', params)
  1156. end
  1157. text_document_did_open_handler(bufnr, client)
  1158. end)
  1159. end;
  1160. on_detach = function()
  1161. local params = { textDocument = { uri = uri; } }
  1162. for_each_buffer_client(bufnr, function(client, _)
  1163. changetracking.reset_buf(client, bufnr)
  1164. if client.resolved_capabilities.text_document_open_close then
  1165. client.notify('textDocument/didClose', params)
  1166. end
  1167. end)
  1168. util.buf_versions[bufnr] = nil
  1169. all_buffer_active_clients[bufnr] = nil
  1170. end;
  1171. -- TODO if we know all of the potential clients ahead of time, then we
  1172. -- could conditionally set this.
  1173. -- utf_sizes = size_index > 1;
  1174. utf_sizes = true;
  1175. })
  1176. end
  1177. if buffer_client_ids[client_id] then return end
  1178. -- This is our first time attaching this client to this buffer.
  1179. buffer_client_ids[client_id] = true
  1180. local client = active_clients[client_id]
  1181. -- Send didOpen for the client if it is initialized. If it isn't initialized
  1182. -- then it will send didOpen on initialize.
  1183. if client then
  1184. client._on_attach(bufnr)
  1185. end
  1186. return true
  1187. end
  1188. --- Detaches client from the specified buffer.
  1189. --- Note: While the server is notified that the text document (buffer)
  1190. --- was closed, it is still able to send notifications should it ignore this notification.
  1191. ---
  1192. ---@param bufnr number Buffer handle, or 0 for current
  1193. ---@param client_id number Client id
  1194. function lsp.buf_detach_client(bufnr, client_id)
  1195. validate {
  1196. bufnr = {bufnr, 'n', true};
  1197. client_id = {client_id, 'n'};
  1198. }
  1199. bufnr = resolve_bufnr(bufnr)
  1200. local client = lsp.get_client_by_id(client_id)
  1201. if not client or not client.attached_buffers[bufnr] then
  1202. vim.notify(
  1203. string.format('Buffer (id: %d) is not attached to client (id: %d). Cannot detach.', client_id, bufnr)
  1204. )
  1205. return
  1206. end
  1207. changetracking.reset_buf(client, bufnr)
  1208. if client.resolved_capabilities.text_document_open_close then
  1209. local uri = vim.uri_from_bufnr(bufnr)
  1210. local params = { textDocument = { uri = uri; } }
  1211. client.notify('textDocument/didClose', params)
  1212. end
  1213. client.attached_buffers[bufnr] = nil
  1214. util.buf_versions[bufnr] = nil
  1215. all_buffer_active_clients[bufnr][client_id] = nil
  1216. if #vim.tbl_keys(all_buffer_active_clients[bufnr]) == 0 then
  1217. all_buffer_active_clients[bufnr] = nil
  1218. end
  1219. local namespace = vim.lsp.diagnostic.get_namespace(client_id)
  1220. vim.diagnostic.reset(namespace, bufnr)
  1221. vim.notify(string.format('Detached buffer (id: %d) from client (id: %d)', bufnr, client_id))
  1222. end
  1223. --- Checks if a buffer is attached for a particular client.
  1224. ---
  1225. ---@param bufnr (number) Buffer handle, or 0 for current
  1226. ---@param client_id (number) the client id
  1227. function lsp.buf_is_attached(bufnr, client_id)
  1228. return (all_buffer_active_clients[resolve_bufnr(bufnr)] or {})[client_id] == true
  1229. end
  1230. --- Gets a client by id, or nil if the id is invalid.
  1231. --- The returned client may not yet be fully initialized.
  1232. ---
  1233. ---@param client_id number client id
  1234. ---
  1235. ---@returns |vim.lsp.client| object, or nil
  1236. function lsp.get_client_by_id(client_id)
  1237. return active_clients[client_id] or uninitialized_clients[client_id]
  1238. end
  1239. --- Returns list of buffers attached to client_id.
  1240. ---
  1241. ---@param client_id number client id
  1242. ---@returns list of buffer ids
  1243. function lsp.get_buffers_by_client_id(client_id)
  1244. local client = lsp.get_client_by_id(client_id)
  1245. return client and vim.tbl_keys(client.attached_buffers) or {}
  1246. end
  1247. --- Stops a client(s).
  1248. ---
  1249. --- You can also use the `stop()` function on a |vim.lsp.client| object.
  1250. --- To stop all clients:
  1251. ---
  1252. --- <pre>
  1253. --- vim.lsp.stop_client(vim.lsp.get_active_clients())
  1254. --- </pre>
  1255. ---
  1256. --- By default asks the server to shutdown, unless stop was requested
  1257. --- already for this client, then force-shutdown is attempted.
  1258. ---
  1259. ---@param client_id client id or |vim.lsp.client| object, or list thereof
  1260. ---@param force boolean (optional) shutdown forcefully
  1261. function lsp.stop_client(client_id, force)
  1262. local ids = type(client_id) == 'table' and client_id or {client_id}
  1263. for _, id in ipairs(ids) do
  1264. if type(id) == 'table' and id.stop ~= nil then
  1265. id.stop(force)
  1266. elseif active_clients[id] then
  1267. active_clients[id].stop(force)
  1268. elseif uninitialized_clients[id] then
  1269. uninitialized_clients[id].stop(true)
  1270. end
  1271. end
  1272. end
  1273. --- Gets all active clients.
  1274. ---
  1275. ---@returns Table of |vim.lsp.client| objects
  1276. function lsp.get_active_clients()
  1277. return vim.tbl_values(active_clients)
  1278. end
  1279. function lsp._vim_exit_handler()
  1280. log.info("exit_handler", active_clients)
  1281. for _, client in pairs(uninitialized_clients) do
  1282. client.stop(true)
  1283. end
  1284. -- TODO handle v:dying differently?
  1285. if tbl_isempty(active_clients) then
  1286. return
  1287. end
  1288. for _, client in pairs(active_clients) do
  1289. client.stop()
  1290. end
  1291. local timeouts = {}
  1292. local max_timeout = 0
  1293. local send_kill = false
  1294. for client_id, client in pairs(active_clients) do
  1295. local timeout = if_nil(client.config.flags.exit_timeout, 500)
  1296. if timeout then
  1297. send_kill = true
  1298. timeouts[client_id] = timeout
  1299. max_timeout = math.max(timeout, max_timeout)
  1300. end
  1301. end
  1302. local poll_time = 50
  1303. ---@private
  1304. local function check_clients_closed()
  1305. for client_id, timeout in pairs(timeouts) do
  1306. timeouts[client_id] = timeout - poll_time
  1307. end
  1308. for client_id, _ in pairs(active_clients) do
  1309. if timeouts[client_id] ~= nil and timeouts[client_id] > 0 then
  1310. return false
  1311. end
  1312. end
  1313. return true
  1314. end
  1315. if send_kill then
  1316. if not vim.wait(max_timeout, check_clients_closed, poll_time) then
  1317. for client_id, client in pairs(active_clients) do
  1318. if timeouts[client_id] ~= nil then
  1319. client.stop(true)
  1320. end
  1321. end
  1322. end
  1323. end
  1324. end
  1325. nvim_command("autocmd VimLeavePre * lua vim.lsp._vim_exit_handler()")
  1326. --- Sends an async request for all active clients attached to the
  1327. --- buffer.
  1328. ---
  1329. ---@param bufnr (number) Buffer handle, or 0 for current.
  1330. ---@param method (string) LSP method name
  1331. ---@param params (optional, table) Parameters to send to the server
  1332. ---@param handler (optional, function) See |lsp-handler|
  1333. --- If nil, follows resolution strategy defined in |lsp-handler-configuration|
  1334. ---
  1335. ---@returns 2-tuple:
  1336. --- - Map of client-id:request-id pairs for all successful requests.
  1337. --- - Function which can be used to cancel all the requests. You could instead
  1338. --- iterate all clients and call their `cancel_request()` methods.
  1339. function lsp.buf_request(bufnr, method, params, handler)
  1340. validate {
  1341. bufnr = { bufnr, 'n', true };
  1342. method = { method, 's' };
  1343. handler = { handler, 'f', true };
  1344. }
  1345. local supported_clients = {}
  1346. local method_supported = false
  1347. for_each_buffer_client(bufnr, function(client, client_id)
  1348. if client.supports_method(method) then
  1349. method_supported = true
  1350. table.insert(supported_clients, client_id)
  1351. end
  1352. end)
  1353. -- if has client but no clients support the given method, notify the user
  1354. if not tbl_isempty(all_buffer_active_clients[resolve_bufnr(bufnr)] or {}) and not method_supported then
  1355. vim.notify(lsp._unsupported_method(method), vim.log.levels.ERROR)
  1356. vim.api.nvim_command("redraw")
  1357. return {}, function() end
  1358. end
  1359. local client_request_ids = {}
  1360. for_each_buffer_client(bufnr, function(client, client_id, resolved_bufnr)
  1361. local request_success, request_id = client.request(method, params, handler, resolved_bufnr)
  1362. -- This could only fail if the client shut down in the time since we looked
  1363. -- it up and we did the request, which should be rare.
  1364. if request_success then
  1365. client_request_ids[client_id] = request_id
  1366. end
  1367. end, supported_clients)
  1368. local function _cancel_all_requests()
  1369. for client_id, request_id in pairs(client_request_ids) do
  1370. local client = active_clients[client_id]
  1371. client.cancel_request(request_id)
  1372. end
  1373. end
  1374. return client_request_ids, _cancel_all_requests
  1375. end
  1376. ---Sends an async request for all active clients attached to the buffer.
  1377. ---Executes the callback on the combined result.
  1378. ---Parameters are the same as |vim.lsp.buf_request()| but the return result and callback are
  1379. ---different.
  1380. ---
  1381. ---@param bufnr (number) Buffer handle, or 0 for current.
  1382. ---@param method (string) LSP method name
  1383. ---@param params (optional, table) Parameters to send to the server
  1384. ---@param callback (function) The callback to call when all requests are finished.
  1385. -- Unlike `buf_request`, this will collect all the responses from each server instead of handling them.
  1386. -- A map of client_id:request_result will be provided to the callback
  1387. --
  1388. ---@returns (function) A function that will cancel all requests which is the same as the one returned from `buf_request`.
  1389. function lsp.buf_request_all(bufnr, method, params, callback)
  1390. local request_results = {}
  1391. local result_count = 0
  1392. local expected_result_count = 0
  1393. local set_expected_result_count = once(function ()
  1394. for_each_buffer_client(bufnr, function(client)
  1395. if client.supports_method(method) then
  1396. expected_result_count = expected_result_count + 1
  1397. end
  1398. end)
  1399. end)
  1400. local function _sync_handler(err, result, ctx)
  1401. request_results[ctx.client_id] = { error = err, result = result }
  1402. result_count = result_count + 1
  1403. set_expected_result_count()
  1404. if result_count >= expected_result_count then
  1405. callback(request_results)
  1406. end
  1407. end
  1408. local _, cancel = lsp.buf_request(bufnr, method, params, _sync_handler)
  1409. return cancel
  1410. end
  1411. --- Sends a request to all server and waits for the response of all of them.
  1412. ---
  1413. --- Calls |vim.lsp.buf_request_all()| but blocks Nvim while awaiting the result.
  1414. --- Parameters are the same as |vim.lsp.buf_request()| but the return result is
  1415. --- different. Wait maximum of {timeout_ms} (default 1000) ms.
  1416. ---
  1417. ---@param bufnr (number) Buffer handle, or 0 for current.
  1418. ---@param method (string) LSP method name
  1419. ---@param params (optional, table) Parameters to send to the server
  1420. ---@param timeout_ms (optional, number, default=1000) Maximum time in
  1421. --- milliseconds to wait for a result.
  1422. ---
  1423. ---@returns Map of client_id:request_result. On timeout, cancel or error,
  1424. --- returns `(nil, err)` where `err` is a string describing the failure
  1425. --- reason.
  1426. function lsp.buf_request_sync(bufnr, method, params, timeout_ms)
  1427. local request_results
  1428. local cancel = lsp.buf_request_all(bufnr, method, params, function(it)
  1429. request_results = it
  1430. end)
  1431. local wait_result, reason = vim.wait(timeout_ms or 1000, function()
  1432. return request_results ~= nil
  1433. end, 10)
  1434. if not wait_result then
  1435. cancel()
  1436. return nil, wait_result_reason[reason]
  1437. end
  1438. return request_results
  1439. end
  1440. --- Send a notification to a server
  1441. ---@param bufnr [number] (optional): The number of the buffer
  1442. ---@param method [string]: Name of the request method
  1443. ---@param params [string]: Arguments to send to the server
  1444. ---
  1445. ---@returns true if any client returns true; false otherwise
  1446. function lsp.buf_notify(bufnr, method, params)
  1447. validate {
  1448. bufnr = { bufnr, 'n', true };
  1449. method = { method, 's' };
  1450. }
  1451. local resp = false
  1452. for_each_buffer_client(bufnr, function(client, _client_id, _resolved_bufnr)
  1453. if client.rpc.notify(method, params) then resp = true end
  1454. end)
  1455. return resp
  1456. end
  1457. ---@private
  1458. local function adjust_start_col(lnum, line, items, encoding)
  1459. local min_start_char = nil
  1460. for _, item in pairs(items) do
  1461. if item.filterText == nil and item.textEdit and item.textEdit.range.start.line == lnum - 1 then
  1462. if min_start_char and min_start_char ~= item.textEdit.range.start.character then
  1463. return nil
  1464. end
  1465. min_start_char = item.textEdit.range.start.character
  1466. end
  1467. end
  1468. if min_start_char then
  1469. return util._str_byteindex_enc(line, min_start_char, encoding)
  1470. else
  1471. return nil
  1472. end
  1473. end
  1474. --- Implements 'omnifunc' compatible LSP completion.
  1475. ---
  1476. ---@see |complete-functions|
  1477. ---@see |complete-items|
  1478. ---@see |CompleteDone|
  1479. ---
  1480. ---@param findstart 0 or 1, decides behavior
  1481. ---@param base If findstart=0, text to match against
  1482. ---
  1483. ---@returns (number) Decided by {findstart}:
  1484. --- - findstart=0: column where the completion starts, or -2 or -3
  1485. --- - findstart=1: list of matches (actually just calls |complete()|)
  1486. function lsp.omnifunc(findstart, base)
  1487. local _ = log.debug() and log.debug("omnifunc.findstart", { findstart = findstart, base = base })
  1488. local bufnr = resolve_bufnr()
  1489. local has_buffer_clients = not tbl_isempty(all_buffer_active_clients[bufnr] or {})
  1490. if not has_buffer_clients then
  1491. if findstart == 1 then
  1492. return -1
  1493. else
  1494. return {}
  1495. end
  1496. end
  1497. -- Then, perform standard completion request
  1498. local _ = log.info() and log.info("base ", base)
  1499. local pos = vim.api.nvim_win_get_cursor(0)
  1500. local line = vim.api.nvim_get_current_line()
  1501. local line_to_cursor = line:sub(1, pos[2])
  1502. local _ = log.trace() and log.trace("omnifunc.line", pos, line)
  1503. -- Get the start position of the current keyword
  1504. local textMatch = vim.fn.match(line_to_cursor, '\\k*$')
  1505. local params = util.make_position_params()
  1506. local items = {}
  1507. lsp.buf_request(bufnr, 'textDocument/completion', params, function(err, result, ctx)
  1508. if err or not result or vim.fn.mode() ~= "i" then return end
  1509. -- Completion response items may be relative to a position different than `textMatch`.
  1510. -- Concrete example, with sumneko/lua-language-server:
  1511. --
  1512. -- require('plenary.asy|
  1513. -- ▲ ▲ ▲
  1514. -- │ │ └── cursor_pos: 20
  1515. -- │ └────── textMatch: 17
  1516. -- └────────────── textEdit.range.start.character: 9
  1517. -- .newText = 'plenary.async'
  1518. -- ^^^
  1519. -- prefix (We'd remove everything not starting with `asy`,
  1520. -- so we'd eliminate the `plenary.async` result
  1521. --
  1522. -- `adjust_start_col` is used to prefer the language server boundary.
  1523. --
  1524. local client = lsp.get_client_by_id(ctx.client_id)
  1525. local encoding = client and client.offset_encoding or 'utf-16'
  1526. local candidates = util.extract_completion_items(result)
  1527. local startbyte = adjust_start_col(pos[1], line, candidates, encoding) or textMatch
  1528. local prefix = line:sub(startbyte + 1, pos[2])
  1529. local matches = util.text_document_completion_list_to_complete_items(result, prefix)
  1530. -- TODO(ashkan): is this the best way to do this?
  1531. vim.list_extend(items, matches)
  1532. vim.fn.complete(startbyte + 1, items)
  1533. end)
  1534. -- Return -2 to signal that we should continue completion so that we can
  1535. -- async complete.
  1536. return -2
  1537. end
  1538. --- Provides an interface between the built-in client and a `formatexpr` function.
  1539. ---
  1540. --- Currently only supports a single client. This can be set via
  1541. --- `setlocal formatexpr=v:lua.vim.lsp.formatexpr()` but will typically or in `on_attach`
  1542. --- via ``vim.api.nvim_buf_set_option(bufnr, 'formatexpr', 'v:lua.vim.lsp.formatexpr(#{timeout_ms:250})')``.
  1543. ---
  1544. ---@param opts table options for customizing the formatting expression which takes the
  1545. --- following optional keys:
  1546. --- * timeout_ms (default 500ms). The timeout period for the formatting request.
  1547. function lsp.formatexpr(opts)
  1548. opts = opts or {}
  1549. local timeout_ms = opts.timeout_ms or 500
  1550. if vim.tbl_contains({'i', 'R', 'ic', 'ix'}, vim.fn.mode()) then
  1551. -- `formatexpr` is also called when exceeding `textwidth` in insert mode
  1552. -- fall back to internal formatting
  1553. return 1
  1554. end
  1555. local start_line = vim.v.lnum
  1556. local end_line = start_line + vim.v.count - 1
  1557. if start_line > 0 and end_line > 0 then
  1558. local params = {
  1559. textDocument = util.make_text_document_params();
  1560. range = {
  1561. start = { line = start_line - 1; character = 0; };
  1562. ["end"] = { line = end_line - 1; character = 0; };
  1563. };
  1564. };
  1565. params.options = util.make_formatting_params().options
  1566. local client_results = vim.lsp.buf_request_sync(0, "textDocument/rangeFormatting", params, timeout_ms)
  1567. -- Apply the text edits from one and only one of the clients.
  1568. for client_id, response in pairs(client_results) do
  1569. if response.result then
  1570. vim.lsp.util.apply_text_edits(response.result, 0, vim.lsp.get_client_by_id(client_id).offset_encoding)
  1571. return 0
  1572. end
  1573. end
  1574. end
  1575. -- do not run builtin formatter.
  1576. return 0
  1577. end
  1578. --- Provides an interface between the built-in client and 'tagfunc'.
  1579. ---
  1580. --- When used with normal mode commands (e.g. |CTRL-]|) this will invoke
  1581. --- the "textDocument/definition" LSP method to find the tag under the cursor.
  1582. --- Otherwise, uses "workspace/symbol". If no results are returned from
  1583. --- any LSP servers, falls back to using built-in tags.
  1584. ---
  1585. ---@param pattern Pattern used to find a workspace symbol
  1586. ---@param flags See |tag-function|
  1587. ---
  1588. ---@returns A list of matching tags
  1589. function lsp.tagfunc(...)
  1590. return require('vim.lsp.tagfunc')(...)
  1591. end
  1592. ---Checks whether a client is stopped.
  1593. ---
  1594. ---@param client_id (Number)
  1595. ---@returns true if client is stopped, false otherwise.
  1596. function lsp.client_is_stopped(client_id)
  1597. return active_clients[client_id] == nil
  1598. end
  1599. --- Gets a map of client_id:client pairs for the given buffer, where each value
  1600. --- is a |vim.lsp.client| object.
  1601. ---
  1602. ---@param bufnr (optional, number): Buffer handle, or 0 for current
  1603. function lsp.buf_get_clients(bufnr)
  1604. bufnr = resolve_bufnr(bufnr)
  1605. local result = {}
  1606. for_each_buffer_client(bufnr, function(client, client_id)
  1607. result[client_id] = client
  1608. end)
  1609. return result
  1610. end
  1611. -- Log level dictionary with reverse lookup as well.
  1612. --
  1613. -- Can be used to lookup the number from the name or the
  1614. -- name from the number.
  1615. -- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR"
  1616. -- Level numbers begin with "TRACE" at 0
  1617. lsp.log_levels = log.levels
  1618. --- Sets the global log level for LSP logging.
  1619. ---
  1620. --- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR"
  1621. --- Level numbers begin with "TRACE" at 0
  1622. ---
  1623. --- Use `lsp.log_levels` for reverse lookup.
  1624. ---
  1625. ---@see |vim.lsp.log_levels|
  1626. ---
  1627. ---@param level [number|string] the case insensitive level name or number
  1628. function lsp.set_log_level(level)
  1629. if type(level) == 'string' or type(level) == 'number' then
  1630. log.set_level(level)
  1631. else
  1632. error(string.format("Invalid log level: %q", level))
  1633. end
  1634. end
  1635. --- Gets the path of the logfile used by the LSP client.
  1636. ---@returns (String) Path to logfile.
  1637. function lsp.get_log_path()
  1638. return log.get_filename()
  1639. end
  1640. --- Invokes a function for each LSP client attached to a buffer.
  1641. ---
  1642. ---@param bufnr number Buffer number
  1643. ---@param fn function Function to run on each client attached to buffer
  1644. --- {bufnr}. The function takes the client, client ID, and
  1645. --- buffer number as arguments. Example:
  1646. --- <pre>
  1647. --- vim.lsp.for_each_buffer_client(0, function(client, client_id, bufnr)
  1648. --- print(vim.inspect(client))
  1649. --- end)
  1650. --- </pre>
  1651. function lsp.for_each_buffer_client(bufnr, fn)
  1652. return for_each_buffer_client(bufnr, fn)
  1653. end
  1654. --- Function to manage overriding defaults for LSP handlers.
  1655. ---@param handler (function) See |lsp-handler|
  1656. ---@param override_config (table) Table containing the keys to override behavior of the {handler}
  1657. function lsp.with(handler, override_config)
  1658. return function(err, result, ctx, config)
  1659. return handler(err, result, ctx, vim.tbl_deep_extend("force", config or {}, override_config))
  1660. end
  1661. end
  1662. --- Helper function to use when implementing a handler.
  1663. --- This will check that all of the keys in the user configuration
  1664. --- are valid keys and make sense to include for this handler.
  1665. ---
  1666. --- Will error on invalid keys (i.e. keys that do not exist in the options)
  1667. function lsp._with_extend(name, options, user_config)
  1668. user_config = user_config or {}
  1669. local resulting_config = {}
  1670. for k, v in pairs(user_config) do
  1671. if options[k] == nil then
  1672. error(debug.traceback(string.format(
  1673. "Invalid option for `%s`: %s. Valid options are:\n%s",
  1674. name,
  1675. k,
  1676. vim.inspect(vim.tbl_keys(options))
  1677. )))
  1678. end
  1679. resulting_config[k] = v
  1680. end
  1681. for k, v in pairs(options) do
  1682. if resulting_config[k] == nil then
  1683. resulting_config[k] = v
  1684. end
  1685. end
  1686. return resulting_config
  1687. end
  1688. --- Registry for client side commands.
  1689. --- This is an extension point for plugins to handle custom commands which are
  1690. --- not part of the core language server protocol specification.
  1691. ---
  1692. --- The registry is a table where the key is a unique command name,
  1693. --- and the value is a function which is called if any LSP action
  1694. --- (code action, code lenses, ...) triggers the command.
  1695. ---
  1696. --- If a LSP response contains a command for which no matching entry is
  1697. --- available in this registry, the command will be executed via the LSP server
  1698. --- using `workspace/executeCommand`.
  1699. ---
  1700. --- The first argument to the function will be the `Command`:
  1701. --- Command
  1702. --- title: String
  1703. --- command: String
  1704. --- arguments?: any[]
  1705. ---
  1706. --- The second argument is the `ctx` of |lsp-handler|
  1707. lsp.commands = setmetatable({}, {
  1708. __newindex = function(tbl, key, value)
  1709. assert(type(key) == 'string', "The key for commands in `vim.lsp.commands` must be a string")
  1710. assert(type(value) == 'function', "Command added to `vim.lsp.commands` must be a function")
  1711. rawset(tbl, key, value)
  1712. end;
  1713. })
  1714. return lsp
  1715. -- vim:sw=2 ts=2 et