diagnostic.lua 54 KB

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