robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
9.4 KiB312 linesraw
1local api = vim.api
2local nvim_on = require('vim._core.util').nvim_on
3
4local severity_module = require('vim.diagnostic._severity')
5
6--- @class (private) vim.diagnostic._store
7local M = {}
8
9-- bufnr -> ns -> Diagnostic[]
10local diagnostic_cache = {} --- @type table<integer,table<integer,vim.Diagnostic[]?>>
11
12local group = api.nvim_create_augroup('nvim.diagnostic.buf_wipeout')
13setmetatable(diagnostic_cache, {
14  --- @param t table<integer,vim.Diagnostic[]>
15  --- @param bufnr integer
16  __index = function(t, bufnr)
17    assert(bufnr > 0, 'Invalid buffer number')
18    nvim_on('BufWipeout', group, { buf = bufnr }, function()
19      rawset(t, bufnr, nil)
20    end)
21    t[bufnr] = {}
22    return t[bufnr]
23  end,
24})
25
26--- @param bufnr integer
27--- @param namespace integer
28--- @param d vim.Diagnostic.Set
29local function norm_diag(bufnr, namespace, d)
30  vim.validate('diagnostic.lnum', d.lnum, 'number')
31  local d1 = d --[[@as vim.Diagnostic]]
32  d1.severity = d.severity and severity_module.to_severity(d.severity)
33    or vim.diagnostic.severity.ERROR
34  d1.end_lnum = d.end_lnum or d.lnum
35  d1.col = d.col or 0
36  d1.end_col = d.end_col or d.col or 0
37  d1.namespace = namespace
38  d1.bufnr = bufnr
39end
40
41--- Set extmarks at the computed positions of the cached diagnostics of
42--- {bufnr}/{namespace}, and store their ids in diagnostic._extmark_id (used by
43--- get_logical_pos to adjust positions).
44---
45--- @param bufnr integer
46--- @param namespace integer
47local function set_position_extmarks(bufnr, namespace)
48  local ns = vim.diagnostic.get_namespace(namespace)
49
50  if not ns.user_data.location_ns then
51    ns.user_data.location_ns =
52      api.nvim_create_namespace(string.format('nvim.%s.diagnostic', ns.name))
53  end
54
55  api.nvim_buf_clear_namespace(bufnr, ns.user_data.location_ns, 0, -1)
56
57  local lines = api.nvim_buf_get_lines(bufnr, 0, -1, true)
58  local buf_cache = rawget(diagnostic_cache, bufnr) --- @type table<integer,vim.Diagnostic[]?>?
59  -- set extmarks at diagnostic locations to preserve logical positions despite text changes
60  for _, diagnostic0 in ipairs(buf_cache and buf_cache[namespace] or {}) do
61    --- @cast diagnostic0 vim.Diagnostic
62    local last_row = #lines - 1
63    local row = math.max(0, math.min(diagnostic0.lnum, last_row))
64    local row_len = #lines[row + 1]
65    local col = math.max(0, math.min(diagnostic0.col, row_len - 1))
66
67    local end_row = math.max(0, math.min(diagnostic0.end_lnum or row, last_row))
68    local end_row_len = #lines[end_row + 1]
69    local end_col = math.max(0, math.min(diagnostic0.end_col or col, end_row_len))
70
71    if end_row == row then
72      -- avoid starting an extmark beyond end of the line
73      if end_col == col then
74        end_col = math.min(end_col + 1, end_row_len)
75      end
76    else
77      -- avoid ending an extmark before start of the line
78      if end_col == 0 then
79        end_row = end_row - 1
80
81        local end_line = lines[end_row + 1]
82
83        if not end_line then
84          error(
85            'Failed to adjust diagnostic position to the end of a previous line. #lines in a buffer: '
86              .. #lines
87              .. ', lnum: '
88              .. diagnostic0.lnum
89              .. ', col: '
90              .. diagnostic0.col
91              .. ', end_lnum: '
92              .. diagnostic0.end_lnum
93              .. ', end_col: '
94              .. diagnostic0.end_col
95          )
96        end
97
98        end_col = #end_line
99      end
100    end
101
102    diagnostic0._extmark_id = api.nvim_buf_set_extmark(bufnr, ns.user_data.location_ns, row, col, {
103      end_row = end_row,
104      end_col = end_col,
105      invalidate = true,
106    })
107  end
108end
109
110-- Positions can only be computed once the buffer is loaded, so set the
111-- extmarks for any buffer with cached diagnostics when it is read (or re-read).
112nvim_on('BufRead', api.nvim_create_augroup('nvim.diagnostic.buf_load'), function(ev)
113  local buf_cache = rawget(diagnostic_cache, ev.buf) --- @type table<integer,vim.Diagnostic[]?>?
114  if buf_cache then
115    for namespace in pairs(buf_cache) do
116      set_position_extmarks(ev.buf, namespace)
117    end
118  end
119end)
120
121--- @param bufnr integer?
122--- @param opts vim.diagnostic.GetOpts?
123--- @param clamp boolean
124--- @return vim.Diagnostic[]
125function M.get_diagnostics(bufnr, opts, clamp)
126  opts = opts or {}
127
128  local namespace = opts.namespace
129
130  if type(namespace) == 'number' then
131    namespace = { namespace }
132  end
133
134  --- @cast namespace integer[]
135
136  --- @type vim.Diagnostic[]
137  local diagnostics = {}
138
139  -- Memoized results of buf_line_count per bufnr
140  --- @type table<integer,integer>
141  local buf_line_count = setmetatable({}, {
142    --- @param t table<integer,integer>
143    --- @param k integer
144    --- @return integer
145    __index = function(t, k)
146      t[k] = api.nvim_buf_line_count(k)
147      return rawget(t, k)
148    end,
149  })
150
151  local match_severity = opts.severity and severity_module.severity_predicate(opts.severity)
152    or function(_)
153      return true
154    end
155
156  --- @param b integer
157  --- @param d vim.Diagnostic
158  local match_enablement = function(d, b)
159    if opts.enabled == nil then
160      return true
161    end
162
163    local enabled = vim.diagnostic.is_enabled({ bufnr = b, ns_id = d.namespace })
164
165    return (enabled and opts.enabled) or (not enabled and not opts.enabled)
166  end
167
168  --- @param b integer
169  --- @param d vim.Diagnostic
170  local function add(b, d)
171    if
172      match_severity(d)
173      and match_enablement(d, b)
174      and (not opts.lnum or (opts.lnum >= d.lnum and opts.lnum <= (d.end_lnum or d.lnum)))
175    then
176      if clamp and api.nvim_buf_is_loaded(b) then
177        local line_count = buf_line_count[b] - 1
178        if
179          d.lnum > line_count
180          or d.end_lnum > line_count
181          or d.lnum < 0
182          or d.end_lnum < 0
183          or d.col < 0
184          or d.end_col < 0
185        then
186          d = vim.deepcopy(d, true)
187          d.lnum = math.max(math.min(d.lnum, line_count), 0)
188          d.end_lnum = math.max(math.min(d.end_lnum, line_count), 0)
189          d.col = math.max(d.col, 0)
190          d.end_col = math.max(d.end_col, 0)
191        end
192      end
193      table.insert(diagnostics, d)
194    end
195  end
196
197  --- @param buf integer
198  --- @param diags vim.Diagnostic[]
199  local function add_all_diags(buf, diags)
200    for _, diagnostic0 in pairs(diags) do
201      add(buf, diagnostic0)
202    end
203  end
204
205  if not namespace and not bufnr then
206    for buf, ns_diags in pairs(diagnostic_cache) do
207      for _, diags in pairs(ns_diags) do
208        add_all_diags(buf, diags)
209      end
210    end
211  elseif not namespace then
212    bufnr = vim._resolve_bufnr(bufnr)
213    for _, diags in pairs(diagnostic_cache[bufnr]) do
214      add_all_diags(bufnr, diags)
215    end
216  elseif bufnr == nil then
217    for b, t in pairs(diagnostic_cache) do
218      for _, iter_namespace in ipairs(namespace) do
219        add_all_diags(b, t[iter_namespace] or {})
220      end
221    end
222  else
223    bufnr = vim._resolve_bufnr(bufnr)
224    for _, iter_namespace in ipairs(namespace) do
225      add_all_diags(bufnr, diagnostic_cache[bufnr][iter_namespace] or {})
226    end
227  end
228
229  return diagnostics
230end
231
232--- @return integer[]
233function M.get_bufnrs()
234  return vim.tbl_keys(diagnostic_cache)
235end
236
237--- @param bufnr integer
238--- @return integer[]
239function M.get_buf_namespaces(bufnr)
240  return vim.tbl_keys(diagnostic_cache[vim._resolve_bufnr(bufnr)])
241end
242
243--- @param namespace integer
244--- @param bufnr integer
245function M.clear(namespace, bufnr)
246  diagnostic_cache[vim._resolve_bufnr(bufnr)][namespace] = nil
247end
248
249--- @param bufnr integer
250function M.drop_buf(bufnr)
251  diagnostic_cache[vim._resolve_bufnr(bufnr)] = nil
252end
253
254--- Set diagnostics for the given namespace and buffer.
255---
256--- @param namespace integer The diagnostic namespace
257--- @param bufnr integer Buffer number
258--- @param diagnostics vim.Diagnostic.Set[]
259function M.set(namespace, bufnr, diagnostics)
260  vim.validate('namespace', namespace, 'number')
261  vim.validate('bufnr', bufnr, 'number')
262  vim.validate('diagnostics', diagnostics, vim.islist, 'a list of diagnostics')
263
264  bufnr = vim._resolve_bufnr(bufnr)
265
266  for _, diagnostic0 in ipairs(diagnostics) do
267    norm_diag(bufnr, namespace, diagnostic0)
268  end
269
270  --- @cast diagnostics vim.Diagnostic[]
271
272  if vim.tbl_isempty(diagnostics) then
273    diagnostic_cache[bufnr][namespace] = nil
274  else
275    diagnostic_cache[bufnr][namespace] = diagnostics
276  end
277
278  if api.nvim_buf_is_loaded(bufnr) then
279    set_position_extmarks(bufnr, namespace)
280  end
281end
282
283--- @param bufnr integer? Buffer number to get diagnostics from. Use 0 for
284---                      current buffer or nil for all buffers.
285--- @param opts? vim.diagnostic.GetOpts
286--- @return vim.Diagnostic[] : Fields `bufnr`, `end_lnum`, `end_col`, and `severity`
287---                           are guaranteed to be present.
288function M.get(bufnr, opts)
289  vim.validate('bufnr', bufnr, 'number', true)
290  vim.validate('opts', opts, 'table', true)
291
292  return vim.deepcopy(M.get_diagnostics(bufnr, opts, false), true)
293end
294
295--- @param bufnr? integer Buffer number to get diagnostics from. Use 0 for
296---                      current buffer or nil for all buffers.
297--- @param opts? vim.diagnostic.GetOpts
298--- @return table<integer, integer> : Table with actually present severity values as keys
299---                (see |diagnostic-severity|) and integer counts as values.
300function M.count(bufnr, opts)
301  vim.validate('bufnr', bufnr, 'number', true)
302  vim.validate('opts', opts, 'table', true)
303
304  local diagnostics = M.get_diagnostics(bufnr, opts, false)
305  local count = {} --- @type table<integer,integer>
306  for _, d in ipairs(diagnostics) do
307    count[d.severity] = (count[d.severity] or 0) + 1
308  end
309  return count
310end
311
312return M