robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
24.5 KiB767 linesraw
1local api = vim.api
2local nvim_on = require('vim._core.util').nvim_on
3local diagnostic = vim.diagnostic
4local diagnostic_shared = require('vim.diagnostic._shared')
5
6local severity = diagnostic.severity
7
8--- @class vim.diagnostic.Handler
9--- @field show? fun(namespace: integer, bufnr: integer, diagnostics: vim.Diagnostic[], opts?: vim.diagnostic.OptsResolved)
10--- @field hide? fun(namespace:integer, bufnr:integer)
11
12--- @class (private) vim.diagnostic._handlers._extmark : vim.api.keyset.get_extmark_item
13--- @field [1] integer extmark_id
14--- @field [2] integer row
15--- @field [3] integer col
16--- @field [4] vim.api.keyset.extmark_details
17
18local M = {}
19
20-- Default diagnostic highlights
21--- @type table<vim.diagnostic.Severity, string>
22local severity_names = {
23  [severity.ERROR] = 'Error',
24  [severity.WARN] = 'Warn',
25  [severity.INFO] = 'Info',
26  [severity.HINT] = 'Hint',
27}
28
29--- @param base_name string
30--- @return table<vim.diagnostic.Severity, string>
31local function make_highlight_map(base_name)
32  local result = {} --- @type table<vim.diagnostic.Severity, string>
33
34  for level, name in pairs(severity_names) do
35    result[level] = ('Diagnostic%s%s'):format(base_name, name)
36  end
37
38  return result
39end
40
41local sign_highlight_map = make_highlight_map('Sign')
42local underline_highlight_map = make_highlight_map('Underline')
43local virtual_text_highlight_map = make_highlight_map('VirtualText')
44local virtual_lines_highlight_map = make_highlight_map('VirtualLines')
45
46-- Metatable that automatically creates an empty table when assigning to a missing key
47local bufnr_and_namespace_cacher_mt = {
48  --- @param t table<integer, table>
49  --- @param bufnr integer
50  --- @return table
51  __index = function(t, bufnr)
52    assert(bufnr > 0, 'Invalid buffer number')
53    t[bufnr] = {}
54    return t[bufnr]
55  end,
56}
57
58--- @type table<integer, table<integer, vim.diagnostic._handlers._extmark[]>>
59local diagnostic_cache_extmarks = setmetatable({}, bufnr_and_namespace_cacher_mt)
60
61--- @type table<integer, true>
62local diagnostic_attached_buffers = {}
63
64--- @param bufnr integer
65--- @param last integer
66local function restore_extmarks(bufnr, last)
67  for ns, extmarks in pairs(diagnostic_cache_extmarks[bufnr]) do
68    local extmarks_current = api.nvim_buf_get_extmarks(bufnr, ns, 0, -1, { details = true })
69    local found = {} --- @type table<integer, true>
70
71    for _, extmark in ipairs(extmarks_current) do
72      -- nvim_buf_set_lines will move any extmark to the line after the last
73      -- nvim_buf_set_text will move any extmark to the last line
74      if extmark[2] ~= last + 1 then
75        found[extmark[1]] = true
76      end
77    end
78
79    for _, extmark in ipairs(extmarks) do
80      if not found[extmark[1]] then
81        local opts = extmark[4] --[[@as vim.api.keyset.set_extmark]]
82        opts.id = extmark[1]
83        pcall(api.nvim_buf_set_extmark, bufnr, ns, extmark[2], extmark[3], opts)
84      end
85    end
86  end
87end
88
89--- @param namespace integer
90--- @param bufnr? integer
91local function save_extmarks(namespace, bufnr)
92  bufnr = vim._resolve_bufnr(bufnr)
93
94  if not diagnostic_attached_buffers[bufnr] then
95    api.nvim_buf_attach(bufnr, false, {
96      on_lines = function(_, _, _, _, _, last)
97        restore_extmarks(bufnr, last - 1)
98      end,
99      on_detach = function()
100        diagnostic_cache_extmarks[bufnr] = nil
101      end,
102    })
103    diagnostic_attached_buffers[bufnr] = true
104  end
105
106  diagnostic_cache_extmarks[bufnr][namespace] =
107    api.nvim_buf_get_extmarks(bufnr, namespace, 0, -1, { details = true })
108end
109
110--- @param bufnr integer
111--- @param namespace integer
112local function clear_extmarks(bufnr, namespace)
113  diagnostic_cache_extmarks[bufnr][namespace] = {}
114  if api.nvim_buf_is_valid(bufnr) then
115    api.nvim_buf_clear_namespace(bufnr, namespace, 0, -1)
116  end
117end
118
119--- @param bufnr integer
120--- @param fn fun()
121--- @return integer?
122local function once_buf_loaded(bufnr, fn)
123  if api.nvim_buf_is_loaded(bufnr) then
124    fn()
125  else
126    return nvim_on('BufRead', nil, { buf = bufnr, once = true }, function()
127      fn()
128    end)
129  end
130end
131
132--- @param autocmd_key string
133--- @param ns vim.diagnostic.NS
134local function cleanup_show_autocmd(autocmd_key, ns)
135  if ns.user_data[autocmd_key] then
136    api.nvim_del_autocmd(ns.user_data[autocmd_key])
137    --- @type integer?
138    ns.user_data[autocmd_key] = nil
139  end
140end
141
142--- @param autocmd_key string
143--- @param ns vim.diagnostic.NS
144--- @param bufnr integer
145--- @param fn fun()
146local function show_once_loaded(autocmd_key, ns, bufnr, fn)
147  cleanup_show_autocmd(autocmd_key, ns)
148
149  --- @type integer?
150  ns.user_data[autocmd_key] = once_buf_loaded(bufnr, function()
151    --- @type integer?
152    ns.user_data[autocmd_key] = nil
153    fn()
154  end)
155end
156
157--- @param priority integer
158--- @param opts? { severity_sort?: boolean|{reverse?:boolean} }
159--- @return fun(severity: vim.diagnostic.Severity): integer
160local function severity_to_extmark_priority(priority, opts)
161  opts = opts or {}
162  if opts.severity_sort then
163    if type(opts.severity_sort) == 'table' and opts.severity_sort.reverse then
164      return function(level)
165        return priority + (level - severity.ERROR)
166      end
167    end
168
169    return function(level)
170      return priority + (severity.HINT - level)
171    end
172  end
173
174  return function()
175    return priority
176  end
177end
178
179M.signs = {}
180
181--- @param namespace integer
182--- @param bufnr integer
183--- @param diagnostics vim.Diagnostic[]
184--- @param opts? vim.diagnostic.OptsResolved
185function M.signs.show(namespace, bufnr, diagnostics, opts)
186  vim.validate('namespace', namespace, 'number')
187  vim.validate('bufnr', bufnr, 'number')
188  vim.validate('diagnostics', diagnostics, vim.islist, 'a list of diagnostics')
189  vim.validate('opts', opts, 'table', true)
190  vim.validate('opts.signs', (opts and opts or {}).signs, 'table', true)
191
192  bufnr = vim._resolve_bufnr(bufnr)
193
194  local sopts = opts and opts.signs or {}
195  local ns = diagnostic.get_namespace(namespace)
196  show_once_loaded('sign_show_autocmd', ns, bufnr, function()
197    -- 10 is the default sign priority when none is explicitly specified
198    local priority = sopts.priority or 10
199    local get_priority = severity_to_extmark_priority(priority, opts)
200
201    if not ns.user_data.sign_ns then
202      ns.user_data.sign_ns =
203        api.nvim_create_namespace(string.format('nvim.%s.diagnostic.signs', ns.name))
204    end
205
206    local text = {} --- @type table<vim.diagnostic.Severity|string, string>
207    for level in pairs(severity) do
208      if sopts.text and sopts.text[level] then
209        text[level] = sopts.text[level]
210      elseif type(level) == 'string' and not text[level] then
211        text[level] = level:sub(1, 1):upper()
212      end
213    end
214
215    local numhl = sopts.numhl or {}
216    local linehl = sopts.linehl or {}
217    local line_count = api.nvim_buf_line_count(bufnr)
218
219    for _, diagnostic0 in ipairs(diagnostics) do
220      if diagnostic0.lnum <= line_count then
221        local severity_name = (
222          severity --[[@as table<vim.diagnostic.Severity, vim.diagnostic.SeverityName>]]
223        )[diagnostic0.severity]
224        api.nvim_buf_set_extmark(bufnr, ns.user_data.sign_ns, diagnostic0.lnum, 0, {
225          sign_text = text[diagnostic0.severity] or text[severity_name] or 'U',
226          sign_hl_group = sign_highlight_map[diagnostic0.severity],
227          number_hl_group = numhl[diagnostic0.severity],
228          line_hl_group = linehl[diagnostic0.severity],
229          priority = get_priority(diagnostic0.severity),
230        })
231      end
232    end
233  end)
234end
235
236--- @param namespace integer
237--- @param bufnr integer
238function M.signs.hide(namespace, bufnr)
239  local ns = diagnostic.get_namespace(namespace)
240  cleanup_show_autocmd('sign_show_autocmd', ns)
241  if ns.user_data.sign_ns and api.nvim_buf_is_valid(bufnr) then
242    api.nvim_buf_clear_namespace(bufnr, ns.user_data.sign_ns, 0, -1)
243  end
244end
245
246M.underline = {}
247
248--- @param namespace integer
249--- @param bufnr integer
250--- @param diagnostics vim.Diagnostic[]
251--- @param opts? vim.diagnostic.OptsResolved
252function M.underline.show(namespace, bufnr, diagnostics, opts)
253  vim.validate('namespace', namespace, 'number')
254  vim.validate('bufnr', bufnr, 'number')
255  vim.validate('diagnostics', diagnostics, vim.islist, 'a list of diagnostics')
256  vim.validate('opts', opts, 'table', true)
257
258  bufnr = vim._resolve_bufnr(bufnr)
259
260  local ns = diagnostic.get_namespace(namespace)
261  show_once_loaded('underline_show_autocmd', ns, bufnr, function()
262    if not ns.user_data.underline_ns then
263      ns.user_data.underline_ns =
264        api.nvim_create_namespace(string.format('nvim.%s.diagnostic.underline', ns.name))
265    end
266
267    local underline_ns = ns.user_data.underline_ns
268    local get_priority = severity_to_extmark_priority(vim.hl.priorities.diagnostics, opts)
269
270    -- skip diagnostics with an out-of-range lnum.
271    local line_count = api.nvim_buf_line_count(bufnr)
272
273    for _, diagnostic0 in ipairs(diagnostics) do
274      if diagnostic0.lnum < line_count then
275        local higroups = { underline_highlight_map[diagnostic0.severity] }
276
277        if diagnostic0._tags then
278          if diagnostic0._tags.unnecessary then
279            table.insert(higroups, 'DiagnosticUnnecessary')
280          end
281          if diagnostic0._tags.deprecated then
282            table.insert(higroups, 'DiagnosticDeprecated')
283          end
284        end
285
286        local lines =
287          api.nvim_buf_get_lines(diagnostic0.bufnr, diagnostic0.lnum, diagnostic0.lnum + 1, true)
288
289        vim.hl.range(
290          bufnr,
291          underline_ns,
292          higroups,
293          { diagnostic0.lnum, math.min(diagnostic0.col, #lines[1] - 1) },
294          { diagnostic0.end_lnum, diagnostic0.end_col },
295          { priority = get_priority(diagnostic0.severity) }
296        )
297      end
298    end
299
300    save_extmarks(underline_ns, bufnr)
301  end)
302end
303
304--- @param namespace integer
305--- @param bufnr integer
306function M.underline.hide(namespace, bufnr)
307  local ns = diagnostic.get_namespace(namespace)
308  cleanup_show_autocmd('underline_show_autocmd', ns)
309  if ns.user_data.underline_ns then
310    clear_extmarks(bufnr, ns.user_data.underline_ns)
311  end
312end
313
314--- @param line_diags table<integer, vim.Diagnostic>
315--- @param opts vim.diagnostic.Opts.VirtualText
316--- @return [string, any][]?
317local function get_virt_text_chunks(line_diags, opts)
318  if #line_diags == 0 then
319    return
320  end
321
322  opts = opts or {}
323  local prefix = opts.prefix or '■'
324  local suffix = opts.suffix or ''
325  local spacing = opts.spacing or 4
326
327  -- Create a little more space between virtual text and contents
328  local virt_texts = { { string.rep(' ', spacing) } }
329
330  for i = 1, #line_diags do
331    local resolved_prefix = prefix
332    if type(prefix) == 'function' then
333      resolved_prefix = prefix(line_diags[i], i, #line_diags) or ''
334    end
335
336    table.insert(
337      virt_texts,
338      { resolved_prefix, virtual_text_highlight_map[line_diags[i].severity] }
339    )
340  end
341
342  local last = line_diags[#line_diags]
343  -- TODO(tjdevries): Allow different servers to be shown first somehow?
344  -- TODO(tjdevries): Display server name associated with these?
345  if last.message then
346    if type(suffix) == 'function' then
347      suffix = suffix(last) or ''
348    end
349
350    table.insert(virt_texts, {
351      string.format(' %s%s', last.message:gsub('\r', ''):gsub('\n', '  '), suffix),
352      virtual_text_highlight_map[last.severity],
353    })
354
355    return virt_texts
356  end
357end
358
359--- @param namespace integer
360--- @param bufnr integer
361--- @param diagnostics table<integer, vim.Diagnostic[]>
362--- @param opts vim.diagnostic.Opts.VirtualText
363local function render_virtual_text(namespace, bufnr, diagnostics, opts)
364  local lnum = api.nvim_win_get_cursor(0)[1] - 1
365  local buf_len = api.nvim_buf_line_count(bufnr)
366  api.nvim_buf_clear_namespace(bufnr, namespace, 0, -1)
367
368  --- @param line integer
369  --- @return boolean
370  local function should_render(line)
371    if
372      line >= buf_len
373      or (opts.current_line == true and line ~= lnum)
374      or (opts.current_line == false and line == lnum)
375    then
376      return false
377    end
378
379    return true
380  end
381
382  for line, line_diagnostics in pairs(diagnostics) do
383    if should_render(line) then
384      local virt_texts = get_virt_text_chunks(line_diagnostics, opts)
385      if virt_texts then
386        api.nvim_buf_set_extmark(bufnr, namespace, line, 0, {
387          hl_mode = opts.hl_mode or 'combine',
388          virt_text = virt_texts,
389          virt_text_pos = opts.virt_text_pos,
390          virt_text_hide = opts.virt_text_hide,
391          virt_text_win_col = opts.virt_text_win_col,
392        })
393      end
394    end
395  end
396end
397
398---Allows to perform actions **only** within CursorHold.
399---@param buf integer
400---@param augroup integer
401---@param on_hold fun() # action to be made on CursorHold
402---@param on_move fun() # action to be made on CursorMoved, usually a cleanup after `on_hold`
403local function on_line_hold(buf, augroup, on_hold, on_move)
404  local hold_line = -1
405
406  nvim_on('CursorHold', augroup, { buf = buf }, function()
407    on_hold()
408
409    local current_line = api.nvim_win_get_cursor(0)[1]
410    if current_line == hold_line then
411      return
412    end
413
414    hold_line = current_line
415
416    -- CursorHold can fire multiple times if LSP still resolves diagnostics.
417    api.nvim_clear_autocmds({ event = 'CursorMoved', buf = buf, group = augroup })
418    nvim_on('CursorMoved', augroup, { buf = buf }, function()
419      local move_line = api.nvim_win_get_cursor(0)[1]
420      if move_line ~= hold_line then
421        on_move()
422        hold_line = -1
423        return true
424      end
425    end)
426  end)
427  -- When first loading a buffer CursorHold is emitted before this fn is executed.
428  -- So retriggering it once to have proper initial render.
429  api.nvim_exec_autocmds('CursorHold', { buf = buf, group = augroup })
430end
431
432M.virtual_text = {}
433
434--- @param namespace integer
435--- @param bufnr integer
436--- @param diagnostics vim.Diagnostic[]
437--- @param opts? vim.diagnostic.OptsResolved
438function M.virtual_text.show(namespace, bufnr, diagnostics, opts)
439  vim.validate('namespace', namespace, 'number')
440  vim.validate('bufnr', bufnr, 'number')
441  vim.validate('diagnostics', diagnostics, vim.islist, 'a list of diagnostics')
442  vim.validate('opts', opts, 'table', true)
443
444  bufnr = vim._resolve_bufnr(bufnr)
445  local vopts = opts and opts.virtual_text or {}
446
447  local ns = diagnostic.get_namespace(namespace)
448  show_once_loaded('virtual_text_show_autocmd', ns, bufnr, function()
449    if vopts.format then
450      diagnostics = diagnostic_shared.reformat_diagnostics(vopts.format, diagnostics)
451    end
452
453    if
454      vopts.source and (vopts.source ~= 'if_many' or diagnostic_shared.count_sources(bufnr) > 1)
455    then
456      diagnostics = diagnostic_shared.prefix_source(diagnostics)
457    end
458
459    if not ns.user_data.virt_text_ns then
460      ns.user_data.virt_text_ns =
461        api.nvim_create_namespace(string.format('nvim.%s.diagnostic.virtual_text', ns.name))
462    end
463    if not ns.user_data.virt_text_augroup then
464      ns.user_data.virt_text_augroup = api.nvim_create_augroup(
465        string.format('nvim.%s.diagnostic.virt_text', ns.name),
466        { clear = true }
467      )
468    end
469
470    api.nvim_clear_autocmds({ group = ns.user_data.virt_text_augroup, buf = bufnr })
471
472    local line_diagnostics = diagnostic_shared.diagnostic_lines(diagnostics, true)
473
474    if vopts.current_line ~= nil then
475      on_line_hold(bufnr, ns.user_data.virt_text_augroup, function()
476        render_virtual_text(ns.user_data.virt_text_ns, bufnr, line_diagnostics, vopts)
477      end, function()
478        if vopts.current_line then
479          clear_extmarks(bufnr, ns.user_data.virt_text_ns)
480        else
481          local saved_current_line = vopts.current_line
482          vopts.current_line = nil
483          render_virtual_text(ns.user_data.virt_text_ns, bufnr, line_diagnostics, vopts)
484          vopts.current_line = saved_current_line
485        end
486      end)
487    else
488      render_virtual_text(ns.user_data.virt_text_ns, bufnr, line_diagnostics, vopts)
489    end
490
491    save_extmarks(ns.user_data.virt_text_ns, bufnr)
492  end)
493end
494
495--- @param namespace integer
496--- @param bufnr integer
497function M.virtual_text.hide(namespace, bufnr)
498  local ns = diagnostic.get_namespace(namespace)
499  cleanup_show_autocmd('virtual_text_show_autocmd', ns)
500  if ns.user_data.virt_text_ns then
501    clear_extmarks(bufnr, ns.user_data.virt_text_ns)
502    if api.nvim_buf_is_valid(bufnr) then
503      api.nvim_clear_autocmds({ group = ns.user_data.virt_text_augroup, buf = bufnr })
504    end
505  end
506end
507
508--- @param bufnr integer
509--- @param lnum integer
510--- @param start_col integer
511--- @param end_col integer
512--- @return integer
513local function distance_between_cols(bufnr, lnum, start_col, end_col)
514  return api.nvim_buf_call(bufnr, function()
515    local s = vim.fn.virtcol({ lnum + 1, start_col })
516    local e = vim.fn.virtcol({ lnum + 1, end_col + 1 })
517    return e - 1 - s
518  end)
519end
520
521--- @param namespace integer
522--- @param bufnr integer
523--- @param diagnostics vim.Diagnostic[]
524--- @param opts vim.diagnostic.Opts.VirtualLines
525local function render_virtual_lines(namespace, bufnr, diagnostics, opts)
526  table.sort(diagnostics, function(d1, d2)
527    return diagnostic_shared.diagnostic_cmp(d1, d2, 'lnum', false)
528  end)
529
530  api.nvim_buf_clear_namespace(bufnr, namespace, 0, -1)
531
532  if not next(diagnostics) then
533    return
534  end
535
536  -- This loop reads each line, putting them into stacks with some extra data since
537  -- rendering each line requires understanding what is beneath it.
538  local ElementType = { Space = 1, Diagnostic = 2, Overlap = 3, Blank = 4 } --- @enum ElementType
539  --- @type table<integer, [ElementType, string|vim.diagnostic.Severity|vim.Diagnostic][]>
540  local line_stacks = {}
541  --- @type table<integer, integer>
542  local line_anchor = {}
543  local prev_lnum = -1
544  local prev_col = 0
545
546  for _, diag in ipairs(diagnostics) do
547    if not line_stacks[diag.lnum] then
548      line_stacks[diag.lnum] = {}
549    end
550
551    local stack = line_stacks[diag.lnum]
552    local end_lnum = diag.end_lnum or diag.lnum
553    if not line_anchor[diag.lnum] or end_lnum > line_anchor[diag.lnum] then
554      line_anchor[diag.lnum] = end_lnum
555    end
556
557    if diag.lnum ~= prev_lnum then
558      table.insert(stack, {
559        ElementType.Space,
560        string.rep(' ', distance_between_cols(bufnr, diag.lnum, 0, diag.col)),
561      })
562    elseif diag.col ~= prev_col then
563      table.insert(stack, {
564        ElementType.Space,
565        -- +1 because indexing starts at 0 in one API but at 1 in the other.
566        string.rep(' ', distance_between_cols(bufnr, diag.lnum, prev_col + 1, diag.col)),
567      })
568    else
569      table.insert(stack, { ElementType.Overlap, diag.severity })
570    end
571
572    if diag.message:find('^%s*$') then
573      table.insert(stack, { ElementType.Blank, diag })
574    else
575      table.insert(stack, { ElementType.Diagnostic, diag })
576    end
577
578    prev_lnum, prev_col = diag.lnum, diag.col
579  end
580
581  local chars = {
582    cross = '┼',
583    horizontal = '─',
584    horizontal_up = '┴',
585    up_right = '└',
586    vertical = '│',
587    vertical_right = '├',
588  }
589
590  for lnum, stack in pairs(line_stacks) do
591    local virt_lines = {}
592
593    -- Note that we read in the order opposite to insertion.
594    for i = #stack, 1, -1 do
595      if stack[i][1] == ElementType.Diagnostic then
596        local diagnostic0 = stack[i][2] --[[@as vim.Diagnostic]]
597        local left = {} --- @type [string, string]
598        local overlap = false
599        local multi = false
600
601        -- Iterate the stack for this line to find elements on the left.
602        for j = 1, i - 1 do
603          local element = assert(stack[j])
604          local element_type, data = element[1], element[2]
605          if element_type == ElementType.Space then
606            if multi then
607              --- @cast data string
608              table.insert(left, {
609                string.rep(chars.horizontal, data:len()),
610                virtual_lines_highlight_map[diagnostic0.severity],
611              })
612            else
613              table.insert(left, { data, '' })
614            end
615          elseif element_type == ElementType.Diagnostic then
616            -- If an overlap follows this line, don't add an extra column.
617            if assert(stack[j + 1])[1] ~= ElementType.Overlap then
618              table.insert(left, { chars.vertical, virtual_lines_highlight_map[data.severity] })
619            end
620            overlap = false
621          elseif element_type == ElementType.Blank then
622            if multi then
623              table.insert(
624                left,
625                { chars.horizontal_up, virtual_lines_highlight_map[data.severity] }
626              )
627            else
628              table.insert(left, { chars.up_right, virtual_lines_highlight_map[data.severity] })
629            end
630            multi = true
631          elseif element_type == ElementType.Overlap then
632            overlap = true
633          end
634        end
635
636        local center_char --- @type string
637        if overlap and multi then
638          center_char = chars.cross
639        elseif overlap then
640          center_char = chars.vertical_right
641        elseif multi then
642          center_char = chars.horizontal_up
643        else
644          center_char = chars.up_right
645        end
646
647        local center = {
648          {
649            string.format('%s%s', center_char, string.rep(chars.horizontal, 4) .. ' '),
650            virtual_lines_highlight_map[diagnostic0.severity],
651          },
652        }
653
654        -- We can draw on the left side if and only if:
655        -- a. Is the last one stacked this line.
656        -- b. Has enough space on the left.
657        -- c. Is just one line.
658        -- d. Is not an overlap.
659        for msg_line in diagnostic0.message:gmatch('([^\n]+)') do
660          local vline = {}
661          vim.list_extend(vline, left)
662          vim.list_extend(vline, center)
663          vim.list_extend(vline, {
664            { msg_line, virtual_lines_highlight_map[diagnostic0.severity] },
665          })
666
667          table.insert(virt_lines, vline)
668
669          -- Special-case for continuation lines:
670          if overlap then
671            center = {
672              { chars.vertical, virtual_lines_highlight_map[diagnostic0.severity] },
673              { '     ', '' },
674            }
675          else
676            center = { { '      ', '' } }
677          end
678        end
679      end
680    end
681
682    api.nvim_buf_set_extmark(bufnr, namespace, line_anchor[lnum] or lnum, 0, {
683      virt_lines_overflow = opts.overflow or 'auto',
684      virt_lines = virt_lines,
685    })
686  end
687end
688
689--- @param diagnostic0 vim.Diagnostic
690--- @return string
691local function format_virtual_lines(diagnostic0)
692  if diagnostic0.code then
693    return string.format('%s: %s', diagnostic0.code, diagnostic0.message)
694  end
695
696  return diagnostic0.message
697end
698
699M.virtual_lines = {}
700
701--- @param namespace integer
702--- @param bufnr integer
703--- @param diagnostics vim.Diagnostic[]
704--- @param opts? vim.diagnostic.OptsResolved
705function M.virtual_lines.show(namespace, bufnr, diagnostics, opts)
706  vim.validate('namespace', namespace, 'number')
707  vim.validate('bufnr', bufnr, 'number')
708  vim.validate('diagnostics', diagnostics, vim.islist, 'a list of diagnostics')
709  vim.validate('opts', opts, 'table', true)
710
711  bufnr = vim._resolve_bufnr(bufnr)
712  local vopts = opts and opts.virtual_lines or {}
713
714  local ns = diagnostic.get_namespace(namespace)
715  show_once_loaded('virtual_lines_show_autocmd', ns, bufnr, function()
716    if not ns.user_data.virt_lines_ns then
717      ns.user_data.virt_lines_ns =
718        api.nvim_create_namespace(string.format('nvim.%s.diagnostic.virtual_lines', ns.name))
719    end
720    if not ns.user_data.virt_lines_augroup then
721      ns.user_data.virt_lines_augroup = api.nvim_create_augroup(
722        string.format('nvim.%s.diagnostic.virt_lines', ns.name),
723        { clear = true }
724      )
725    end
726
727    api.nvim_clear_autocmds({ group = ns.user_data.virt_lines_augroup, buf = bufnr })
728
729    diagnostics =
730      diagnostic_shared.reformat_diagnostics(vopts.format or format_virtual_lines, diagnostics)
731
732    if vopts.current_line == true then
733      -- Create a mapping from line -> diagnostics so that we can quickly get the
734      -- diagnostics we need when the cursor line doesn't change.
735      local line_diagnostics = diagnostic_shared.diagnostic_lines(diagnostics, true)
736      on_line_hold(bufnr, ns.user_data.virt_lines_augroup, function()
737        render_virtual_lines(
738          ns.user_data.virt_lines_ns,
739          bufnr,
740          diagnostic_shared.diagnostics_at_cursor(line_diagnostics),
741          vopts
742        )
743      end, function()
744        clear_extmarks(bufnr, ns.user_data.virt_lines_ns)
745      end)
746    else
747      render_virtual_lines(ns.user_data.virt_lines_ns, bufnr, diagnostics, vopts)
748    end
749
750    save_extmarks(ns.user_data.virt_lines_ns, bufnr)
751  end)
752end
753
754--- @param namespace integer
755--- @param bufnr integer
756function M.virtual_lines.hide(namespace, bufnr)
757  local ns = diagnostic.get_namespace(namespace)
758  cleanup_show_autocmd('virtual_lines_show_autocmd', ns)
759  if ns.user_data.virt_lines_ns then
760    clear_extmarks(bufnr, ns.user_data.virt_lines_ns)
761    if api.nvim_buf_is_valid(bufnr) then
762      api.nvim_clear_autocmds({ group = ns.user_data.virt_lines_augroup, buf = bufnr })
763    end
764  end
765end
766
767return M