feat(vim.pos): accept buf=0 for current buf #39414

This commit is contained in:
Luis Calle
2026-04-26 05:34:18 -05:00
committed by Justin M. Keyes
parent 828a35b14f
commit 49efe692f3
5 changed files with 74 additions and 44 deletions

View File

@@ -16,8 +16,8 @@ local validate = vim.validate
---
--- Example:
--- ```lua
--- local pos1 = vim.pos(vim.api.nvim_get_current_buf(), 3, 5)
--- local pos2 = vim.pos(vim.api.nvim_get_current_buf(), 4, 0)
--- local pos1 = vim.pos(0, 3, 5)
--- local pos2 = vim.pos(0, 4, 0)
---
--- -- Operators are overloaded for comparing two `vim.Pos` objects.
--- if pos1 < pos2 then
@@ -65,6 +65,10 @@ function M.new(buf, row, col)
validate('row', row, 'number')
validate('col', col, 'number')
if buf == 0 then
buf = api.nvim_get_current_buf()
end
---@type vim.Pos
local self = setmetatable({
row,
@@ -123,8 +127,7 @@ end
---
--- Example:
--- ```lua
--- local buf = vim.api.nvim_get_current_buf()
--- local pos = vim.pos(buf, 3, 5)
--- local pos = vim.pos(0, 3, 5)
---
--- -- Convert to LSP position, you can call it in a method style.
--- local lsp_pos = pos:to_lsp('utf-16')
@@ -150,13 +153,12 @@ end
---
--- Example:
--- ```lua
--- local buf = vim.api.nvim_get_current_buf()
--- local lsp_pos = {
--- line = 3,
--- character = 5
--- }
---
--- local pos = vim.pos.lsp(buf, lsp_pos, 'utf-16')
--- local pos = vim.pos.lsp(0, lsp_pos, 'utf-16')
--- ```
---@param buf integer
---@param pos lsp.Position
@@ -166,6 +168,10 @@ function M.lsp(buf, pos, position_encoding)
validate('pos', pos, 'table')
validate('position_encoding', position_encoding, 'string')
if buf == 0 then
buf = api.nvim_get_current_buf()
end
local row, col = pos.line, pos.character
-- When on the first character,
-- we can ignore the difference between byte and character.
@@ -213,6 +219,10 @@ end
---@param row integer
---@param col integer
function M.extmark(buf, row, col)
if buf == 0 then
buf = api.nvim_get_current_buf()
end
return M.new(buf, row, col)
end