lsp.lua 79 KB

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