Skip to content

Commit 00fc0d1

Browse files
committed
perf: Convert between 1D and 2D indices in a non-stupid way.
Before I was just concatenating all of the previous lines in the buffer in order to compute the right indices. This PR changes things to use builtin Vim functions which are hopefully much more performant.
1 parent 8dd9150 commit 00fc0d1

File tree

1 file changed

+5
-14
lines changed

1 file changed

+5
-14
lines changed

lua/nvim-surround/patterns.lua

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,13 @@ local buffer = require("nvim-surround.buffer")
33
local M = {}
44

55
-- Converts a 1D index into the buffer to the corresponding 2D buffer position.
6-
---@param index integer The index of the character in the string.
6+
---@param index integer The index of the character in the buffer (viewed as a single `\n`-joined string).
77
---@return position @The position of the character in the buffer.
88
---@nodiscard
99
M.index_to_pos = function(index)
10-
local buffer_text = table.concat(buffer.get_lines(1, -1), "\n")
11-
-- Counts the number of newline characters, plus one for the final character before the current line
12-
local lnum = select(2, buffer_text:sub(1, math.max(1, index - 1)):gsub("\n", "\n")) + 1
13-
-- Special case for first line, as there are no newline characters preceding it
14-
if lnum == 1 then
15-
return { 1, index }
16-
end
17-
local col = index - #table.concat(buffer.get_lines(1, lnum - 1), "\n") - 1
10+
local lnum = vim.fn.byte2line(index)
11+
local lnum_bytes = vim.fn.line2byte(lnum)
12+
local col = index - lnum_bytes + 1
1813
return { lnum, col }
1914
end
2015

@@ -23,11 +18,7 @@ end
2318
---@return integer @The index of the character into the buffer.
2419
---@nodiscard
2520
M.pos_to_index = function(pos)
26-
-- Special case for first line, as there are no newline characters preceding it
27-
if pos[1] == 1 then
28-
return pos[2]
29-
end
30-
return #table.concat(buffer.get_lines(1, pos[1] - 1), "\n") + pos[2] + 1
21+
return vim.api.nvim_buf_get_offset(0, pos[1] - 1) + pos[2]
3122
end
3223

3324
-- Expands a selection to properly contain multi-byte characters.

0 commit comments

Comments
 (0)