fix(lsp): add assertion for explicit bufnr in apply_text_edits (#27614)

Assert that the buffer number passed to apply_text_edits is fully
resolved (not 0 or null). Pass the known buffer number to
apply_text_edits from lsp.formatexpr().
This commit is contained in:
Gregory Anders 2024-02-24 19:21:57 -06:00 committed by GitHub
parent c2ddef30e7
commit 2e1f5055ac
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 6 additions and 3 deletions

View File

@ -1280,7 +1280,7 @@ function lsp.formatexpr(opts)
local response =
client.request_sync(ms.textDocument_rangeFormatting, params, timeout_ms, bufnr)
if response and response.result then
lsp.util.apply_text_edits(response.result, 0, client.offset_encoding)
lsp.util.apply_text_edits(response.result, bufnr, client.offset_encoding)
return 0
end
end

View File

@ -419,6 +419,9 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding)
if not next(text_edits) then
return
end
assert(bufnr ~= 0, 'Explicit buffer number is required')
if not api.nvim_buf_is_loaded(bufnr) then
vim.fn.bufload(bufnr)
end
@ -457,7 +460,7 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding)
-- save and restore local marks since they get deleted by nvim_buf_set_lines
local marks = {}
for _, m in pairs(vim.fn.getmarklist(bufnr or vim.api.nvim_get_current_buf())) do
for _, m in pairs(vim.fn.getmarklist(bufnr)) do
if m.mark:match("^'[a-z]$") then
marks[m.mark:sub(2, 2)] = { m.pos[2], m.pos[3] - 1 } -- api-indexed
end
@ -516,7 +519,7 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding)
local max = api.nvim_buf_line_count(bufnr)
-- no need to restore marks that still exist
for _, m in pairs(vim.fn.getmarklist(bufnr or vim.api.nvim_get_current_buf())) do
for _, m in pairs(vim.fn.getmarklist(bufnr)) do
marks[m.mark:sub(2, 2)] = nil
end
-- restore marks