diagnostic.lua 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  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 not global_diagnostic_options[name] 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 "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 Configuration table with the following keys:
  494. --- - underline: (default true) Use underline for diagnostics. Options:
  495. --- * severity: Only underline diagnostics matching the given severity
  496. --- |diagnostic-severity|
  497. --- - virtual_text: (default true) Use virtual text for diagnostics. If multiple diagnostics
  498. --- are set for a namespace, one prefix per diagnostic + the last diagnostic
  499. --- message are shown.
  500. --- Options:
  501. --- * severity: Only show virtual text for diagnostics matching the given
  502. --- severity |diagnostic-severity|
  503. --- * source: (boolean or string) Include the diagnostic source in virtual
  504. --- text. Use "if_many" to only show sources if there is more than
  505. --- one diagnostic source in the buffer. Otherwise, any truthy value
  506. --- means to always show the diagnostic source.
  507. --- * spacing: (number) Amount of empty spaces inserted at the beginning
  508. --- of the virtual text.
  509. --- * prefix: (string) Prepend diagnostic message with prefix.
  510. --- * format: (function) A function that takes a diagnostic as input and
  511. --- returns a string. The return value is the text used to display
  512. --- the diagnostic. Example:
  513. --- <pre>
  514. --- function(diagnostic)
  515. --- if diagnostic.severity == vim.diagnostic.severity.ERROR then
  516. --- return string.format("E: %s", diagnostic.message)
  517. --- end
  518. --- return diagnostic.message
  519. --- end
  520. --- </pre>
  521. --- - signs: (default true) Use signs for diagnostics. Options:
  522. --- * severity: Only show signs for diagnostics matching the given severity
  523. --- |diagnostic-severity|
  524. --- * priority: (number, default 10) Base priority to use for signs. When
  525. --- {severity_sort} is used, the priority of a sign is adjusted based on
  526. --- its severity. Otherwise, all signs use the same priority.
  527. --- - float: Options for floating windows. See |vim.diagnostic.open_float()|.
  528. --- - update_in_insert: (default false) Update diagnostics in Insert mode (if false,
  529. --- diagnostics are updated on InsertLeave)
  530. --- - severity_sort: (default false) Sort diagnostics by severity. This affects the order in
  531. --- which signs and virtual text are displayed. When true, higher severities
  532. --- are displayed before lower severities (e.g. ERROR is displayed before WARN).
  533. --- Options:
  534. --- * reverse: (boolean) Reverse sort order
  535. ---
  536. ---@param namespace number|nil Update the options for the given namespace. When omitted, update the
  537. --- global diagnostic options.
  538. function M.config(opts, namespace)
  539. vim.validate {
  540. opts = { opts, 't' },
  541. namespace = { namespace, 'n', true },
  542. }
  543. local t
  544. if namespace then
  545. local ns = M.get_namespace(namespace)
  546. t = ns.opts
  547. else
  548. t = global_diagnostic_options
  549. end
  550. for opt in pairs(global_diagnostic_options) do
  551. if opts[opt] ~= nil then
  552. t[opt] = opts[opt]
  553. end
  554. end
  555. if namespace then
  556. for bufnr, v in pairs(diagnostic_cache) do
  557. if vim.api.nvim_buf_is_loaded(bufnr) and v[namespace] then
  558. M.show(namespace, bufnr)
  559. end
  560. end
  561. else
  562. for bufnr, v in pairs(diagnostic_cache) do
  563. if vim.api.nvim_buf_is_loaded(bufnr) then
  564. for ns in pairs(v) do
  565. M.show(ns, bufnr)
  566. end
  567. end
  568. end
  569. end
  570. end
  571. --- Set diagnostics for the given namespace and buffer.
  572. ---
  573. ---@param namespace number The diagnostic namespace
  574. ---@param bufnr number Buffer number
  575. ---@param diagnostics table A list of diagnostic items |diagnostic-structure|
  576. ---@param opts table|nil Display options to pass to |vim.diagnostic.show()|
  577. function M.set(namespace, bufnr, diagnostics, opts)
  578. vim.validate {
  579. namespace = {namespace, 'n'},
  580. bufnr = {bufnr, 'n'},
  581. diagnostics = {diagnostics, 't'},
  582. opts = {opts, 't', true},
  583. }
  584. bufnr = get_bufnr(bufnr)
  585. if vim.tbl_isempty(diagnostics) then
  586. diagnostic_cache[bufnr][namespace] = nil
  587. else
  588. set_diagnostic_cache(namespace, bufnr, diagnostics)
  589. end
  590. if vim.api.nvim_buf_is_loaded(bufnr) then
  591. M.show(namespace, bufnr, nil, opts)
  592. end
  593. vim.api.nvim_buf_call(bufnr, function()
  594. vim.api.nvim_command(
  595. string.format(
  596. "doautocmd <nomodeline> DiagnosticChanged %s",
  597. vim.fn.fnameescape(vim.api.nvim_buf_get_name(bufnr))
  598. )
  599. )
  600. end)
  601. end
  602. --- Get namespace metadata.
  603. ---
  604. ---@param namespace number Diagnostic namespace
  605. ---@return table Namespace metadata
  606. function M.get_namespace(namespace)
  607. vim.validate { namespace = { namespace, 'n' } }
  608. if not all_namespaces[namespace] then
  609. local name
  610. for k, v in pairs(vim.api.nvim_get_namespaces()) do
  611. if namespace == v then
  612. name = k
  613. break
  614. end
  615. end
  616. assert(name, "namespace does not exist or is anonymous")
  617. all_namespaces[namespace] = {
  618. name = name,
  619. opts = {},
  620. user_data = {},
  621. }
  622. end
  623. return all_namespaces[namespace]
  624. end
  625. --- Get current diagnostic namespaces.
  626. ---
  627. ---@return table A list of active diagnostic namespaces |vim.diagnostic|.
  628. function M.get_namespaces()
  629. return vim.deepcopy(all_namespaces)
  630. end
  631. --- Get current diagnostics.
  632. ---
  633. ---@param bufnr number|nil Buffer number to get diagnostics from. Use 0 for
  634. --- current buffer or nil for all buffers.
  635. ---@param opts table|nil A table with the following keys:
  636. --- - namespace: (number) Limit diagnostics to the given namespace.
  637. --- - lnum: (number) Limit diagnostics to the given line number.
  638. --- - severity: See |diagnostic-severity|.
  639. ---@return table A list of diagnostic items |diagnostic-structure|.
  640. function M.get(bufnr, opts)
  641. vim.validate {
  642. bufnr = { bufnr, 'n', true },
  643. opts = { opts, 't', true },
  644. }
  645. return get_diagnostics(bufnr, opts, false)
  646. end
  647. --- Get the previous diagnostic closest to the cursor position.
  648. ---
  649. ---@param opts table See |vim.diagnostic.goto_next()|
  650. ---@return table Previous diagnostic
  651. function M.get_prev(opts)
  652. opts = opts or {}
  653. local win_id = opts.win_id or vim.api.nvim_get_current_win()
  654. local bufnr = vim.api.nvim_win_get_buf(win_id)
  655. local cursor_position = opts.cursor_position or vim.api.nvim_win_get_cursor(win_id)
  656. return next_diagnostic(cursor_position, false, bufnr, opts, opts.namespace)
  657. end
  658. --- Return the position of the previous diagnostic in the current buffer.
  659. ---
  660. ---@param opts table See |vim.diagnostic.goto_next()|
  661. ---@return table Previous diagnostic position as a (row, col) tuple.
  662. function M.get_prev_pos(opts)
  663. local prev = M.get_prev(opts)
  664. if not prev then
  665. return false
  666. end
  667. return {prev.lnum, prev.col}
  668. end
  669. --- Move to the previous diagnostic in the current buffer.
  670. ---@param opts table See |vim.diagnostic.goto_next()|
  671. function M.goto_prev(opts)
  672. return diagnostic_move_pos(
  673. opts,
  674. M.get_prev_pos(opts)
  675. )
  676. end
  677. --- Get the next diagnostic closest to the cursor position.
  678. ---
  679. ---@param opts table See |vim.diagnostic.goto_next()|
  680. ---@return table Next diagnostic
  681. function M.get_next(opts)
  682. opts = opts or {}
  683. local win_id = opts.win_id or vim.api.nvim_get_current_win()
  684. local bufnr = vim.api.nvim_win_get_buf(win_id)
  685. local cursor_position = opts.cursor_position or vim.api.nvim_win_get_cursor(win_id)
  686. return next_diagnostic(cursor_position, true, bufnr, opts, opts.namespace)
  687. end
  688. --- Return the position of the next diagnostic in the current buffer.
  689. ---
  690. ---@param opts table See |vim.diagnostic.goto_next()|
  691. ---@return table Next diagnostic position as a (row, col) tuple.
  692. function M.get_next_pos(opts)
  693. local next = M.get_next(opts)
  694. if not next then
  695. return false
  696. end
  697. return {next.lnum, next.col}
  698. end
  699. --- Move to the next diagnostic.
  700. ---
  701. ---@param opts table|nil Configuration table with the following keys:
  702. --- - namespace: (number) Only consider diagnostics from the given namespace.
  703. --- - cursor_position: (cursor position) Cursor position as a (row, col) tuple. See
  704. --- |nvim_win_get_cursor()|. Defaults to the current cursor position.
  705. --- - wrap: (boolean, default true) Whether to loop around file or not. Similar to 'wrapscan'.
  706. --- - severity: See |diagnostic-severity|.
  707. --- - float: (boolean or table, default true) If "true", call |vim.diagnostic.open_float()|
  708. --- after moving. If a table, pass the table as the {opts} parameter to
  709. --- |vim.diagnostic.open_float()|. Unless overridden, the float will show
  710. --- diagnostics at the new cursor position (as if "cursor" were passed to
  711. --- the "scope" option).
  712. --- - win_id: (number, default 0) Window ID
  713. function M.goto_next(opts)
  714. return diagnostic_move_pos(
  715. opts,
  716. M.get_next_pos(opts)
  717. )
  718. end
  719. M.handlers.signs = {
  720. show = function(namespace, bufnr, diagnostics, opts)
  721. vim.validate {
  722. namespace = {namespace, 'n'},
  723. bufnr = {bufnr, 'n'},
  724. diagnostics = {diagnostics, 't'},
  725. opts = {opts, 't', true},
  726. }
  727. bufnr = get_bufnr(bufnr)
  728. if opts.signs and opts.signs.severity then
  729. diagnostics = filter_by_severity(opts.signs.severity, diagnostics)
  730. end
  731. define_default_signs()
  732. -- 10 is the default sign priority when none is explicitly specified
  733. local priority = opts.signs and opts.signs.priority or 10
  734. local get_priority
  735. if opts.severity_sort then
  736. if type(opts.severity_sort) == "table" and opts.severity_sort.reverse then
  737. get_priority = function(severity)
  738. return priority + (severity - vim.diagnostic.severity.ERROR)
  739. end
  740. else
  741. get_priority = function(severity)
  742. return priority + (vim.diagnostic.severity.HINT - severity)
  743. end
  744. end
  745. else
  746. get_priority = function()
  747. return priority
  748. end
  749. end
  750. local ns = M.get_namespace(namespace)
  751. if not ns.user_data.sign_group then
  752. ns.user_data.sign_group = string.format("vim.diagnostic.%s", ns.name)
  753. end
  754. local sign_group = ns.user_data.sign_group
  755. for _, diagnostic in ipairs(diagnostics) do
  756. vim.fn.sign_place(
  757. 0,
  758. sign_group,
  759. sign_highlight_map[diagnostic.severity],
  760. bufnr,
  761. {
  762. priority = get_priority(diagnostic.severity),
  763. lnum = diagnostic.lnum + 1
  764. }
  765. )
  766. end
  767. end,
  768. hide = function(namespace, bufnr)
  769. local ns = M.get_namespace(namespace)
  770. if ns.user_data.sign_group then
  771. vim.fn.sign_unplace(ns.user_data.sign_group, {buffer=bufnr})
  772. end
  773. end,
  774. }
  775. M.handlers.underline = {
  776. show = function(namespace, bufnr, diagnostics, opts)
  777. vim.validate {
  778. namespace = {namespace, 'n'},
  779. bufnr = {bufnr, 'n'},
  780. diagnostics = {diagnostics, 't'},
  781. opts = {opts, 't', true},
  782. }
  783. bufnr = get_bufnr(bufnr)
  784. if opts.underline and opts.underline.severity then
  785. diagnostics = filter_by_severity(opts.underline.severity, diagnostics)
  786. end
  787. local ns = M.get_namespace(namespace)
  788. if not ns.user_data.underline_ns then
  789. ns.user_data.underline_ns = vim.api.nvim_create_namespace("")
  790. end
  791. local underline_ns = ns.user_data.underline_ns
  792. for _, diagnostic in ipairs(diagnostics) do
  793. local higroup = underline_highlight_map[diagnostic.severity]
  794. if higroup == nil then
  795. -- Default to error if we don't have a highlight associated
  796. higroup = underline_highlight_map.Error
  797. end
  798. vim.highlight.range(
  799. bufnr,
  800. underline_ns,
  801. higroup,
  802. { diagnostic.lnum, diagnostic.col },
  803. { diagnostic.end_lnum, diagnostic.end_col }
  804. )
  805. end
  806. save_extmarks(underline_ns, bufnr)
  807. end,
  808. hide = function(namespace, bufnr)
  809. local ns = M.get_namespace(namespace)
  810. if ns.user_data.underline_ns then
  811. diagnostic_cache_extmarks[bufnr][ns.user_data.underline_ns] = {}
  812. vim.api.nvim_buf_clear_namespace(bufnr, ns.user_data.underline_ns, 0, -1)
  813. end
  814. end
  815. }
  816. M.handlers.virtual_text = {
  817. show = function(namespace, bufnr, diagnostics, opts)
  818. vim.validate {
  819. namespace = {namespace, 'n'},
  820. bufnr = {bufnr, 'n'},
  821. diagnostics = {diagnostics, 't'},
  822. opts = {opts, 't', true},
  823. }
  824. bufnr = get_bufnr(bufnr)
  825. local severity
  826. if opts.virtual_text then
  827. if opts.virtual_text.format then
  828. diagnostics = reformat_diagnostics(opts.virtual_text.format, diagnostics)
  829. end
  830. if
  831. opts.virtual_text.source
  832. and (opts.virtual_text.source ~= "if_many" or count_sources(bufnr) > 1)
  833. then
  834. diagnostics = prefix_source(diagnostics)
  835. end
  836. if opts.virtual_text.severity then
  837. severity = opts.virtual_text.severity
  838. end
  839. end
  840. local ns = M.get_namespace(namespace)
  841. if not ns.user_data.virt_text_ns then
  842. ns.user_data.virt_text_ns = vim.api.nvim_create_namespace("")
  843. end
  844. local virt_text_ns = ns.user_data.virt_text_ns
  845. local buffer_line_diagnostics = diagnostic_lines(diagnostics)
  846. for line, line_diagnostics in pairs(buffer_line_diagnostics) do
  847. if severity then
  848. line_diagnostics = filter_by_severity(severity, line_diagnostics)
  849. end
  850. local virt_texts = M._get_virt_text_chunks(line_diagnostics, opts.virtual_text)
  851. if virt_texts then
  852. vim.api.nvim_buf_set_extmark(bufnr, virt_text_ns, line, 0, {
  853. hl_mode = "combine",
  854. virt_text = virt_texts,
  855. })
  856. end
  857. end
  858. save_extmarks(virt_text_ns, bufnr)
  859. end,
  860. hide = function(namespace, bufnr)
  861. local ns = M.get_namespace(namespace)
  862. if ns.user_data.virt_text_ns then
  863. diagnostic_cache_extmarks[bufnr][ns.user_data.virt_text_ns] = {}
  864. vim.api.nvim_buf_clear_namespace(bufnr, ns.user_data.virt_text_ns, 0, -1)
  865. end
  866. end,
  867. }
  868. --- Get virtual text chunks to display using |nvim_buf_set_extmark()|.
  869. ---
  870. --- Exported for backward compatibility with
  871. --- vim.lsp.diagnostic.get_virtual_text_chunks_for_line(). When that function is eventually removed,
  872. --- this can be made local.
  873. ---@private
  874. function M._get_virt_text_chunks(line_diags, opts)
  875. if #line_diags == 0 then
  876. return nil
  877. end
  878. opts = opts or {}
  879. local prefix = opts.prefix or "■"
  880. local spacing = opts.spacing or 4
  881. -- Create a little more space between virtual text and contents
  882. local virt_texts = {{string.rep(" ", spacing)}}
  883. for i = 1, #line_diags - 1 do
  884. table.insert(virt_texts, {prefix, virtual_text_highlight_map[line_diags[i].severity]})
  885. end
  886. local last = line_diags[#line_diags]
  887. -- TODO(tjdevries): Allow different servers to be shown first somehow?
  888. -- TODO(tjdevries): Display server name associated with these?
  889. if last.message then
  890. table.insert(
  891. virt_texts,
  892. {
  893. string.format("%s %s", prefix, last.message:gsub("\r", ""):gsub("\n", " ")),
  894. virtual_text_highlight_map[last.severity]
  895. }
  896. )
  897. return virt_texts
  898. end
  899. end
  900. --- Callback scheduled when leaving Insert mode.
  901. ---
  902. --- This function must be exported publicly so that it is available to be
  903. --- called from the Vimscript autocommand.
  904. ---
  905. --- See @ref schedule_display()
  906. ---
  907. ---@private
  908. function M._execute_scheduled_display(namespace, bufnr)
  909. local args = bufs_waiting_to_update[bufnr][namespace]
  910. if not args then
  911. return
  912. end
  913. -- Clear the args so we don't display unnecessarily.
  914. bufs_waiting_to_update[bufnr][namespace] = nil
  915. M.show(namespace, bufnr, nil, args)
  916. end
  917. --- Hide currently displayed diagnostics.
  918. ---
  919. --- This only clears the decorations displayed in the buffer. Diagnostics can
  920. --- be redisplayed with |vim.diagnostic.show()|. To completely remove
  921. --- diagnostics, use |vim.diagnostic.reset()|.
  922. ---
  923. --- To hide diagnostics and prevent them from re-displaying, use
  924. --- |vim.diagnostic.disable()|.
  925. ---
  926. ---@param namespace number|nil Diagnostic namespace. When omitted, hide
  927. --- diagnostics from all namespaces.
  928. ---@param bufnr number|nil Buffer number, or 0 for current buffer. When
  929. --- omitted, hide diagnostics in all buffers.
  930. function M.hide(namespace, bufnr)
  931. vim.validate {
  932. namespace = { namespace, 'n', true },
  933. bufnr = { bufnr, 'n', true },
  934. }
  935. local buffers = bufnr and {get_bufnr(bufnr)} or vim.tbl_keys(diagnostic_cache)
  936. for _, iter_bufnr in ipairs(buffers) do
  937. local namespaces = namespace and {namespace} or vim.tbl_keys(diagnostic_cache[iter_bufnr])
  938. for _, iter_namespace in ipairs(namespaces) do
  939. for _, handler in pairs(M.handlers) do
  940. if handler.hide then
  941. handler.hide(iter_namespace, iter_bufnr)
  942. end
  943. end
  944. end
  945. end
  946. end
  947. --- Display diagnostics for the given namespace and buffer.
  948. ---
  949. ---@param namespace number|nil Diagnostic namespace. When omitted, show
  950. --- diagnostics from all namespaces.
  951. ---@param bufnr number|nil Buffer number, or 0 for current buffer. When omitted, show
  952. --- diagnostics in all buffers.
  953. ---@param diagnostics table|nil The diagnostics to display. When omitted, use the
  954. --- saved diagnostics for the given namespace and
  955. --- buffer. This can be used to display a list of diagnostics
  956. --- without saving them or to display only a subset of
  957. --- diagnostics. May not be used when {namespace}
  958. --- or {bufnr} is nil.
  959. ---@param opts table|nil Display options. See |vim.diagnostic.config()|.
  960. function M.show(namespace, bufnr, diagnostics, opts)
  961. vim.validate {
  962. namespace = { namespace, 'n', true },
  963. bufnr = { bufnr, 'n', true },
  964. diagnostics = { diagnostics, 't', true },
  965. opts = { opts, 't', true },
  966. }
  967. if not bufnr or not namespace then
  968. assert(not diagnostics, "Cannot show diagnostics without a buffer and namespace")
  969. if not bufnr then
  970. for iter_bufnr in pairs(diagnostic_cache) do
  971. M.show(namespace, iter_bufnr, nil, opts)
  972. end
  973. else
  974. -- namespace is nil
  975. bufnr = get_bufnr(bufnr)
  976. for iter_namespace in pairs(diagnostic_cache[bufnr]) do
  977. M.show(iter_namespace, bufnr, nil, opts)
  978. end
  979. end
  980. return
  981. end
  982. if is_disabled(namespace, bufnr) then
  983. return
  984. end
  985. M.hide(namespace, bufnr)
  986. diagnostics = diagnostics or get_diagnostics(bufnr, {namespace=namespace}, true)
  987. if not diagnostics or vim.tbl_isempty(diagnostics) then
  988. return
  989. end
  990. opts = get_resolved_options(opts, namespace, bufnr)
  991. if opts.update_in_insert then
  992. clear_scheduled_display(namespace, bufnr)
  993. else
  994. local mode = vim.api.nvim_get_mode()
  995. if string.sub(mode.mode, 1, 1) == 'i' then
  996. schedule_display(namespace, bufnr, opts)
  997. return
  998. end
  999. end
  1000. if vim.F.if_nil(opts.severity_sort, false) then
  1001. if type(opts.severity_sort) == "table" and opts.severity_sort.reverse then
  1002. table.sort(diagnostics, function(a, b) return a.severity < b.severity end)
  1003. else
  1004. table.sort(diagnostics, function(a, b) return a.severity > b.severity end)
  1005. end
  1006. end
  1007. for handler_name, handler in pairs(M.handlers) do
  1008. if handler.show and opts[handler_name] then
  1009. handler.show(namespace, bufnr, diagnostics, opts)
  1010. end
  1011. end
  1012. end
  1013. --- Show diagnostics in a floating window.
  1014. ---
  1015. ---@param opts table|nil Configuration table with the same keys as
  1016. --- |vim.lsp.util.open_floating_preview()| in addition to the following:
  1017. --- - bufnr: (number) Buffer number to show diagnostics from.
  1018. --- Defaults to the current buffer.
  1019. --- - namespace: (number) Limit diagnostics to the given namespace
  1020. --- - scope: (string, default "line") Show diagnostics from the whole buffer ("buffer"),
  1021. --- the current cursor line ("line"), or the current cursor position ("cursor").
  1022. --- Shorthand versions are also accepted ("c" for "cursor", "l" for "line", "b"
  1023. --- for "buffer").
  1024. --- - pos: (number or table) If {scope} is "line" or "cursor", use this position rather
  1025. --- than the cursor position. If a number, interpreted as a line number;
  1026. --- otherwise, a (row, col) tuple.
  1027. --- - severity_sort: (default false) Sort diagnostics by severity. Overrides the setting
  1028. --- from |vim.diagnostic.config()|.
  1029. --- - severity: See |diagnostic-severity|. Overrides the setting from
  1030. --- |vim.diagnostic.config()|.
  1031. --- - header: (string or table) String to use as the header for the floating window. If a
  1032. --- table, it is interpreted as a [text, hl_group] tuple. Overrides the setting
  1033. --- from |vim.diagnostic.config()|.
  1034. --- - source: (boolean or string) Include the diagnostic source in the message.
  1035. --- Use "if_many" to only show sources if there is more than one source of
  1036. --- diagnostics in the buffer. Otherwise, any truthy value means to always show
  1037. --- the diagnostic source. Overrides the setting from
  1038. --- |vim.diagnostic.config()|.
  1039. --- - format: (function) A function that takes a diagnostic as input and returns a
  1040. --- string. The return value is the text used to display the diagnostic.
  1041. --- Overrides the setting from |vim.diagnostic.config()|.
  1042. --- - prefix: (function, string, or table) Prefix each diagnostic in the floating
  1043. --- window. If a function, it must have the signature (diagnostic, i,
  1044. --- total) -> (string, string), where {i} is the index of the diagnostic
  1045. --- being evaluated and {total} is the total number of diagnostics
  1046. --- displayed in the window. The function should return a string which
  1047. --- is prepended to each diagnostic in the window as well as an
  1048. --- (optional) highlight group which will be used to highlight the
  1049. --- prefix. If {prefix} is a table, it is interpreted as a [text,
  1050. --- hl_group] tuple as in |nvim_echo()|; otherwise, if {prefix} is a
  1051. --- string, it is prepended to each diagnostic in the window with no
  1052. --- highlight.
  1053. --- Overrides the setting from |vim.diagnostic.config()|.
  1054. ---@return tuple ({float_bufnr}, {win_id})
  1055. function M.open_float(opts, ...)
  1056. -- Support old (bufnr, opts) signature
  1057. local bufnr
  1058. if opts == nil or type(opts) == "number" then
  1059. bufnr = opts
  1060. opts = ...
  1061. else
  1062. vim.validate {
  1063. opts = { opts, 't', true },
  1064. }
  1065. end
  1066. opts = opts or {}
  1067. bufnr = get_bufnr(bufnr or opts.bufnr)
  1068. local scope = ({l = "line", c = "cursor", b = "buffer"})[opts.scope] or opts.scope or "line"
  1069. local lnum, col
  1070. if scope == "line" or scope == "cursor" then
  1071. if not opts.pos then
  1072. local pos = vim.api.nvim_win_get_cursor(0)
  1073. lnum = pos[1] - 1
  1074. col = pos[2]
  1075. elseif type(opts.pos) == "number" then
  1076. lnum = opts.pos
  1077. elseif type(opts.pos) == "table" then
  1078. lnum, col = unpack(opts.pos)
  1079. else
  1080. error("Invalid value for option 'pos'")
  1081. end
  1082. elseif scope ~= "buffer" then
  1083. error("Invalid value for option 'scope'")
  1084. end
  1085. do
  1086. -- Resolve options with user settings from vim.diagnostic.config
  1087. -- Unlike the other decoration functions (e.g. set_virtual_text, set_signs, etc.) `open_float`
  1088. -- does not have a dedicated table for configuration options; instead, the options are mixed in
  1089. -- with its `opts` table which also includes "keyword" parameters. So we create a dedicated
  1090. -- options table that inherits missing keys from the global configuration before resolving.
  1091. local t = global_diagnostic_options.float
  1092. local float_opts = vim.tbl_extend("keep", opts, type(t) == "table" and t or {})
  1093. opts = get_resolved_options({ float = float_opts }, nil, bufnr).float
  1094. end
  1095. local diagnostics = get_diagnostics(bufnr, opts, true)
  1096. if scope == "line" then
  1097. diagnostics = vim.tbl_filter(function(d)
  1098. return d.lnum == lnum
  1099. end, diagnostics)
  1100. elseif scope == "cursor" then
  1101. -- LSP servers can send diagnostics with `end_col` past the length of the line
  1102. local line_length = #vim.api.nvim_buf_get_lines(bufnr, lnum, lnum + 1, true)[1]
  1103. diagnostics = vim.tbl_filter(function(d)
  1104. return d.lnum == lnum
  1105. and math.min(d.col, line_length - 1) <= col
  1106. and (d.end_col >= col or d.end_lnum > lnum)
  1107. end, diagnostics)
  1108. end
  1109. if vim.tbl_isempty(diagnostics) then
  1110. return
  1111. end
  1112. local severity_sort = vim.F.if_nil(opts.severity_sort, global_diagnostic_options.severity_sort)
  1113. if severity_sort then
  1114. if type(severity_sort) == "table" and severity_sort.reverse then
  1115. table.sort(diagnostics, function(a, b) return a.severity > b.severity end)
  1116. else
  1117. table.sort(diagnostics, function(a, b) return a.severity < b.severity end)
  1118. end
  1119. end
  1120. local lines = {}
  1121. local highlights = {}
  1122. local header = if_nil(opts.header, "Diagnostics:")
  1123. if header then
  1124. vim.validate { header = { header, function(v)
  1125. return type(v) == "string" or type(v) == "table"
  1126. end, "'string' or 'table'" } }
  1127. if type(header) == "table" then
  1128. -- Don't insert any lines for an empty string
  1129. if string.len(if_nil(header[1], "")) > 0 then
  1130. table.insert(lines, header[1])
  1131. table.insert(highlights, {0, header[2] or "Bold"})
  1132. end
  1133. elseif #header > 0 then
  1134. table.insert(lines, header)
  1135. table.insert(highlights, {0, "Bold"})
  1136. end
  1137. end
  1138. if opts.format then
  1139. diagnostics = reformat_diagnostics(opts.format, diagnostics)
  1140. end
  1141. if opts.source and (opts.source ~= "if_many" or count_sources(bufnr) > 1) then
  1142. diagnostics = prefix_source(diagnostics)
  1143. end
  1144. local prefix_opt = if_nil(opts.prefix, (scope == "cursor" and #diagnostics <= 1) and "" or function(_, i)
  1145. return string.format("%d. ", i)
  1146. end)
  1147. local prefix, prefix_hl_group
  1148. if prefix_opt then
  1149. vim.validate { prefix = { prefix_opt, function(v)
  1150. return type(v) == "string" or type(v) == "table" or type(v) == "function"
  1151. end, "'string' or 'table' or 'function'" } }
  1152. if type(prefix_opt) == "string" then
  1153. prefix, prefix_hl_group = prefix_opt, "NormalFloat"
  1154. elseif type(prefix_opt) == "table" then
  1155. prefix, prefix_hl_group = prefix_opt[1] or "", prefix_opt[2] or "NormalFloat"
  1156. end
  1157. end
  1158. for i, diagnostic in ipairs(diagnostics) do
  1159. if prefix_opt and type(prefix_opt) == "function" then
  1160. prefix, prefix_hl_group = prefix_opt(diagnostic, i, #diagnostics)
  1161. prefix, prefix_hl_group = prefix or "", prefix_hl_group or "NormalFloat"
  1162. end
  1163. local hiname = floating_highlight_map[diagnostic.severity]
  1164. local message_lines = vim.split(diagnostic.message, '\n')
  1165. table.insert(lines, prefix..message_lines[1])
  1166. table.insert(highlights, {#prefix, hiname, prefix_hl_group})
  1167. for j = 2, #message_lines do
  1168. table.insert(lines, string.rep(' ', #prefix) .. message_lines[j])
  1169. table.insert(highlights, {0, hiname})
  1170. end
  1171. end
  1172. -- Used by open_floating_preview to allow the float to be focused
  1173. if not opts.focus_id then
  1174. opts.focus_id = scope
  1175. end
  1176. local float_bufnr, winnr = require('vim.lsp.util').open_floating_preview(lines, 'plaintext', opts)
  1177. for i, hi in ipairs(highlights) do
  1178. local prefixlen, hiname, prefix_hiname = unpack(hi)
  1179. if prefix_hiname then
  1180. vim.api.nvim_buf_add_highlight(float_bufnr, -1, prefix_hiname, i-1, 0, prefixlen)
  1181. end
  1182. vim.api.nvim_buf_add_highlight(float_bufnr, -1, hiname, i-1, prefixlen, -1)
  1183. end
  1184. return float_bufnr, winnr
  1185. end
  1186. --- Remove all diagnostics from the given namespace.
  1187. ---
  1188. --- Unlike |vim.diagnostic.hide()|, this function removes all saved
  1189. --- diagnostics. They cannot be redisplayed using |vim.diagnostic.show()|. To
  1190. --- simply remove diagnostic decorations in a way that they can be
  1191. --- re-displayed, use |vim.diagnostic.hide()|.
  1192. ---
  1193. ---@param namespace number|nil Diagnostic namespace. When omitted, remove
  1194. --- diagnostics from all namespaces.
  1195. ---@param bufnr number|nil Remove diagnostics for the given buffer. When omitted,
  1196. --- diagnostics are removed for all buffers.
  1197. function M.reset(namespace, bufnr)
  1198. vim.validate {
  1199. namespace = {namespace, 'n', true},
  1200. bufnr = {bufnr, 'n', true},
  1201. }
  1202. local buffers = bufnr and {get_bufnr(bufnr)} or vim.tbl_keys(diagnostic_cache)
  1203. for _, iter_bufnr in ipairs(buffers) do
  1204. local namespaces = namespace and {namespace} or vim.tbl_keys(diagnostic_cache[iter_bufnr])
  1205. for _, iter_namespace in ipairs(namespaces) do
  1206. diagnostic_cache[iter_bufnr][iter_namespace] = nil
  1207. M.hide(iter_namespace, iter_bufnr)
  1208. end
  1209. end
  1210. vim.api.nvim_buf_call(bufnr, function()
  1211. vim.api.nvim_command(
  1212. string.format(
  1213. "doautocmd <nomodeline> DiagnosticChanged %s",
  1214. vim.fn.fnameescape(vim.api.nvim_buf_get_name(bufnr))
  1215. )
  1216. )
  1217. end)
  1218. end
  1219. --- Add all diagnostics to the quickfix list.
  1220. ---
  1221. ---@param opts table|nil Configuration table with the following keys:
  1222. --- - namespace: (number) Only add diagnostics from the given namespace.
  1223. --- - open: (boolean, default true) Open quickfix list after setting.
  1224. --- - title: (string) Title of quickfix list. Defaults to "Diagnostics".
  1225. --- - severity: See |diagnostic-severity|.
  1226. function M.setqflist(opts)
  1227. set_list(false, opts)
  1228. end
  1229. --- Add buffer diagnostics to the location list.
  1230. ---
  1231. ---@param opts table|nil Configuration table with the following keys:
  1232. --- - namespace: (number) Only add diagnostics from the given namespace.
  1233. --- - winnr: (number, default 0) Window number to set location list for.
  1234. --- - open: (boolean, default true) Open the location list after setting.
  1235. --- - title: (string) Title of the location list. Defaults to "Diagnostics".
  1236. --- - severity: See |diagnostic-severity|.
  1237. function M.setloclist(opts)
  1238. set_list(true, opts)
  1239. end
  1240. --- Disable diagnostics in the given buffer.
  1241. ---
  1242. ---@param bufnr number|nil Buffer number, or 0 for current buffer. When
  1243. --- omitted, disable diagnostics in all buffers.
  1244. ---@param namespace number|nil Only disable diagnostics for the given namespace.
  1245. function M.disable(bufnr, namespace)
  1246. vim.validate { bufnr = {bufnr, 'n', true}, namespace = {namespace, 'n', true} }
  1247. if bufnr == nil then
  1248. if namespace == nil then
  1249. -- Disable everything (including as yet non-existing buffers and
  1250. -- namespaces) by setting diagnostic_disabled to an empty table and set
  1251. -- its metatable to always return true. This metatable is removed
  1252. -- in enable()
  1253. diagnostic_disabled = setmetatable({}, {
  1254. __index = function() return true end,
  1255. })
  1256. else
  1257. local ns = M.get_namespace(namespace)
  1258. ns.disabled = true
  1259. end
  1260. else
  1261. bufnr = get_bufnr(bufnr)
  1262. if namespace == nil then
  1263. diagnostic_disabled[bufnr] = true
  1264. else
  1265. if type(diagnostic_disabled[bufnr]) ~= "table" then
  1266. diagnostic_disabled[bufnr] = {}
  1267. end
  1268. diagnostic_disabled[bufnr][namespace] = true
  1269. end
  1270. end
  1271. M.hide(namespace, bufnr)
  1272. end
  1273. --- Enable diagnostics in the given buffer.
  1274. ---
  1275. ---@param bufnr number|nil Buffer number, or 0 for current buffer. When
  1276. --- omitted, enable diagnostics in all buffers.
  1277. ---@param namespace number|nil Only enable diagnostics for the given namespace.
  1278. function M.enable(bufnr, namespace)
  1279. vim.validate { bufnr = {bufnr, 'n', true}, namespace = {namespace, 'n', true} }
  1280. if bufnr == nil then
  1281. if namespace == nil then
  1282. -- Enable everything by setting diagnostic_disabled to an empty table
  1283. diagnostic_disabled = {}
  1284. else
  1285. local ns = M.get_namespace(namespace)
  1286. ns.disabled = false
  1287. end
  1288. else
  1289. bufnr = get_bufnr(bufnr)
  1290. if namespace == nil then
  1291. diagnostic_disabled[bufnr] = nil
  1292. else
  1293. if type(diagnostic_disabled[bufnr]) ~= "table" then
  1294. return
  1295. end
  1296. diagnostic_disabled[bufnr][namespace] = nil
  1297. end
  1298. end
  1299. M.show(namespace, bufnr)
  1300. end
  1301. --- Parse a diagnostic from a string.
  1302. ---
  1303. --- For example, consider a line of output from a linter:
  1304. --- <pre>
  1305. --- WARNING filename:27:3: Variable 'foo' does not exist
  1306. --- </pre>
  1307. ---
  1308. --- This can be parsed into a diagnostic |diagnostic-structure|
  1309. --- with:
  1310. --- <pre>
  1311. --- local s = "WARNING filename:27:3: Variable 'foo' does not exist"
  1312. --- local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$"
  1313. --- local groups = {"severity", "lnum", "col", "message"}
  1314. --- vim.diagnostic.match(s, pattern, groups, {WARNING = vim.diagnostic.WARN})
  1315. --- </pre>
  1316. ---
  1317. ---@param str string String to parse diagnostics from.
  1318. ---@param pat string Lua pattern with capture groups.
  1319. ---@param groups table List of fields in a |diagnostic-structure| to
  1320. --- associate with captures from {pat}.
  1321. ---@param severity_map table A table mapping the severity field from {groups}
  1322. --- with an item from |vim.diagnostic.severity|.
  1323. ---@param defaults table|nil Table of default values for any fields not listed in {groups}.
  1324. --- When omitted, numeric values default to 0 and "severity" defaults to
  1325. --- ERROR.
  1326. ---@return diagnostic |diagnostic-structure| or `nil` if {pat} fails to match {str}.
  1327. function M.match(str, pat, groups, severity_map, defaults)
  1328. vim.validate {
  1329. str = { str, 's' },
  1330. pat = { pat, 's' },
  1331. groups = { groups, 't' },
  1332. severity_map = { severity_map, 't', true },
  1333. defaults = { defaults, 't', true },
  1334. }
  1335. severity_map = severity_map or M.severity
  1336. local diagnostic = {}
  1337. local matches = {string.match(str, pat)}
  1338. if vim.tbl_isempty(matches) then
  1339. return
  1340. end
  1341. for i, match in ipairs(matches) do
  1342. local field = groups[i]
  1343. if field == "severity" then
  1344. match = severity_map[match]
  1345. elseif field == "lnum" or field == "end_lnum" or field == "col" or field == "end_col" then
  1346. match = assert(tonumber(match)) - 1
  1347. end
  1348. diagnostic[field] = match
  1349. end
  1350. diagnostic = vim.tbl_extend("keep", diagnostic, defaults or {})
  1351. diagnostic.severity = diagnostic.severity or M.severity.ERROR
  1352. diagnostic.col = diagnostic.col or 0
  1353. diagnostic.end_lnum = diagnostic.end_lnum or diagnostic.lnum
  1354. diagnostic.end_col = diagnostic.end_col or diagnostic.col
  1355. return diagnostic
  1356. end
  1357. local errlist_type_map = {
  1358. [M.severity.ERROR] = 'E',
  1359. [M.severity.WARN] = 'W',
  1360. [M.severity.INFO] = 'I',
  1361. [M.severity.HINT] = 'N',
  1362. }
  1363. --- Convert a list of diagnostics to a list of quickfix items that can be
  1364. --- passed to |setqflist()| or |setloclist()|.
  1365. ---
  1366. ---@param diagnostics table List of diagnostics |diagnostic-structure|.
  1367. ---@return array of quickfix list items |setqflist-what|
  1368. function M.toqflist(diagnostics)
  1369. vim.validate { diagnostics = {diagnostics, 't'} }
  1370. local list = {}
  1371. for _, v in ipairs(diagnostics) do
  1372. local item = {
  1373. bufnr = v.bufnr,
  1374. lnum = v.lnum + 1,
  1375. col = v.col and (v.col + 1) or nil,
  1376. end_lnum = v.end_lnum and (v.end_lnum + 1) or nil,
  1377. end_col = v.end_col and (v.end_col + 1) or nil,
  1378. text = v.message,
  1379. type = errlist_type_map[v.severity] or 'E',
  1380. }
  1381. table.insert(list, item)
  1382. end
  1383. table.sort(list, function(a, b)
  1384. if a.bufnr == b.bufnr then
  1385. return a.lnum < b.lnum
  1386. else
  1387. return a.bufnr < b.bufnr
  1388. end
  1389. end)
  1390. return list
  1391. end
  1392. --- Convert a list of quickfix items to a list of diagnostics.
  1393. ---
  1394. ---@param list table A list of quickfix items from |getqflist()| or
  1395. --- |getloclist()|.
  1396. ---@return array of diagnostics |diagnostic-structure|
  1397. function M.fromqflist(list)
  1398. vim.validate { list = {list, 't'} }
  1399. local diagnostics = {}
  1400. for _, item in ipairs(list) do
  1401. if item.valid == 1 then
  1402. local lnum = math.max(0, item.lnum - 1)
  1403. local col = math.max(0, item.col - 1)
  1404. local end_lnum = item.end_lnum > 0 and (item.end_lnum - 1) or lnum
  1405. local end_col = item.end_col > 0 and (item.end_col - 1) or col
  1406. local severity = item.type ~= "" and M.severity[item.type] or M.severity.ERROR
  1407. table.insert(diagnostics, {
  1408. bufnr = item.bufnr,
  1409. lnum = lnum,
  1410. col = col,
  1411. end_lnum = end_lnum,
  1412. end_col = end_col,
  1413. severity = severity,
  1414. message = item.text,
  1415. })
  1416. end
  1417. end
  1418. return diagnostics
  1419. end
  1420. return M