diagnostic.lua 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618
  1. local if_nil = vim.F.if_nil
  2. local M = {}
  3. M.severity = {
  4. ERROR = 1,
  5. WARN = 2,
  6. INFO = 3,
  7. HINT = 4,
  8. }
  9. vim.tbl_add_reverse_lookup(M.severity)
  10. -- Mappings from qflist/loclist error types to severities
  11. M.severity.E = M.severity.ERROR
  12. M.severity.W = M.severity.WARN
  13. M.severity.I = M.severity.INFO
  14. M.severity.N = M.severity.HINT
  15. local global_diagnostic_options = {
  16. signs = true,
  17. underline = true,
  18. virtual_text = true,
  19. float = true,
  20. update_in_insert = false,
  21. severity_sort = false,
  22. }
  23. M.handlers = setmetatable({}, {
  24. __newindex = function(t, name, handler)
  25. vim.validate { handler = {handler, "t" } }
  26. rawset(t, name, handler)
  27. if global_diagnostic_options[name] == nil then
  28. global_diagnostic_options[name] = true
  29. end
  30. end,
  31. })
  32. -- Metatable that automatically creates an empty table when assigning to a missing key
  33. local bufnr_and_namespace_cacher_mt = {
  34. __index = function(t, bufnr)
  35. assert(bufnr > 0, "Invalid buffer number")
  36. t[bufnr] = {}
  37. return t[bufnr]
  38. end,
  39. }
  40. local diagnostic_cache = setmetatable({}, {
  41. __index = function(t, bufnr)
  42. assert(bufnr > 0, "Invalid buffer number")
  43. vim.api.nvim_buf_attach(bufnr, false, {
  44. on_detach = function()
  45. rawset(t, bufnr, nil) -- clear cache
  46. end
  47. })
  48. t[bufnr] = {}
  49. return t[bufnr]
  50. end,
  51. })
  52. local diagnostic_cache_extmarks = setmetatable({}, bufnr_and_namespace_cacher_mt)
  53. local diagnostic_attached_buffers = {}
  54. local diagnostic_disabled = {}
  55. local bufs_waiting_to_update = setmetatable({}, bufnr_and_namespace_cacher_mt)
  56. local all_namespaces = {}
  57. ---@private
  58. local function to_severity(severity)
  59. if type(severity) == 'string' then
  60. return assert(M.severity[string.upper(severity)], string.format("Invalid severity: %s", severity))
  61. end
  62. return severity
  63. end
  64. ---@private
  65. local function filter_by_severity(severity, diagnostics)
  66. if not severity then
  67. return diagnostics
  68. end
  69. if type(severity) ~= "table" then
  70. severity = to_severity(severity)
  71. return vim.tbl_filter(function(t) return t.severity == severity end, diagnostics)
  72. end
  73. local min_severity = to_severity(severity.min) or M.severity.HINT
  74. local max_severity = to_severity(severity.max) or M.severity.ERROR
  75. return vim.tbl_filter(function(t) return t.severity <= min_severity and t.severity >= max_severity end, diagnostics)
  76. end
  77. ---@private
  78. local function count_sources(bufnr)
  79. local seen = {}
  80. local count = 0
  81. for _, namespace_diagnostics in pairs(diagnostic_cache[bufnr]) do
  82. for _, diagnostic in ipairs(namespace_diagnostics) do
  83. if diagnostic.source and not seen[diagnostic.source] then
  84. seen[diagnostic.source] = true
  85. count = count + 1
  86. end
  87. end
  88. end
  89. return count
  90. end
  91. ---@private
  92. local function prefix_source(diagnostics)
  93. return vim.tbl_map(function(d)
  94. if not d.source then
  95. return d
  96. end
  97. local t = vim.deepcopy(d)
  98. t.message = string.format("%s: %s", d.source, d.message)
  99. return t
  100. end, diagnostics)
  101. end
  102. ---@private
  103. local function reformat_diagnostics(format, diagnostics)
  104. vim.validate {
  105. format = {format, 'f'},
  106. diagnostics = {diagnostics, 't'},
  107. }
  108. local formatted = vim.deepcopy(diagnostics)
  109. for _, diagnostic in ipairs(formatted) do
  110. diagnostic.message = format(diagnostic)
  111. end
  112. return formatted
  113. end
  114. ---@private
  115. local function enabled_value(option, namespace)
  116. local ns = namespace and M.get_namespace(namespace) or {}
  117. if ns.opts and type(ns.opts[option]) == "table" then
  118. return ns.opts[option]
  119. end
  120. if type(global_diagnostic_options[option]) == "table" then
  121. return global_diagnostic_options[option]
  122. end
  123. return {}
  124. end
  125. ---@private
  126. local function resolve_optional_value(option, value, namespace, bufnr)
  127. if not value then
  128. return false
  129. elseif value == true then
  130. return enabled_value(option, namespace)
  131. elseif type(value) == 'function' then
  132. local val = value(namespace, bufnr)
  133. if val == true then
  134. return enabled_value(option, namespace)
  135. else
  136. return val
  137. end
  138. elseif type(value) == 'table' then
  139. return value
  140. else
  141. error("Unexpected option type: " .. vim.inspect(value))
  142. end
  143. end
  144. ---@private
  145. local function get_resolved_options(opts, namespace, bufnr)
  146. local ns = namespace and M.get_namespace(namespace) or {}
  147. -- Do not use tbl_deep_extend so that an empty table can be used to reset to default values
  148. local resolved = vim.tbl_extend('keep', opts or {}, ns.opts or {}, global_diagnostic_options)
  149. for k in pairs(global_diagnostic_options) do
  150. if resolved[k] ~= nil then
  151. resolved[k] = resolve_optional_value(k, resolved[k], namespace, bufnr)
  152. end
  153. end
  154. return resolved
  155. end
  156. -- Default diagnostic highlights
  157. local diagnostic_severities = {
  158. [M.severity.ERROR] = { ctermfg = 1, guifg = "Red" };
  159. [M.severity.WARN] = { ctermfg = 3, guifg = "Orange" };
  160. [M.severity.INFO] = { ctermfg = 4, guifg = "LightBlue" };
  161. [M.severity.HINT] = { ctermfg = 7, guifg = "LightGrey" };
  162. }
  163. -- Make a map from DiagnosticSeverity -> Highlight Name
  164. ---@private
  165. local function make_highlight_map(base_name)
  166. local result = {}
  167. for k in pairs(diagnostic_severities) do
  168. local name = M.severity[k]
  169. name = name:sub(1, 1) .. name:sub(2):lower()
  170. result[k] = "Diagnostic" .. base_name .. name
  171. end
  172. return result
  173. end
  174. local virtual_text_highlight_map = make_highlight_map("VirtualText")
  175. local underline_highlight_map = make_highlight_map("Underline")
  176. local floating_highlight_map = make_highlight_map("Floating")
  177. local sign_highlight_map = make_highlight_map("Sign")
  178. ---@private
  179. local define_default_signs = (function()
  180. local signs_defined = false
  181. return function()
  182. if signs_defined then
  183. return
  184. end
  185. for severity, sign_hl_name in pairs(sign_highlight_map) do
  186. if vim.tbl_isempty(vim.fn.sign_getdefined(sign_hl_name)) then
  187. local severity_name = M.severity[severity]
  188. vim.fn.sign_define(sign_hl_name, {
  189. text = (severity_name or 'U'):sub(1, 1),
  190. texthl = sign_hl_name,
  191. linehl = '',
  192. numhl = '',
  193. })
  194. end
  195. end
  196. signs_defined = true
  197. end
  198. end)()
  199. ---@private
  200. local function get_bufnr(bufnr)
  201. if not bufnr or bufnr == 0 then
  202. return vim.api.nvim_get_current_buf()
  203. end
  204. return bufnr
  205. end
  206. ---@private
  207. local function is_disabled(namespace, bufnr)
  208. local ns = M.get_namespace(namespace)
  209. if ns.disabled then
  210. return true
  211. end
  212. if type(diagnostic_disabled[bufnr]) == "table" then
  213. return diagnostic_disabled[bufnr][namespace]
  214. end
  215. return diagnostic_disabled[bufnr]
  216. end
  217. ---@private
  218. local function diagnostic_lines(diagnostics)
  219. if not diagnostics then
  220. return {}
  221. end
  222. local diagnostics_by_line = {}
  223. for _, diagnostic in ipairs(diagnostics) do
  224. local line_diagnostics = diagnostics_by_line[diagnostic.lnum]
  225. if not line_diagnostics then
  226. line_diagnostics = {}
  227. diagnostics_by_line[diagnostic.lnum] = line_diagnostics
  228. end
  229. table.insert(line_diagnostics, diagnostic)
  230. end
  231. return diagnostics_by_line
  232. end
  233. ---@private
  234. local function set_diagnostic_cache(namespace, bufnr, diagnostics)
  235. for _, diagnostic in ipairs(diagnostics) do
  236. assert(diagnostic.lnum, "Diagnostic line number is required")
  237. assert(diagnostic.col, "Diagnostic column is required")
  238. diagnostic.severity = diagnostic.severity and to_severity(diagnostic.severity) or M.severity.ERROR
  239. diagnostic.end_lnum = diagnostic.end_lnum or diagnostic.lnum
  240. diagnostic.end_col = diagnostic.end_col or diagnostic.col
  241. diagnostic.namespace = namespace
  242. diagnostic.bufnr = bufnr
  243. end
  244. diagnostic_cache[bufnr][namespace] = diagnostics
  245. end
  246. ---@private
  247. local function restore_extmarks(bufnr, last)
  248. for ns, extmarks in pairs(diagnostic_cache_extmarks[bufnr]) do
  249. local extmarks_current = vim.api.nvim_buf_get_extmarks(bufnr, ns, 0, -1, {details = true})
  250. local found = {}
  251. for _, extmark in ipairs(extmarks_current) do
  252. -- nvim_buf_set_lines will move any extmark to the line after the last
  253. -- nvim_buf_set_text will move any extmark to the last line
  254. if extmark[2] ~= last + 1 then
  255. found[extmark[1]] = true
  256. end
  257. end
  258. for _, extmark in ipairs(extmarks) do
  259. if not found[extmark[1]] then
  260. local opts = extmark[4]
  261. opts.id = extmark[1]
  262. pcall(vim.api.nvim_buf_set_extmark, bufnr, ns, extmark[2], extmark[3], opts)
  263. end
  264. end
  265. end
  266. end
  267. ---@private
  268. local function save_extmarks(namespace, bufnr)
  269. bufnr = get_bufnr(bufnr)
  270. if not diagnostic_attached_buffers[bufnr] then
  271. vim.api.nvim_buf_attach(bufnr, false, {
  272. on_lines = function(_, _, _, _, _, last)
  273. restore_extmarks(bufnr, last - 1)
  274. end,
  275. on_detach = function()
  276. diagnostic_cache_extmarks[bufnr] = nil
  277. end})
  278. diagnostic_attached_buffers[bufnr] = true
  279. end
  280. diagnostic_cache_extmarks[bufnr][namespace] = vim.api.nvim_buf_get_extmarks(bufnr, namespace, 0, -1, {details = true})
  281. end
  282. local registered_autocmds = {}
  283. ---@private
  284. local function make_augroup_key(namespace, bufnr)
  285. local ns = M.get_namespace(namespace)
  286. return string.format("DiagnosticInsertLeave:%s:%s", bufnr, ns.name)
  287. end
  288. --- Table of autocmd events to fire the update for displaying new diagnostic information
  289. local insert_leave_auto_cmds = { "InsertLeave", "CursorHoldI" }
  290. ---@private
  291. local function schedule_display(namespace, bufnr, args)
  292. bufs_waiting_to_update[bufnr][namespace] = args
  293. local key = make_augroup_key(namespace, bufnr)
  294. if not registered_autocmds[key] then
  295. vim.cmd(string.format([[augroup %s
  296. au!
  297. autocmd %s <buffer=%s> lua vim.diagnostic._execute_scheduled_display(%s, %s)
  298. augroup END]],
  299. key,
  300. table.concat(insert_leave_auto_cmds, ","),
  301. bufnr,
  302. namespace,
  303. bufnr))
  304. registered_autocmds[key] = true
  305. end
  306. end
  307. ---@private
  308. local function clear_scheduled_display(namespace, bufnr)
  309. local key = make_augroup_key(namespace, bufnr)
  310. if registered_autocmds[key] then
  311. vim.cmd(string.format([[augroup %s
  312. au!
  313. augroup END]], key))
  314. registered_autocmds[key] = nil
  315. end
  316. end
  317. ---@private
  318. local function get_diagnostics(bufnr, opts, clamp)
  319. opts = opts or {}
  320. local namespace = opts.namespace
  321. local diagnostics = {}
  322. -- Memoized results of buf_line_count per bufnr
  323. local buf_line_count = setmetatable({}, {
  324. __index = function(t, k)
  325. t[k] = vim.api.nvim_buf_line_count(k)
  326. return rawget(t, k)
  327. end,
  328. })
  329. ---@private
  330. local function add(b, d)
  331. if not opts.lnum or d.lnum == opts.lnum then
  332. if clamp and vim.api.nvim_buf_is_loaded(b) then
  333. local line_count = buf_line_count[b] - 1
  334. if (d.lnum > line_count or d.end_lnum > line_count or d.lnum < 0 or d.end_lnum < 0) then
  335. d = vim.deepcopy(d)
  336. d.lnum = math.max(math.min(d.lnum, line_count), 0)
  337. d.end_lnum = math.max(math.min(d.end_lnum, line_count), 0)
  338. end
  339. end
  340. table.insert(diagnostics, d)
  341. end
  342. end
  343. if namespace == nil and bufnr == nil then
  344. for b, t in pairs(diagnostic_cache) do
  345. for _, v in pairs(t) do
  346. for _, diagnostic in pairs(v) do
  347. add(b, diagnostic)
  348. end
  349. end
  350. end
  351. elseif namespace == nil then
  352. bufnr = get_bufnr(bufnr)
  353. for iter_namespace in pairs(diagnostic_cache[bufnr]) do
  354. for _, diagnostic in pairs(diagnostic_cache[bufnr][iter_namespace]) do
  355. add(bufnr, diagnostic)
  356. end
  357. end
  358. elseif bufnr == nil then
  359. for b, t in pairs(diagnostic_cache) do
  360. for _, diagnostic in pairs(t[namespace] or {}) do
  361. add(b, diagnostic)
  362. end
  363. end
  364. else
  365. bufnr = get_bufnr(bufnr)
  366. for _, diagnostic in pairs(diagnostic_cache[bufnr][namespace] or {}) do
  367. add(bufnr, diagnostic)
  368. end
  369. end
  370. if opts.severity then
  371. diagnostics = filter_by_severity(opts.severity, diagnostics)
  372. end
  373. return diagnostics
  374. end
  375. ---@private
  376. local function set_list(loclist, opts)
  377. opts = opts or {}
  378. local open = vim.F.if_nil(opts.open, true)
  379. local title = opts.title or "Diagnostics"
  380. local winnr = opts.winnr or 0
  381. local bufnr
  382. if loclist then
  383. bufnr = vim.api.nvim_win_get_buf(winnr)
  384. end
  385. -- Don't clamp line numbers since the quickfix list can already handle line
  386. -- numbers beyond the end of the buffer
  387. local diagnostics = get_diagnostics(bufnr, opts, false)
  388. local items = M.toqflist(diagnostics)
  389. if loclist then
  390. vim.fn.setloclist(winnr, {}, ' ', { title = title, items = items })
  391. else
  392. vim.fn.setqflist({}, ' ', { title = title, items = items })
  393. end
  394. if open then
  395. vim.api.nvim_command(loclist and "lopen" or "botright copen")
  396. end
  397. end
  398. ---@private
  399. local function next_diagnostic(position, search_forward, bufnr, opts, namespace)
  400. position[1] = position[1] - 1
  401. bufnr = get_bufnr(bufnr)
  402. local wrap = vim.F.if_nil(opts.wrap, true)
  403. local line_count = vim.api.nvim_buf_line_count(bufnr)
  404. local diagnostics = get_diagnostics(bufnr, vim.tbl_extend("keep", opts, {namespace = namespace}), true)
  405. local line_diagnostics = diagnostic_lines(diagnostics)
  406. for i = 0, line_count do
  407. local offset = i * (search_forward and 1 or -1)
  408. local lnum = position[1] + offset
  409. if lnum < 0 or lnum >= line_count then
  410. if not wrap then
  411. return
  412. end
  413. lnum = (lnum + line_count) % line_count
  414. end
  415. if line_diagnostics[lnum] and not vim.tbl_isempty(line_diagnostics[lnum]) then
  416. local line_length = #vim.api.nvim_buf_get_lines(bufnr, lnum, lnum + 1, true)[1]
  417. local sort_diagnostics, is_next
  418. if search_forward then
  419. sort_diagnostics = function(a, b) return a.col < b.col end
  420. is_next = function(d) return math.min(d.col, line_length - 1) > position[2] end
  421. else
  422. sort_diagnostics = function(a, b) return a.col > b.col end
  423. is_next = function(d) return math.min(d.col, line_length - 1) < position[2] end
  424. end
  425. table.sort(line_diagnostics[lnum], sort_diagnostics)
  426. if i == 0 then
  427. for _, v in pairs(line_diagnostics[lnum]) do
  428. if is_next(v) then
  429. return v
  430. end
  431. end
  432. else
  433. return line_diagnostics[lnum][1]
  434. end
  435. end
  436. end
  437. end
  438. ---@private
  439. local function diagnostic_move_pos(opts, pos)
  440. opts = opts or {}
  441. local float = vim.F.if_nil(opts.float, true)
  442. local win_id = opts.win_id or vim.api.nvim_get_current_win()
  443. if not pos then
  444. vim.api.nvim_echo({{"No more valid diagnostics to move to", "WarningMsg"}}, true, {})
  445. return
  446. end
  447. vim.api.nvim_win_call(win_id, function()
  448. -- Save position in the window's jumplist
  449. vim.cmd("normal! m'")
  450. vim.api.nvim_win_set_cursor(win_id, {pos[1] + 1, pos[2]})
  451. -- Open folds under the cursor
  452. vim.cmd("normal! zv")
  453. end)
  454. if float then
  455. local float_opts = type(float) == "table" and float or {}
  456. vim.schedule(function()
  457. M.open_float(
  458. vim.tbl_extend("keep", float_opts, {
  459. bufnr = vim.api.nvim_win_get_buf(win_id),
  460. scope = "cursor",
  461. focus = false,
  462. })
  463. )
  464. end)
  465. end
  466. end
  467. --- Configure diagnostic options globally or for a specific diagnostic
  468. --- namespace.
  469. ---
  470. --- Configuration can be specified globally, per-namespace, or ephemerally
  471. --- (i.e. only for a single call to |vim.diagnostic.set()| or
  472. --- |vim.diagnostic.show()|). Ephemeral configuration has highest priority,
  473. --- followed by namespace configuration, and finally global configuration.
  474. ---
  475. --- For example, if a user enables virtual text globally with
  476. --- <pre>
  477. --- vim.diagnostic.config({virtual_text = true})
  478. --- </pre>
  479. ---
  480. --- and a diagnostic producer sets diagnostics with
  481. --- <pre>
  482. --- vim.diagnostic.set(ns, 0, diagnostics, {virtual_text = false})
  483. --- </pre>
  484. ---
  485. --- then virtual text will not be enabled for those diagnostics.
  486. ---
  487. ---@note Each of the configuration options below accepts one of the following:
  488. --- - `false`: Disable this feature
  489. --- - `true`: Enable this feature, use default settings.
  490. --- - `table`: Enable this feature with overrides. Use an empty table to use default values.
  491. --- - `function`: Function with signature (namespace, bufnr) that returns any of the above.
  492. ---
  493. ---@param opts table|nil When omitted or "nil", retrieve the current configuration. Otherwise, a
  494. --- configuration table with the following keys:
  495. --- - underline: (default true) Use underline for diagnostics. Options:
  496. --- * severity: Only underline diagnostics matching the given severity
  497. --- |diagnostic-severity|
  498. --- - virtual_text: (default true) Use virtual text for diagnostics. If multiple diagnostics
  499. --- are set for a namespace, one prefix per diagnostic + the last diagnostic
  500. --- message are shown.
  501. --- Options:
  502. --- * severity: Only show virtual text for diagnostics matching the given
  503. --- severity |diagnostic-severity|
  504. --- * source: (boolean or string) Include the diagnostic source in virtual
  505. --- text. Use "if_many" to only show sources if there is more than
  506. --- one diagnostic source in the buffer. Otherwise, any truthy value
  507. --- means to always show the diagnostic source.
  508. --- * spacing: (number) Amount of empty spaces inserted at the beginning
  509. --- of the virtual text.
  510. --- * prefix: (string) Prepend diagnostic message with prefix.
  511. --- * format: (function) A function that takes a diagnostic as input and
  512. --- returns a string. The return value is the text used to display
  513. --- the diagnostic. Example:
  514. --- <pre>
  515. --- function(diagnostic)
  516. --- if diagnostic.severity == vim.diagnostic.severity.ERROR then
  517. --- return string.format("E: %s", diagnostic.message)
  518. --- end
  519. --- return diagnostic.message
  520. --- end
  521. --- </pre>
  522. --- - signs: (default true) Use signs for diagnostics. Options:
  523. --- * severity: Only show signs for diagnostics matching the given severity
  524. --- |diagnostic-severity|
  525. --- * priority: (number, default 10) Base priority to use for signs. When
  526. --- {severity_sort} is used, the priority of a sign is adjusted based on
  527. --- its severity. Otherwise, all signs use the same priority.
  528. --- - float: Options for floating windows. See |vim.diagnostic.open_float()|.
  529. --- - update_in_insert: (default false) Update diagnostics in Insert mode (if false,
  530. --- diagnostics are updated on InsertLeave)
  531. --- - severity_sort: (default false) Sort diagnostics by severity. This affects the order in
  532. --- which signs and virtual text are displayed. When true, higher severities
  533. --- are displayed before lower severities (e.g. ERROR is displayed before WARN).
  534. --- Options:
  535. --- * reverse: (boolean) Reverse sort order
  536. ---
  537. ---@param namespace number|nil Update the options for the given namespace. When omitted, update the
  538. --- global diagnostic options.
  539. function M.config(opts, namespace)
  540. vim.validate {
  541. opts = { opts, 't', true },
  542. namespace = { namespace, 'n', true },
  543. }
  544. local t
  545. if namespace then
  546. local ns = M.get_namespace(namespace)
  547. t = ns.opts
  548. else
  549. t = global_diagnostic_options
  550. end
  551. if not opts then
  552. -- Return current config
  553. return vim.deepcopy(t)
  554. end
  555. for k, v in pairs(opts) do
  556. t[k] = v
  557. end
  558. if namespace then
  559. for bufnr, v in pairs(diagnostic_cache) do
  560. if vim.api.nvim_buf_is_loaded(bufnr) and v[namespace] then
  561. M.show(namespace, bufnr)
  562. end
  563. end
  564. else
  565. for bufnr, v in pairs(diagnostic_cache) do
  566. if vim.api.nvim_buf_is_loaded(bufnr) then
  567. for ns in pairs(v) do
  568. M.show(ns, bufnr)
  569. end
  570. end
  571. end
  572. end
  573. end
  574. --- Set diagnostics for the given namespace and buffer.
  575. ---
  576. ---@param namespace number The diagnostic namespace
  577. ---@param bufnr number Buffer number
  578. ---@param diagnostics table A list of diagnostic items |diagnostic-structure|
  579. ---@param opts table|nil Display options to pass to |vim.diagnostic.show()|
  580. function M.set(namespace, bufnr, diagnostics, opts)
  581. vim.validate {
  582. namespace = {namespace, 'n'},
  583. bufnr = {bufnr, 'n'},
  584. diagnostics = {
  585. diagnostics,
  586. vim.tbl_islist,
  587. "a list of diagnostics",
  588. },
  589. opts = {opts, 't', true},
  590. }
  591. bufnr = get_bufnr(bufnr)
  592. if vim.tbl_isempty(diagnostics) then
  593. diagnostic_cache[bufnr][namespace] = nil
  594. else
  595. set_diagnostic_cache(namespace, bufnr, diagnostics)
  596. end
  597. if vim.api.nvim_buf_is_loaded(bufnr) then
  598. M.show(namespace, bufnr, nil, opts)
  599. end
  600. vim.api.nvim_exec_autocmds("DiagnosticChanged", {
  601. modeline = false,
  602. buffer = bufnr,
  603. })
  604. end
  605. --- Get namespace metadata.
  606. ---
  607. ---@param namespace number Diagnostic namespace
  608. ---@return table Namespace metadata
  609. function M.get_namespace(namespace)
  610. vim.validate { namespace = { namespace, 'n' } }
  611. if not all_namespaces[namespace] then
  612. local name
  613. for k, v in pairs(vim.api.nvim_get_namespaces()) do
  614. if namespace == v then
  615. name = k
  616. break
  617. end
  618. end
  619. assert(name, "namespace does not exist or is anonymous")
  620. all_namespaces[namespace] = {
  621. name = name,
  622. opts = {},
  623. user_data = {},
  624. }
  625. end
  626. return all_namespaces[namespace]
  627. end
  628. --- Get current diagnostic namespaces.
  629. ---
  630. ---@return table A list of active diagnostic namespaces |vim.diagnostic|.
  631. function M.get_namespaces()
  632. return vim.deepcopy(all_namespaces)
  633. end
  634. --- Get current diagnostics.
  635. ---
  636. ---@param bufnr number|nil Buffer number to get diagnostics from. Use 0 for
  637. --- current buffer or nil for all buffers.
  638. ---@param opts table|nil A table with the following keys:
  639. --- - namespace: (number) Limit diagnostics to the given namespace.
  640. --- - lnum: (number) Limit diagnostics to the given line number.
  641. --- - severity: See |diagnostic-severity|.
  642. ---@return table A list of diagnostic items |diagnostic-structure|.
  643. function M.get(bufnr, opts)
  644. vim.validate {
  645. bufnr = { bufnr, 'n', true },
  646. opts = { opts, 't', true },
  647. }
  648. return get_diagnostics(bufnr, opts, false)
  649. end
  650. --- Get the previous diagnostic closest to the cursor position.
  651. ---
  652. ---@param opts table See |vim.diagnostic.goto_next()|
  653. ---@return table Previous diagnostic
  654. function M.get_prev(opts)
  655. opts = opts or {}
  656. local win_id = opts.win_id or vim.api.nvim_get_current_win()
  657. local bufnr = vim.api.nvim_win_get_buf(win_id)
  658. local cursor_position = opts.cursor_position or vim.api.nvim_win_get_cursor(win_id)
  659. return next_diagnostic(cursor_position, false, bufnr, opts, opts.namespace)
  660. end
  661. --- Return the position of the previous diagnostic in the current buffer.
  662. ---
  663. ---@param opts table See |vim.diagnostic.goto_next()|
  664. ---@return table Previous diagnostic position as a (row, col) tuple.
  665. function M.get_prev_pos(opts)
  666. local prev = M.get_prev(opts)
  667. if not prev then
  668. return false
  669. end
  670. return {prev.lnum, prev.col}
  671. end
  672. --- Move to the previous diagnostic in the current buffer.
  673. ---@param opts table See |vim.diagnostic.goto_next()|
  674. function M.goto_prev(opts)
  675. return diagnostic_move_pos(
  676. opts,
  677. M.get_prev_pos(opts)
  678. )
  679. end
  680. --- Get the next diagnostic closest to the cursor position.
  681. ---
  682. ---@param opts table See |vim.diagnostic.goto_next()|
  683. ---@return table Next diagnostic
  684. function M.get_next(opts)
  685. opts = opts or {}
  686. local win_id = opts.win_id or vim.api.nvim_get_current_win()
  687. local bufnr = vim.api.nvim_win_get_buf(win_id)
  688. local cursor_position = opts.cursor_position or vim.api.nvim_win_get_cursor(win_id)
  689. return next_diagnostic(cursor_position, true, bufnr, opts, opts.namespace)
  690. end
  691. --- Return the position of the next diagnostic in the current buffer.
  692. ---
  693. ---@param opts table See |vim.diagnostic.goto_next()|
  694. ---@return table Next diagnostic position as a (row, col) tuple.
  695. function M.get_next_pos(opts)
  696. local next = M.get_next(opts)
  697. if not next then
  698. return false
  699. end
  700. return {next.lnum, next.col}
  701. end
  702. --- Move to the next diagnostic.
  703. ---
  704. ---@param opts table|nil Configuration table with the following keys:
  705. --- - namespace: (number) Only consider diagnostics from the given namespace.
  706. --- - cursor_position: (cursor position) Cursor position as a (row, col) tuple. See
  707. --- |nvim_win_get_cursor()|. Defaults to the current cursor position.
  708. --- - wrap: (boolean, default true) Whether to loop around file or not. Similar to 'wrapscan'.
  709. --- - severity: See |diagnostic-severity|.
  710. --- - float: (boolean or table, default true) If "true", call |vim.diagnostic.open_float()|
  711. --- after moving. If a table, pass the table as the {opts} parameter to
  712. --- |vim.diagnostic.open_float()|. Unless overridden, the float will show
  713. --- diagnostics at the new cursor position (as if "cursor" were passed to
  714. --- the "scope" option).
  715. --- - win_id: (number, default 0) Window ID
  716. function M.goto_next(opts)
  717. return diagnostic_move_pos(
  718. opts,
  719. M.get_next_pos(opts)
  720. )
  721. end
  722. M.handlers.signs = {
  723. show = function(namespace, bufnr, diagnostics, opts)
  724. vim.validate {
  725. namespace = {namespace, 'n'},
  726. bufnr = {bufnr, 'n'},
  727. diagnostics = {
  728. diagnostics,
  729. vim.tbl_islist,
  730. "a list of diagnostics",
  731. },
  732. opts = {opts, 't', true},
  733. }
  734. bufnr = get_bufnr(bufnr)
  735. opts = opts or {}
  736. if opts.signs and opts.signs.severity then
  737. diagnostics = filter_by_severity(opts.signs.severity, diagnostics)
  738. end
  739. define_default_signs()
  740. -- 10 is the default sign priority when none is explicitly specified
  741. local priority = opts.signs and opts.signs.priority or 10
  742. local get_priority
  743. if opts.severity_sort then
  744. if type(opts.severity_sort) == "table" and opts.severity_sort.reverse then
  745. get_priority = function(severity)
  746. return priority + (severity - vim.diagnostic.severity.ERROR)
  747. end
  748. else
  749. get_priority = function(severity)
  750. return priority + (vim.diagnostic.severity.HINT - severity)
  751. end
  752. end
  753. else
  754. get_priority = function()
  755. return priority
  756. end
  757. end
  758. local ns = M.get_namespace(namespace)
  759. if not ns.user_data.sign_group then
  760. ns.user_data.sign_group = string.format("vim.diagnostic.%s", ns.name)
  761. end
  762. local sign_group = ns.user_data.sign_group
  763. for _, diagnostic in ipairs(diagnostics) do
  764. vim.fn.sign_place(
  765. 0,
  766. sign_group,
  767. sign_highlight_map[diagnostic.severity],
  768. bufnr,
  769. {
  770. priority = get_priority(diagnostic.severity),
  771. lnum = diagnostic.lnum + 1
  772. }
  773. )
  774. end
  775. end,
  776. hide = function(namespace, bufnr)
  777. local ns = M.get_namespace(namespace)
  778. if ns.user_data.sign_group then
  779. vim.fn.sign_unplace(ns.user_data.sign_group, {buffer=bufnr})
  780. end
  781. end,
  782. }
  783. M.handlers.underline = {
  784. show = function(namespace, bufnr, diagnostics, opts)
  785. vim.validate {
  786. namespace = {namespace, 'n'},
  787. bufnr = {bufnr, 'n'},
  788. diagnostics = {
  789. diagnostics,
  790. vim.tbl_islist,
  791. "a list of diagnostics",
  792. },
  793. opts = {opts, 't', true},
  794. }
  795. bufnr = get_bufnr(bufnr)
  796. opts = opts or {}
  797. if opts.underline and opts.underline.severity then
  798. diagnostics = filter_by_severity(opts.underline.severity, diagnostics)
  799. end
  800. local ns = M.get_namespace(namespace)
  801. if not ns.user_data.underline_ns then
  802. ns.user_data.underline_ns = vim.api.nvim_create_namespace("")
  803. end
  804. local underline_ns = ns.user_data.underline_ns
  805. for _, diagnostic in ipairs(diagnostics) do
  806. local higroup = underline_highlight_map[diagnostic.severity]
  807. if higroup == nil then
  808. -- Default to error if we don't have a highlight associated
  809. higroup = underline_highlight_map.Error
  810. end
  811. vim.highlight.range(
  812. bufnr,
  813. underline_ns,
  814. higroup,
  815. { diagnostic.lnum, diagnostic.col },
  816. { diagnostic.end_lnum, diagnostic.end_col },
  817. { priority = vim.highlight.priorities.diagnostics }
  818. )
  819. end
  820. save_extmarks(underline_ns, bufnr)
  821. end,
  822. hide = function(namespace, bufnr)
  823. local ns = M.get_namespace(namespace)
  824. if ns.user_data.underline_ns then
  825. diagnostic_cache_extmarks[bufnr][ns.user_data.underline_ns] = {}
  826. vim.api.nvim_buf_clear_namespace(bufnr, ns.user_data.underline_ns, 0, -1)
  827. end
  828. end
  829. }
  830. M.handlers.virtual_text = {
  831. show = function(namespace, bufnr, diagnostics, opts)
  832. vim.validate {
  833. namespace = {namespace, 'n'},
  834. bufnr = {bufnr, 'n'},
  835. diagnostics = {
  836. diagnostics,
  837. vim.tbl_islist,
  838. "a list of diagnostics",
  839. },
  840. opts = {opts, 't', true},
  841. }
  842. bufnr = get_bufnr(bufnr)
  843. opts = opts or {}
  844. local severity
  845. if opts.virtual_text then
  846. if opts.virtual_text.format then
  847. diagnostics = reformat_diagnostics(opts.virtual_text.format, diagnostics)
  848. end
  849. if
  850. opts.virtual_text.source
  851. and (opts.virtual_text.source ~= "if_many" or count_sources(bufnr) > 1)
  852. then
  853. diagnostics = prefix_source(diagnostics)
  854. end
  855. if opts.virtual_text.severity then
  856. severity = opts.virtual_text.severity
  857. end
  858. end
  859. local ns = M.get_namespace(namespace)
  860. if not ns.user_data.virt_text_ns then
  861. ns.user_data.virt_text_ns = vim.api.nvim_create_namespace("")
  862. end
  863. local virt_text_ns = ns.user_data.virt_text_ns
  864. local buffer_line_diagnostics = diagnostic_lines(diagnostics)
  865. for line, line_diagnostics in pairs(buffer_line_diagnostics) do
  866. if severity then
  867. line_diagnostics = filter_by_severity(severity, line_diagnostics)
  868. end
  869. local virt_texts = M._get_virt_text_chunks(line_diagnostics, opts.virtual_text)
  870. if virt_texts then
  871. vim.api.nvim_buf_set_extmark(bufnr, virt_text_ns, line, 0, {
  872. hl_mode = "combine",
  873. virt_text = virt_texts,
  874. })
  875. end
  876. end
  877. save_extmarks(virt_text_ns, bufnr)
  878. end,
  879. hide = function(namespace, bufnr)
  880. local ns = M.get_namespace(namespace)
  881. if ns.user_data.virt_text_ns then
  882. diagnostic_cache_extmarks[bufnr][ns.user_data.virt_text_ns] = {}
  883. vim.api.nvim_buf_clear_namespace(bufnr, ns.user_data.virt_text_ns, 0, -1)
  884. end
  885. end,
  886. }
  887. --- Get virtual text chunks to display using |nvim_buf_set_extmark()|.
  888. ---
  889. --- Exported for backward compatibility with
  890. --- vim.lsp.diagnostic.get_virtual_text_chunks_for_line(). When that function is eventually removed,
  891. --- this can be made local.
  892. ---@private
  893. function M._get_virt_text_chunks(line_diags, opts)
  894. if #line_diags == 0 then
  895. return nil
  896. end
  897. opts = opts or {}
  898. local prefix = opts.prefix or "■"
  899. local spacing = opts.spacing or 4
  900. -- Create a little more space between virtual text and contents
  901. local virt_texts = {{string.rep(" ", spacing)}}
  902. for i = 1, #line_diags - 1 do
  903. table.insert(virt_texts, {prefix, virtual_text_highlight_map[line_diags[i].severity]})
  904. end
  905. local last = line_diags[#line_diags]
  906. -- TODO(tjdevries): Allow different servers to be shown first somehow?
  907. -- TODO(tjdevries): Display server name associated with these?
  908. if last.message then
  909. table.insert(
  910. virt_texts,
  911. {
  912. string.format("%s %s", prefix, last.message:gsub("\r", ""):gsub("\n", " ")),
  913. virtual_text_highlight_map[last.severity]
  914. }
  915. )
  916. return virt_texts
  917. end
  918. end
  919. --- Callback scheduled when leaving Insert mode.
  920. ---
  921. --- This function must be exported publicly so that it is available to be
  922. --- called from the Vimscript autocommand.
  923. ---
  924. --- See @ref schedule_display()
  925. ---
  926. ---@private
  927. function M._execute_scheduled_display(namespace, bufnr)
  928. local args = bufs_waiting_to_update[bufnr][namespace]
  929. if not args then
  930. return
  931. end
  932. -- Clear the args so we don't display unnecessarily.
  933. bufs_waiting_to_update[bufnr][namespace] = nil
  934. M.show(namespace, bufnr, nil, args)
  935. end
  936. --- Hide currently displayed diagnostics.
  937. ---
  938. --- This only clears the decorations displayed in the buffer. Diagnostics can
  939. --- be redisplayed with |vim.diagnostic.show()|. To completely remove
  940. --- diagnostics, use |vim.diagnostic.reset()|.
  941. ---
  942. --- To hide diagnostics and prevent them from re-displaying, use
  943. --- |vim.diagnostic.disable()|.
  944. ---
  945. ---@param namespace number|nil Diagnostic namespace. When omitted, hide
  946. --- diagnostics from all namespaces.
  947. ---@param bufnr number|nil Buffer number, or 0 for current buffer. When
  948. --- omitted, hide diagnostics in all buffers.
  949. function M.hide(namespace, bufnr)
  950. vim.validate {
  951. namespace = { namespace, 'n', true },
  952. bufnr = { bufnr, 'n', true },
  953. }
  954. local buffers = bufnr and {get_bufnr(bufnr)} or vim.tbl_keys(diagnostic_cache)
  955. for _, iter_bufnr in ipairs(buffers) do
  956. local namespaces = namespace and {namespace} or vim.tbl_keys(diagnostic_cache[iter_bufnr])
  957. for _, iter_namespace in ipairs(namespaces) do
  958. for _, handler in pairs(M.handlers) do
  959. if handler.hide then
  960. handler.hide(iter_namespace, iter_bufnr)
  961. end
  962. end
  963. end
  964. end
  965. end
  966. --- Display diagnostics for the given namespace and buffer.
  967. ---
  968. ---@param namespace number|nil Diagnostic namespace. When omitted, show
  969. --- diagnostics from all namespaces.
  970. ---@param bufnr number|nil Buffer number, or 0 for current buffer. When omitted, show
  971. --- diagnostics in all buffers.
  972. ---@param diagnostics table|nil The diagnostics to display. When omitted, use the
  973. --- saved diagnostics for the given namespace and
  974. --- buffer. This can be used to display a list of diagnostics
  975. --- without saving them or to display only a subset of
  976. --- diagnostics. May not be used when {namespace}
  977. --- or {bufnr} is nil.
  978. ---@param opts table|nil Display options. See |vim.diagnostic.config()|.
  979. function M.show(namespace, bufnr, diagnostics, opts)
  980. vim.validate {
  981. namespace = { namespace, 'n', true },
  982. bufnr = { bufnr, 'n', true },
  983. diagnostics = {
  984. diagnostics,
  985. function(v) return v == nil or vim.tbl_islist(v) end,
  986. "a list of diagnostics",
  987. },
  988. opts = { opts, 't', true },
  989. }
  990. if not bufnr or not namespace then
  991. assert(not diagnostics, "Cannot show diagnostics without a buffer and namespace")
  992. if not bufnr then
  993. for iter_bufnr in pairs(diagnostic_cache) do
  994. M.show(namespace, iter_bufnr, nil, opts)
  995. end
  996. else
  997. -- namespace is nil
  998. bufnr = get_bufnr(bufnr)
  999. for iter_namespace in pairs(diagnostic_cache[bufnr]) do
  1000. M.show(iter_namespace, bufnr, nil, opts)
  1001. end
  1002. end
  1003. return
  1004. end
  1005. if is_disabled(namespace, bufnr) then
  1006. return
  1007. end
  1008. M.hide(namespace, bufnr)
  1009. diagnostics = diagnostics or get_diagnostics(bufnr, {namespace=namespace}, true)
  1010. if not diagnostics or vim.tbl_isempty(diagnostics) then
  1011. return
  1012. end
  1013. opts = get_resolved_options(opts, namespace, bufnr)
  1014. if opts.update_in_insert then
  1015. clear_scheduled_display(namespace, bufnr)
  1016. else
  1017. local mode = vim.api.nvim_get_mode()
  1018. if string.sub(mode.mode, 1, 1) == 'i' then
  1019. schedule_display(namespace, bufnr, opts)
  1020. return
  1021. end
  1022. end
  1023. if vim.F.if_nil(opts.severity_sort, false) then
  1024. if type(opts.severity_sort) == "table" and opts.severity_sort.reverse then
  1025. table.sort(diagnostics, function(a, b) return a.severity < b.severity end)
  1026. else
  1027. table.sort(diagnostics, function(a, b) return a.severity > b.severity end)
  1028. end
  1029. end
  1030. for handler_name, handler in pairs(M.handlers) do
  1031. if handler.show and opts[handler_name] then
  1032. handler.show(namespace, bufnr, diagnostics, opts)
  1033. end
  1034. end
  1035. end
  1036. --- Show diagnostics in a floating window.
  1037. ---
  1038. ---@param opts table|nil Configuration table with the same keys as
  1039. --- |vim.lsp.util.open_floating_preview()| in addition to the following:
  1040. --- - bufnr: (number) Buffer number to show diagnostics from.
  1041. --- Defaults to the current buffer.
  1042. --- - namespace: (number) Limit diagnostics to the given namespace
  1043. --- - scope: (string, default "line") Show diagnostics from the whole buffer ("buffer"),
  1044. --- the current cursor line ("line"), or the current cursor position ("cursor").
  1045. --- Shorthand versions are also accepted ("c" for "cursor", "l" for "line", "b"
  1046. --- for "buffer").
  1047. --- - pos: (number or table) If {scope} is "line" or "cursor", use this position rather
  1048. --- than the cursor position. If a number, interpreted as a line number;
  1049. --- otherwise, a (row, col) tuple.
  1050. --- - severity_sort: (default false) Sort diagnostics by severity. Overrides the setting
  1051. --- from |vim.diagnostic.config()|.
  1052. --- - severity: See |diagnostic-severity|. Overrides the setting from
  1053. --- |vim.diagnostic.config()|.
  1054. --- - header: (string or table) String to use as the header for the floating window. If a
  1055. --- table, it is interpreted as a [text, hl_group] tuple. Overrides the setting
  1056. --- from |vim.diagnostic.config()|.
  1057. --- - source: (boolean or string) Include the diagnostic source in the message.
  1058. --- Use "if_many" to only show sources if there is more than one source of
  1059. --- diagnostics in the buffer. Otherwise, any truthy value means to always show
  1060. --- the diagnostic source. Overrides the setting from
  1061. --- |vim.diagnostic.config()|.
  1062. --- - format: (function) A function that takes a diagnostic as input and returns a
  1063. --- string. The return value is the text used to display the diagnostic.
  1064. --- Overrides the setting from |vim.diagnostic.config()|.
  1065. --- - prefix: (function, string, or table) Prefix each diagnostic in the floating
  1066. --- window. If a function, it must have the signature (diagnostic, i,
  1067. --- total) -> (string, string), where {i} is the index of the diagnostic
  1068. --- being evaluated and {total} is the total number of diagnostics
  1069. --- displayed in the window. The function should return a string which
  1070. --- is prepended to each diagnostic in the window as well as an
  1071. --- (optional) highlight group which will be used to highlight the
  1072. --- prefix. If {prefix} is a table, it is interpreted as a [text,
  1073. --- hl_group] tuple as in |nvim_echo()|; otherwise, if {prefix} is a
  1074. --- string, it is prepended to each diagnostic in the window with no
  1075. --- highlight.
  1076. --- Overrides the setting from |vim.diagnostic.config()|.
  1077. ---@return tuple ({float_bufnr}, {win_id})
  1078. function M.open_float(opts, ...)
  1079. -- Support old (bufnr, opts) signature
  1080. local bufnr
  1081. if opts == nil or type(opts) == "number" then
  1082. bufnr = opts
  1083. opts = ...
  1084. else
  1085. vim.validate {
  1086. opts = { opts, 't', true },
  1087. }
  1088. end
  1089. opts = opts or {}
  1090. bufnr = get_bufnr(bufnr or opts.bufnr)
  1091. do
  1092. -- Resolve options with user settings from vim.diagnostic.config
  1093. -- Unlike the other decoration functions (e.g. set_virtual_text, set_signs, etc.) `open_float`
  1094. -- does not have a dedicated table for configuration options; instead, the options are mixed in
  1095. -- with its `opts` table which also includes "keyword" parameters. So we create a dedicated
  1096. -- options table that inherits missing keys from the global configuration before resolving.
  1097. local t = global_diagnostic_options.float
  1098. local float_opts = vim.tbl_extend("keep", opts, type(t) == "table" and t or {})
  1099. opts = get_resolved_options({ float = float_opts }, nil, bufnr).float
  1100. end
  1101. local scope = ({l = "line", c = "cursor", b = "buffer"})[opts.scope] or opts.scope or "line"
  1102. local lnum, col
  1103. if scope == "line" or scope == "cursor" then
  1104. if not opts.pos then
  1105. local pos = vim.api.nvim_win_get_cursor(0)
  1106. lnum = pos[1] - 1
  1107. col = pos[2]
  1108. elseif type(opts.pos) == "number" then
  1109. lnum = opts.pos
  1110. elseif type(opts.pos) == "table" then
  1111. lnum, col = unpack(opts.pos)
  1112. else
  1113. error("Invalid value for option 'pos'")
  1114. end
  1115. elseif scope ~= "buffer" then
  1116. error("Invalid value for option 'scope'")
  1117. end
  1118. local diagnostics = get_diagnostics(bufnr, opts, true)
  1119. if scope == "line" then
  1120. diagnostics = vim.tbl_filter(function(d)
  1121. return d.lnum == lnum
  1122. end, diagnostics)
  1123. elseif scope == "cursor" then
  1124. -- LSP servers can send diagnostics with `end_col` past the length of the line
  1125. local line_length = #vim.api.nvim_buf_get_lines(bufnr, lnum, lnum + 1, true)[1]
  1126. diagnostics = vim.tbl_filter(function(d)
  1127. return d.lnum == lnum
  1128. and math.min(d.col, line_length - 1) <= col
  1129. and (d.end_col >= col or d.end_lnum > lnum)
  1130. end, diagnostics)
  1131. end
  1132. if vim.tbl_isempty(diagnostics) then
  1133. return
  1134. end
  1135. local severity_sort = vim.F.if_nil(opts.severity_sort, global_diagnostic_options.severity_sort)
  1136. if severity_sort then
  1137. if type(severity_sort) == "table" and severity_sort.reverse then
  1138. table.sort(diagnostics, function(a, b) return a.severity > b.severity end)
  1139. else
  1140. table.sort(diagnostics, function(a, b) return a.severity < b.severity end)
  1141. end
  1142. end
  1143. local lines = {}
  1144. local highlights = {}
  1145. local header = if_nil(opts.header, "Diagnostics:")
  1146. if header then
  1147. vim.validate { header = { header, function(v)
  1148. return type(v) == "string" or type(v) == "table"
  1149. end, "'string' or 'table'" } }
  1150. if type(header) == "table" then
  1151. -- Don't insert any lines for an empty string
  1152. if string.len(if_nil(header[1], "")) > 0 then
  1153. table.insert(lines, header[1])
  1154. table.insert(highlights, {0, header[2] or "Bold"})
  1155. end
  1156. elseif #header > 0 then
  1157. table.insert(lines, header)
  1158. table.insert(highlights, {0, "Bold"})
  1159. end
  1160. end
  1161. if opts.format then
  1162. diagnostics = reformat_diagnostics(opts.format, diagnostics)
  1163. end
  1164. if opts.source and (opts.source ~= "if_many" or count_sources(bufnr) > 1) then
  1165. diagnostics = prefix_source(diagnostics)
  1166. end
  1167. local prefix_opt = if_nil(opts.prefix, (scope == "cursor" and #diagnostics <= 1) and "" or function(_, i)
  1168. return string.format("%d. ", i)
  1169. end)
  1170. local prefix, prefix_hl_group
  1171. if prefix_opt then
  1172. vim.validate { prefix = { prefix_opt, function(v)
  1173. return type(v) == "string" or type(v) == "table" or type(v) == "function"
  1174. end, "'string' or 'table' or 'function'" } }
  1175. if type(prefix_opt) == "string" then
  1176. prefix, prefix_hl_group = prefix_opt, "NormalFloat"
  1177. elseif type(prefix_opt) == "table" then
  1178. prefix, prefix_hl_group = prefix_opt[1] or "", prefix_opt[2] or "NormalFloat"
  1179. end
  1180. end
  1181. for i, diagnostic in ipairs(diagnostics) do
  1182. if prefix_opt and type(prefix_opt) == "function" then
  1183. prefix, prefix_hl_group = prefix_opt(diagnostic, i, #diagnostics)
  1184. prefix, prefix_hl_group = prefix or "", prefix_hl_group or "NormalFloat"
  1185. end
  1186. local hiname = floating_highlight_map[diagnostic.severity]
  1187. local message_lines = vim.split(diagnostic.message, '\n')
  1188. table.insert(lines, prefix..message_lines[1])
  1189. table.insert(highlights, {#prefix, hiname, prefix_hl_group})
  1190. for j = 2, #message_lines do
  1191. table.insert(lines, string.rep(' ', #prefix) .. message_lines[j])
  1192. table.insert(highlights, {0, hiname})
  1193. end
  1194. end
  1195. -- Used by open_floating_preview to allow the float to be focused
  1196. if not opts.focus_id then
  1197. opts.focus_id = scope
  1198. end
  1199. local float_bufnr, winnr = require('vim.lsp.util').open_floating_preview(lines, 'plaintext', opts)
  1200. for i, hi in ipairs(highlights) do
  1201. local prefixlen, hiname, prefix_hiname = unpack(hi)
  1202. if prefix_hiname then
  1203. vim.api.nvim_buf_add_highlight(float_bufnr, -1, prefix_hiname, i-1, 0, prefixlen)
  1204. end
  1205. vim.api.nvim_buf_add_highlight(float_bufnr, -1, hiname, i-1, prefixlen, -1)
  1206. end
  1207. return float_bufnr, winnr
  1208. end
  1209. --- Remove all diagnostics from the given namespace.
  1210. ---
  1211. --- Unlike |vim.diagnostic.hide()|, this function removes all saved
  1212. --- diagnostics. They cannot be redisplayed using |vim.diagnostic.show()|. To
  1213. --- simply remove diagnostic decorations in a way that they can be
  1214. --- re-displayed, use |vim.diagnostic.hide()|.
  1215. ---
  1216. ---@param namespace number|nil Diagnostic namespace. When omitted, remove
  1217. --- diagnostics from all namespaces.
  1218. ---@param bufnr number|nil Remove diagnostics for the given buffer. When omitted,
  1219. --- diagnostics are removed for all buffers.
  1220. function M.reset(namespace, bufnr)
  1221. vim.validate {
  1222. namespace = {namespace, 'n', true},
  1223. bufnr = {bufnr, 'n', true},
  1224. }
  1225. local buffers = bufnr and {get_bufnr(bufnr)} or vim.tbl_keys(diagnostic_cache)
  1226. for _, iter_bufnr in ipairs(buffers) do
  1227. local namespaces = namespace and {namespace} or vim.tbl_keys(diagnostic_cache[iter_bufnr])
  1228. for _, iter_namespace in ipairs(namespaces) do
  1229. diagnostic_cache[iter_bufnr][iter_namespace] = nil
  1230. M.hide(iter_namespace, iter_bufnr)
  1231. end
  1232. vim.api.nvim_exec_autocmds("DiagnosticChanged", {
  1233. modeline = false,
  1234. buffer = iter_bufnr,
  1235. })
  1236. end
  1237. end
  1238. --- Add all diagnostics to the quickfix list.
  1239. ---
  1240. ---@param opts table|nil Configuration table with the following keys:
  1241. --- - namespace: (number) Only add diagnostics from the given namespace.
  1242. --- - open: (boolean, default true) Open quickfix list after setting.
  1243. --- - title: (string) Title of quickfix list. Defaults to "Diagnostics".
  1244. --- - severity: See |diagnostic-severity|.
  1245. function M.setqflist(opts)
  1246. set_list(false, opts)
  1247. end
  1248. --- Add buffer diagnostics to the location list.
  1249. ---
  1250. ---@param opts table|nil Configuration table with the following keys:
  1251. --- - namespace: (number) Only add diagnostics from the given namespace.
  1252. --- - winnr: (number, default 0) Window number to set location list for.
  1253. --- - open: (boolean, default true) Open the location list after setting.
  1254. --- - title: (string) Title of the location list. Defaults to "Diagnostics".
  1255. --- - severity: See |diagnostic-severity|.
  1256. function M.setloclist(opts)
  1257. set_list(true, opts)
  1258. end
  1259. --- Disable diagnostics in the given buffer.
  1260. ---
  1261. ---@param bufnr number|nil Buffer number, or 0 for current buffer. When
  1262. --- omitted, disable diagnostics in all buffers.
  1263. ---@param namespace number|nil Only disable diagnostics for the given namespace.
  1264. function M.disable(bufnr, namespace)
  1265. vim.validate { bufnr = {bufnr, 'n', true}, namespace = {namespace, 'n', true} }
  1266. if bufnr == nil then
  1267. if namespace == nil then
  1268. -- Disable everything (including as yet non-existing buffers and
  1269. -- namespaces) by setting diagnostic_disabled to an empty table and set
  1270. -- its metatable to always return true. This metatable is removed
  1271. -- in enable()
  1272. diagnostic_disabled = setmetatable({}, {
  1273. __index = function() return true end,
  1274. })
  1275. else
  1276. local ns = M.get_namespace(namespace)
  1277. ns.disabled = true
  1278. end
  1279. else
  1280. bufnr = get_bufnr(bufnr)
  1281. if namespace == nil then
  1282. diagnostic_disabled[bufnr] = true
  1283. else
  1284. if type(diagnostic_disabled[bufnr]) ~= "table" then
  1285. diagnostic_disabled[bufnr] = {}
  1286. end
  1287. diagnostic_disabled[bufnr][namespace] = true
  1288. end
  1289. end
  1290. M.hide(namespace, bufnr)
  1291. end
  1292. --- Enable diagnostics in the given buffer.
  1293. ---
  1294. ---@param bufnr number|nil Buffer number, or 0 for current buffer. When
  1295. --- omitted, enable diagnostics in all buffers.
  1296. ---@param namespace number|nil Only enable diagnostics for the given namespace.
  1297. function M.enable(bufnr, namespace)
  1298. vim.validate { bufnr = {bufnr, 'n', true}, namespace = {namespace, 'n', true} }
  1299. if bufnr == nil then
  1300. if namespace == nil then
  1301. -- Enable everything by setting diagnostic_disabled to an empty table
  1302. diagnostic_disabled = {}
  1303. else
  1304. local ns = M.get_namespace(namespace)
  1305. ns.disabled = false
  1306. end
  1307. else
  1308. bufnr = get_bufnr(bufnr)
  1309. if namespace == nil then
  1310. diagnostic_disabled[bufnr] = nil
  1311. else
  1312. if type(diagnostic_disabled[bufnr]) ~= "table" then
  1313. return
  1314. end
  1315. diagnostic_disabled[bufnr][namespace] = nil
  1316. end
  1317. end
  1318. M.show(namespace, bufnr)
  1319. end
  1320. --- Parse a diagnostic from a string.
  1321. ---
  1322. --- For example, consider a line of output from a linter:
  1323. --- <pre>
  1324. --- WARNING filename:27:3: Variable 'foo' does not exist
  1325. --- </pre>
  1326. ---
  1327. --- This can be parsed into a diagnostic |diagnostic-structure|
  1328. --- with:
  1329. --- <pre>
  1330. --- local s = "WARNING filename:27:3: Variable 'foo' does not exist"
  1331. --- local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$"
  1332. --- local groups = {"severity", "lnum", "col", "message"}
  1333. --- vim.diagnostic.match(s, pattern, groups, {WARNING = vim.diagnostic.WARN})
  1334. --- </pre>
  1335. ---
  1336. ---@param str string String to parse diagnostics from.
  1337. ---@param pat string Lua pattern with capture groups.
  1338. ---@param groups table List of fields in a |diagnostic-structure| to
  1339. --- associate with captures from {pat}.
  1340. ---@param severity_map table A table mapping the severity field from {groups}
  1341. --- with an item from |vim.diagnostic.severity|.
  1342. ---@param defaults table|nil Table of default values for any fields not listed in {groups}.
  1343. --- When omitted, numeric values default to 0 and "severity" defaults to
  1344. --- ERROR.
  1345. ---@return diagnostic |diagnostic-structure| or `nil` if {pat} fails to match {str}.
  1346. function M.match(str, pat, groups, severity_map, defaults)
  1347. vim.validate {
  1348. str = { str, 's' },
  1349. pat = { pat, 's' },
  1350. groups = { groups, 't' },
  1351. severity_map = { severity_map, 't', true },
  1352. defaults = { defaults, 't', true },
  1353. }
  1354. severity_map = severity_map or M.severity
  1355. local diagnostic = {}
  1356. local matches = {string.match(str, pat)}
  1357. if vim.tbl_isempty(matches) then
  1358. return
  1359. end
  1360. for i, match in ipairs(matches) do
  1361. local field = groups[i]
  1362. if field == "severity" then
  1363. match = severity_map[match]
  1364. elseif field == "lnum" or field == "end_lnum" or field == "col" or field == "end_col" then
  1365. match = assert(tonumber(match)) - 1
  1366. end
  1367. diagnostic[field] = match
  1368. end
  1369. diagnostic = vim.tbl_extend("keep", diagnostic, defaults or {})
  1370. diagnostic.severity = diagnostic.severity or M.severity.ERROR
  1371. diagnostic.col = diagnostic.col or 0
  1372. diagnostic.end_lnum = diagnostic.end_lnum or diagnostic.lnum
  1373. diagnostic.end_col = diagnostic.end_col or diagnostic.col
  1374. return diagnostic
  1375. end
  1376. local errlist_type_map = {
  1377. [M.severity.ERROR] = 'E',
  1378. [M.severity.WARN] = 'W',
  1379. [M.severity.INFO] = 'I',
  1380. [M.severity.HINT] = 'N',
  1381. }
  1382. --- Convert a list of diagnostics to a list of quickfix items that can be
  1383. --- passed to |setqflist()| or |setloclist()|.
  1384. ---
  1385. ---@param diagnostics table List of diagnostics |diagnostic-structure|.
  1386. ---@return array of quickfix list items |setqflist-what|
  1387. function M.toqflist(diagnostics)
  1388. vim.validate {
  1389. diagnostics = {
  1390. diagnostics,
  1391. vim.tbl_islist,
  1392. "a list of diagnostics",
  1393. },
  1394. }
  1395. local list = {}
  1396. for _, v in ipairs(diagnostics) do
  1397. local item = {
  1398. bufnr = v.bufnr,
  1399. lnum = v.lnum + 1,
  1400. col = v.col and (v.col + 1) or nil,
  1401. end_lnum = v.end_lnum and (v.end_lnum + 1) or nil,
  1402. end_col = v.end_col and (v.end_col + 1) or nil,
  1403. text = v.message,
  1404. type = errlist_type_map[v.severity] or 'E',
  1405. }
  1406. table.insert(list, item)
  1407. end
  1408. table.sort(list, function(a, b)
  1409. if a.bufnr == b.bufnr then
  1410. return a.lnum < b.lnum
  1411. else
  1412. return a.bufnr < b.bufnr
  1413. end
  1414. end)
  1415. return list
  1416. end
  1417. --- Convert a list of quickfix items to a list of diagnostics.
  1418. ---
  1419. ---@param list table A list of quickfix items from |getqflist()| or
  1420. --- |getloclist()|.
  1421. ---@return array of diagnostics |diagnostic-structure|
  1422. function M.fromqflist(list)
  1423. vim.validate {
  1424. list = {
  1425. list,
  1426. vim.tbl_islist,
  1427. "a list of quickfix items",
  1428. },
  1429. }
  1430. local diagnostics = {}
  1431. for _, item in ipairs(list) do
  1432. if item.valid == 1 then
  1433. local lnum = math.max(0, item.lnum - 1)
  1434. local col = math.max(0, item.col - 1)
  1435. local end_lnum = item.end_lnum > 0 and (item.end_lnum - 1) or lnum
  1436. local end_col = item.end_col > 0 and (item.end_col - 1) or col
  1437. local severity = item.type ~= "" and M.severity[item.type] or M.severity.ERROR
  1438. table.insert(diagnostics, {
  1439. bufnr = item.bufnr,
  1440. lnum = lnum,
  1441. col = col,
  1442. end_lnum = end_lnum,
  1443. end_col = end_col,
  1444. severity = severity,
  1445. message = item.text,
  1446. })
  1447. end
  1448. end
  1449. return diagnostics
  1450. end
  1451. return M