fix(diagnostic): always return copies of diagnostic items (#25010)

This commit is contained in:
Evgeni Chasnovski
2023-09-06 20:54:18 +03:00
committed by GitHub
parent 2ef7b6a433
commit d272143318
3 changed files with 18 additions and 1 deletions

View File

@@ -480,6 +480,9 @@ fromqflist({list}) *vim.diagnostic.fromqflist()*
get({bufnr}, {opts}) *vim.diagnostic.get()* get({bufnr}, {opts}) *vim.diagnostic.get()*
Get current diagnostics. Get current diagnostics.
Modifying diagnostics in the returned table has no effect. To set
diagnostics in a buffer, use |vim.diagnostic.set()|.
Parameters: ~ Parameters: ~
• {bufnr} (integer|nil) Buffer number to get diagnostics from. Use 0 • {bufnr} (integer|nil) Buffer number to get diagnostics from. Use 0
for current buffer or nil for all buffers. for current buffer or nil for all buffers.

View File

@@ -386,6 +386,7 @@ local function get_diagnostics(bufnr, opts, clamp)
local function add(b, d) local function add(b, d)
if not opts.lnum or d.lnum == opts.lnum then if not opts.lnum or d.lnum == opts.lnum then
d = vim.deepcopy(d)
if clamp and api.nvim_buf_is_loaded(b) then if clamp and api.nvim_buf_is_loaded(b) then
local line_count = buf_line_count[b] - 1 local line_count = buf_line_count[b] - 1
if if
@@ -396,7 +397,6 @@ local function get_diagnostics(bufnr, opts, clamp)
or d.col < 0 or d.col < 0
or d.end_col < 0 or d.end_col < 0
then then
d = vim.deepcopy(d)
d.lnum = math.max(math.min(d.lnum, line_count), 0) d.lnum = math.max(math.min(d.lnum, line_count), 0)
d.end_lnum = math.max(math.min(d.end_lnum, line_count), 0) d.end_lnum = math.max(math.min(d.end_lnum, line_count), 0)
d.col = math.max(d.col, 0) d.col = math.max(d.col, 0)
@@ -750,6 +750,8 @@ end
--- Get current diagnostics. --- Get current diagnostics.
--- ---
--- Modifying diagnostics in the returned table has no effect. To set diagnostics in a buffer, use |vim.diagnostic.set()|.
---
---@param bufnr integer|nil Buffer number to get diagnostics from. Use 0 for ---@param bufnr integer|nil Buffer number to get diagnostics from. Use 0 for
--- current buffer or nil for all buffers. --- current buffer or nil for all buffers.
---@param opts table|nil A table with the following keys: ---@param opts table|nil A table with the following keys:

View File

@@ -181,6 +181,18 @@ describe('vim.diagnostic', function()
eq(0, #diagnostics) eq(0, #diagnostics)
end) end)
it('always returns a copy of diagnostic tables', function()
local result = exec_lua [[
vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, {
make_error('Diagnostic #1', 1, 1, 1, 1),
})
local diag = vim.diagnostic.get()
diag[1].col = 10000
return vim.diagnostic.get()[1].col == 10000
]]
eq(result, false)
end)
it('resolves buffer number 0 to the current buffer', function() it('resolves buffer number 0 to the current buffer', function()
eq(2, exec_lua [[ eq(2, exec_lua [[
vim.api.nvim_set_current_buf(diagnostic_bufnr) vim.api.nvim_set_current_buf(diagnostic_bufnr)