feat(pos): pos:to_offset(), pos.offset() #39564

Problem:
For a given position, it is not easy to compare which of several other positions is closest to it.

Solution:
Add support for converting `vim.Pos` to a buffer byte offset.

This allows for sorting, e.g:
```lua
table.sort(positions, function(pos1, pos2)
  return pos1:to_offset() < pos2:to_offset()
end
```

Or a binary search, e.g:
```lua
vim.list.bisect(positions, pos, { key = function(pos) return pos:to_offset() end })
```
This commit is contained in:
Yi Ming
2026-05-07 04:37:16 +08:00
committed by GitHub
parent 7b00f58d84
commit 9174157f74
4 changed files with 84 additions and 0 deletions

View File

@@ -2,6 +2,7 @@
local t = require('test.testutil')
local n = require('test.functional.testnvim')()
local eq = t.eq
local dedent = t.dedent
local clear = n.clear
local exec_lua = n.exec_lua
@@ -120,4 +121,40 @@ describe('vim.pos', function()
end)
eq({ 0, 9, buf }, pos2)
end)
it('converts between vim.Pos and buffer offset', function()
local buf = exec_lua(function()
return vim.api.nvim_get_current_buf()
end)
insert(dedent [[
first
second
third
]])
local offsets = exec_lua(function()
return {
vim.pos(buf, 0, 0):to_offset(),
vim.pos(buf, 0, 3):to_offset(),
vim.pos(buf, 1, 0):to_offset(),
vim.pos(buf, 3, 0):to_offset(),
}
end)
eq({ 0, 3, 6, 19 }, offsets)
local positions = exec_lua(function()
return {
vim.pos.offset(buf, 0),
vim.pos.offset(buf, 3),
vim.pos.offset(buf, 6),
vim.pos.offset(buf, 19),
}
end)
eq({
{ 0, 0, buf },
{ 0, 3, buf },
{ 1, 0, buf },
{ 3, 0, buf },
}, positions)
end)
end)