robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
10.6 KiB299 linesraw
1local api, nonnil = vim.api, vim.nonnil
2local shared = require('vim.diagnostic._shared')
3local store = require('vim.diagnostic._store')
4
5--- @class (private) vim.diagnostic._float
6local M = {}
7
8local float_ns = api.nvim_create_namespace('nvim.diagnostic.float')
9
10local severity = vim.diagnostic.severity
11
12--- @type table<vim.diagnostic.Severity, string>
13local floating_highlight_map = {
14  [severity.ERROR] = 'DiagnosticFloatingError',
15  [severity.WARN] = 'DiagnosticFloatingWarn',
16  [severity.INFO] = 'DiagnosticFloatingInfo',
17  [severity.HINT] = 'DiagnosticFloatingHint',
18}
19
20--- @param opts vim.diagnostic.Opts.Float
21--- @param bufnr integer
22--- @return vim.diagnostic.Opts.Float, vim.diagnostic.Opts
23local function resolve_float_opts(opts, bufnr)
24  -- Resolve options with user settings from vim.diagnostic.config
25  -- Unlike the other decoration functions (e.g. set_virtual_text, set_signs, etc.) `open_float`
26  -- does not have a dedicated table for configuration options; instead, the options are mixed in
27  -- with its `opts` table. We create a dedicated options table (`float_opts`) that inherits
28  -- missing keys from the global configuration (`global_diagnostic_options.float`), which can
29  -- be a table or a function.
30  local global_opts = vim.diagnostic.config()
31  local float_opts = global_opts.float
32  local resolved_float_opts = type(float_opts) == 'table' and float_opts
33    or (type(float_opts) == 'function' and float_opts(opts.namespace, bufnr) or {})
34
35  return vim.tbl_extend('keep', opts, resolved_float_opts), global_opts
36end
37
38--- @param opts vim.diagnostic.Opts.Float?
39--- @return integer? float_bufnr
40--- @return integer? winid
41function M.open(opts, ...)
42  -- Support old (bufnr, opts) signature
43  local bufnr --- @type integer?
44  if opts == nil or type(opts) == 'number' then
45    bufnr = opts --[[@as integer?]]
46    opts = ... --- @type vim.diagnostic.Opts.Float
47  else
48    vim.validate('opts', opts, 'table', true)
49  end
50
51  opts = opts or {}
52  bufnr = vim._resolve_bufnr((bufnr or opts.bufnr) --[[@as integer?]])
53  local global_opts --- @type vim.diagnostic.Opts
54  opts, global_opts = resolve_float_opts(opts, bufnr)
55
56  local scope = ({ l = 'line', c = 'cursor', b = 'buffer' })[opts.scope] or opts.scope or 'line'
57  local lnum, col --- @type integer, integer
58  local opts_pos = opts.pos
59  if scope == 'line' or scope == 'cursor' then
60    if not opts_pos then
61      local pos = api.nvim_win_get_cursor(0)
62      lnum = pos[1] - 1
63      col = pos[2]
64    elseif type(opts_pos) == 'number' then
65      lnum = opts_pos
66    elseif type(opts_pos) == 'table' then
67      lnum, col = opts_pos[1], opts_pos[2]
68    else
69      error("Invalid value for option 'pos'")
70    end
71  elseif scope ~= 'buffer' then
72    error("Invalid value for option 'scope'")
73  end
74
75  local diagnostics = store.get_diagnostics(bufnr, opts --[[@as vim.diagnostic.GetOpts]], true)
76
77  if scope == 'line' then
78    --- @param diagnostic vim.Diagnostic
79    local function line_filter(diagnostic)
80      local d_lnum, _, d_end_lnum, d_end_col = shared.get_logical_pos(diagnostic)
81      return lnum >= d_lnum
82        and lnum <= d_end_lnum
83        and (d_lnum == d_end_lnum or lnum ~= d_end_lnum or d_end_col ~= 0)
84    end
85    diagnostics = vim.tbl_filter(line_filter, diagnostics)
86  elseif scope == 'cursor' then
87    -- If `col` is past the end of the line, show if the cursor is on the last char in the line
88    local line_length = #api.nvim_buf_get_lines(bufnr, lnum, lnum + 1, true)[1]
89    --- @param diagnostic vim.Diagnostic
90    local function cursor_filter(diagnostic)
91      local d_lnum, d_col, d_end_lnum, d_end_col = shared.get_logical_pos(diagnostic)
92      return lnum >= d_lnum
93        and lnum <= d_end_lnum
94        and (lnum ~= d_lnum or col >= math.min(d_col, line_length - 1))
95        and ((d_lnum == d_end_lnum and d_col == d_end_col) or lnum ~= d_end_lnum or col < d_end_col)
96    end
97    diagnostics = vim.tbl_filter(cursor_filter, diagnostics)
98  end
99
100  if vim.tbl_isempty(diagnostics) then
101    return
102  end
103
104  local severity_sort = nonnil(opts.severity_sort, global_opts.severity_sort)
105  if severity_sort then
106    if type(severity_sort) == 'table' and severity_sort.reverse then
107      table.sort(diagnostics, function(a, b)
108        return shared.diagnostic_cmp(a, b, 'severity', true)
109      end)
110    else
111      table.sort(diagnostics, function(a, b)
112        return shared.diagnostic_cmp(a, b, 'severity', false)
113      end)
114    end
115  end
116
117  local lines = {} --- @type string[]
118  local highlights = {} --- @type { hlname: string, prefix?: { length: integer, hlname: string? }, suffix?: { length: integer, hlname: string? } }[]
119  local header = nonnil(opts.header, 'Diagnostics:')
120  if header then
121    vim.validate('header', header, { 'string', 'table' }, "'string' or 'table'")
122    if type(header) == 'table' then
123      -- Don't insert any lines for an empty string
124      if #(header[1] or '') > 0 then
125        lines[#lines + 1] = header[1]
126        highlights[#highlights + 1] = { hlname = header[2] or 'Bold' }
127      end
128    elseif #header > 0 then
129      lines[#lines + 1] = header
130      highlights[#highlights + 1] = { hlname = 'Bold' }
131    end
132  end
133
134  if opts.format then
135    diagnostics = shared.reformat_diagnostics(opts.format, diagnostics)
136  end
137
138  if opts.source and (opts.source ~= 'if_many' or shared.count_sources(bufnr) > 1) then
139    diagnostics = shared.prefix_source(diagnostics)
140  end
141
142  local prefix_opt = opts.prefix
143    or (scope == 'cursor' and #diagnostics <= 1) and ''
144    or function(_, i)
145      return string.format('%d. ', i)
146    end
147
148  local prefix, prefix_hl_group --- @type string?, string?
149  if prefix_opt then
150    vim.validate(
151      'prefix',
152      prefix_opt,
153      { 'string', 'table', 'function' },
154      "'string' or 'table' or 'function'"
155    )
156    if type(prefix_opt) == 'string' then
157      prefix, prefix_hl_group = prefix_opt, 'NormalFloat'
158    elseif type(prefix_opt) == 'table' then
159      prefix, prefix_hl_group = prefix_opt[1] or '', prefix_opt[2] or 'NormalFloat'
160    end
161  end
162
163  local suffix_opt = opts.suffix
164    or function(diagnostic)
165      return diagnostic.code and string.format(' [%s]', diagnostic.code) or ''
166    end
167
168  local suffix, suffix_hl_group --- @type string?, string?
169  if suffix_opt then
170    vim.validate(
171      'suffix',
172      suffix_opt,
173      { 'string', 'table', 'function' },
174      "'string' or 'table' or 'function'"
175    )
176    if type(suffix_opt) == 'string' then
177      suffix, suffix_hl_group = suffix_opt, 'NormalFloat'
178    elseif type(suffix_opt) == 'table' then
179      suffix, suffix_hl_group = suffix_opt[1] or '', suffix_opt[2] or 'NormalFloat'
180    end
181  end
182
183  local related_info_locations = {} --- @type table<integer, lsp.Location>
184  for i, diagnostic in ipairs(diagnostics) do
185    if type(prefix_opt) == 'function' then
186      local prefix0, prefix_hl_group0 = prefix_opt(diagnostic, i, #diagnostics)
187      prefix, prefix_hl_group = prefix0 or '', prefix_hl_group0 or 'NormalFloat'
188    end
189    if type(suffix_opt) == 'function' then
190      local suffix0, suffix_hl_group0 = suffix_opt(diagnostic, i, #diagnostics)
191      suffix, suffix_hl_group = suffix0 or '', suffix_hl_group0 or 'NormalFloat'
192    end
193
194    local hiname = floating_highlight_map[diagnostic.severity]
195    local message_lines = vim.split(diagnostic.message, '\n')
196    local default_pre = string.rep(' ', #prefix)
197    for j = 1, #message_lines do
198      local pre = j == 1 and prefix or default_pre
199      local suf = j == #message_lines and suffix or ''
200      lines[#lines + 1] = pre .. message_lines[j] .. suf
201      highlights[#highlights + 1] = {
202        hlname = hiname,
203        prefix = {
204          length = j == 1 and #prefix or 0,
205          hlname = prefix_hl_group,
206        },
207        suffix = {
208          length = #suf,
209          hlname = suffix_hl_group,
210        },
211      }
212    end
213
214    --- @type lsp.DiagnosticRelatedInformation[]
215    local related_info = vim.tbl_get(diagnostic, 'user_data', 'lsp', 'relatedInformation') or {}
216    assert(related_info ~= vim.NIL, 'server response has invalid (null) relatedInformation')
217    -- Below the diagnostic, show its LSP related information (if any) in the form of file name and
218    -- range, plus description.
219    for _, info in ipairs(related_info) do
220      local location = info.location
221      local file_name = vim.fs.basename(vim.uri_to_fname(location.uri))
222      local info_suffix = ': ' .. info.message
223      related_info_locations[#lines + 1] = location
224      lines[#lines + 1] = string.format(
225        '%s%s:%s:%s%s',
226        default_pre,
227        file_name,
228        location.range.start.line + 1,
229        location.range.start.character + 1,
230        info_suffix
231      )
232      highlights[#highlights + 1] = {
233        hlname = '@string.special.path',
234        prefix = {
235          length = #default_pre,
236          hlname = prefix_hl_group,
237        },
238        suffix = {
239          length = #info_suffix,
240          hlname = 'NormalFloat',
241        },
242      }
243    end
244  end
245
246  -- Used by open_floating_preview to allow the float to be focused
247  if not opts.focus_id then
248    opts.focus_id = scope
249  end
250
251  --- @diagnostic disable-next-line: param-type-mismatch
252  local float_bufnr, winnr = vim.lsp.util.open_floating_preview(lines, 'plaintext', opts)
253  vim.bo[float_bufnr].path = vim.bo[bufnr].path
254
255  -- TODO: Handle this generally (like vim.ui.open()), rather than overriding gf.
256  vim.keymap.set('n', 'gf', function()
257    local cursor_row = api.nvim_win_get_cursor(0)[1]
258    local location = related_info_locations[cursor_row]
259    if location then
260      -- Split the window before calling `show_document` so the window doesn't disappear.
261      vim.cmd.split()
262      vim.lsp.util.show_document(location, 'utf-16', { focus = true })
263    else
264      vim.cmd.normal({ 'gf', bang = true })
265    end
266  end, { buf = float_bufnr, remap = false })
267
268  -- The preview may trim empty lines or reuse an older buffer, so highlight ranges
269  -- can extend past its contents. Use strict = false to tolerate this.
270  for i, hl in ipairs(highlights) do
271    local line = lines[i]
272    local prefix_len = hl.prefix and hl.prefix.length or 0
273    local suffix_len = hl.suffix and hl.suffix.length or 0
274    if hl.prefix and prefix_len > 0 then
275      api.nvim_buf_set_extmark(float_bufnr, float_ns, i - 1, 0, {
276        hl_group = hl.prefix.hlname,
277        end_col = prefix_len,
278        strict = false,
279      })
280    end
281    api.nvim_buf_set_extmark(float_bufnr, float_ns, i - 1, prefix_len, {
282      hl_group = hl.hlname,
283      end_col = #line - suffix_len,
284      strict = false,
285    })
286    if hl.suffix and suffix_len > 0 then
287      api.nvim_buf_set_extmark(float_bufnr, float_ns, i - 1, #line - suffix_len, {
288        hl_group = hl.suffix.hlname,
289        end_row = i,
290        end_col = 0,
291        strict = false,
292      })
293    end
294  end
295
296  return float_bufnr, winnr
297end
298
299return M