Skip to content

Commit

Permalink
fix: Bounds check when restoring cursor position. (kylechui#365)
Browse files Browse the repository at this point in the history
* fix: bounds check when restoring cursor position (kylechui#364)

* test: Add regression test for invalid cursor position.

---------

Co-authored-by: Kyle Chui <[email protected]>
  • Loading branch information
2 people authored and phgz committed Jan 31, 2025
1 parent 374468b commit 74f1367
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lua/nvim-surround/buffer.lua
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ M.set_curpos = function(pos)
if not pos then
return
end
vim.api.nvim_win_set_cursor(0, { pos[1], pos[2] - 1 })

local lnum = math.min(pos[1], vim.api.nvim_buf_line_count(0))
local column = pos[2] - 1
vim.api.nvim_win_set_cursor(0, { lnum, column })
end

-- Move the cursor to a location in the buffer, depending on the `move_cursor` setting.
Expand Down
21 changes: 21 additions & 0 deletions tests/configuration_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -571,4 +571,25 @@ describe("configuration", function()
assert.are.same(get_curpos(), { 1, 5 })
check_lines({ "(some 'text')" })
end)

it("will clamp cursor position if deleting a surround invalidates the old position", function()
require("nvim-surround").setup({
move_cursor = false,
surrounds = {
["c"] = {
add = function()
return { { "```", "" }, { "", "```" } }
end,
find = "(```[a-zA-Z]*\n)().-(\n```)()",
delete = "(```[a-zA-Z]*\n)().-(\n```)()",
},
},
})

set_lines({ "```lua", "print('foo')", "```" })
set_curpos({ 3, 1 }) -- If we delete the ```, the cursor position won't be valid
vim.cmd("normal dsc")
assert.are.same(get_curpos(), { 1, 1 })
check_lines({ "print('foo')" })
end)
end)

0 comments on commit 74f1367

Please sign in to comment.