Skip to content

Commit 3994651

Browse files
mawklerkylechui
andauthored
fix: Bounds check when restoring cursor position. (#365)
* fix: bounds check when restoring cursor position (#364) * test: Add regression test for invalid cursor position. --------- Co-authored-by: Kyle Chui <[email protected]>
1 parent 9f0cb49 commit 3994651

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

lua/nvim-surround/buffer.lua

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,10 @@ M.set_curpos = function(pos)
2525
if not pos then
2626
return
2727
end
28-
vim.api.nvim_win_set_cursor(0, { pos[1], pos[2] - 1 })
28+
29+
local lnum = math.min(pos[1], vim.api.nvim_buf_line_count(0))
30+
local column = pos[2] - 1
31+
vim.api.nvim_win_set_cursor(0, { lnum, column })
2932
end
3033

3134
-- Move the cursor to a location in the buffer, depending on the `move_cursor` setting.

tests/configuration_spec.lua

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,4 +571,25 @@ describe("configuration", function()
571571
assert.are.same(get_curpos(), { 1, 5 })
572572
check_lines({ "(some 'text')" })
573573
end)
574+
575+
it("will clamp cursor position if deleting a surround invalidates the old position", function()
576+
require("nvim-surround").setup({
577+
move_cursor = false,
578+
surrounds = {
579+
["c"] = {
580+
add = function()
581+
return { { "```", "" }, { "", "```" } }
582+
end,
583+
find = "(```[a-zA-Z]*\n)().-(\n```)()",
584+
delete = "(```[a-zA-Z]*\n)().-(\n```)()",
585+
},
586+
},
587+
})
588+
589+
set_lines({ "```lua", "print('foo')", "```" })
590+
set_curpos({ 3, 1 }) -- If we delete the ```, the cursor position won't be valid
591+
vim.cmd("normal dsc")
592+
assert.are.same(get_curpos(), { 1, 1 })
593+
check_lines({ "print('foo')" })
594+
end)
574595
end)

0 commit comments

Comments
 (0)