fix(lsp): handle encoding bounds in str_utfindex_enc

Problem:
str_utfindex_enc could return an error if the index was longer than the
line length. This was handled in each of the calls to it individually

Solution:
* Fix the call at the source level so that if the index is higher than
  the line length, utf length is returned

(cherry picked from commit f279d1ae33)
This commit is contained in:
tris203
2024-09-09 22:39:02 +01:00
committed by Mathias Fußenegger
parent b55435f438
commit e13564b9f4

View File

@@ -120,6 +120,7 @@ end
---@param encoding string|nil utf-8|utf-16|utf-32|nil defaults to utf-16 ---@param encoding string|nil utf-8|utf-16|utf-32|nil defaults to utf-16
---@return integer `encoding` index of `index` in `line` ---@return integer `encoding` index of `index` in `line`
function M._str_utfindex_enc(line, index, encoding) function M._str_utfindex_enc(line, index, encoding)
local len32, len16 = vim.str_utfindex(line)
if not encoding then if not encoding then
encoding = 'utf-16' encoding = 'utf-16'
end end
@@ -130,9 +131,15 @@ function M._str_utfindex_enc(line, index, encoding)
return #line return #line
end end
elseif encoding == 'utf-16' then elseif encoding == 'utf-16' then
if not index or index > len16 then
return len16
end
local _, col16 = vim.str_utfindex(line, index) local _, col16 = vim.str_utfindex(line, index)
return col16 return col16
elseif encoding == 'utf-32' then elseif encoding == 'utf-32' then
if not index or index > len32 then
return len32
end
local col32, _ = vim.str_utfindex(line, index) local col32, _ = vim.str_utfindex(line, index)
return col32 return col32
else else
@@ -172,8 +179,6 @@ function M._str_byteindex_enc(line, index, encoding)
end end
end end
local _str_utfindex_enc = M._str_utfindex_enc
--- Replaces text in a range with new text. --- Replaces text in a range with new text.
--- ---
--- CAUTION: Changes in-place! --- CAUTION: Changes in-place!
@@ -2039,7 +2044,7 @@ local function make_position_param(window, offset_encoding)
return { line = 0, character = 0 } return { line = 0, character = 0 }
end end
col = _str_utfindex_enc(line, col, offset_encoding) col = M._str_utfindex_enc(line, col, offset_encoding)
return { line = row, character = col } return { line = row, character = col }
end end
@@ -2220,11 +2225,7 @@ function M.character_offset(buf, row, col, offset_encoding)
) )
offset_encoding = vim.lsp.get_clients({ bufnr = buf })[1].offset_encoding offset_encoding = vim.lsp.get_clients({ bufnr = buf })[1].offset_encoding
end end
-- If the col is past the EOL, use the line length. return M._str_utfindex_enc(line, col, offset_encoding)
if col > #line then
return _str_utfindex_enc(line, nil, offset_encoding)
end
return _str_utfindex_enc(line, col, offset_encoding)
end end
--- Helper function to return nested values in language server settings --- Helper function to return nested values in language server settings