Skip to content

Commit 06c00bc

Browse files
authored
fix: properly handle ranges ending with a newline (#828)
Fixes #827 . The changes are similar to the ones in #812 , but they are different from the function mentioned in a comment of that PR (#812 (comment)) because said function assumes that the range returned is end-inclusive, while this plugin currently is treating the range as end_exclusive. This bug was surfaced by #687 (because and `end_row, end_col` pair like `4, 0` becomes `4, -1` after the change), but this wasn't working properly before #687 either. The behavior before that PR was to also select the first character of the next line (so, one character after the newline).
1 parent 7024f86 commit 06c00bc

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

lua/nvim-treesitter-textobjects/move.lua

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,19 @@ local function goto_node(range, goto_end, avoid_set_jump)
2525
vim.cmd('normal! v')
2626
end
2727

28+
-- end positions with `col=0` mean "up to the end of the previous line, including the newline character"
29+
if end_col == 0 then
30+
end_row = end_row - 1
31+
end_col = #api.nvim_buf_get_lines(0, end_row, end_row + 1, true)[1]
32+
else
33+
end_col = end_col - 1
34+
end
35+
2836
-- Position is 1, 0 indexed.
2937
if not goto_end then
3038
api.nvim_win_set_cursor(0, { start_row + 1, start_col })
3139
else
32-
api.nvim_win_set_cursor(0, { end_row + 1, end_col - 1 })
40+
api.nvim_win_set_cursor(0, { end_row + 1, end_col })
3341
end
3442
end
3543

lua/nvim-treesitter-textobjects/select.lua

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,23 @@ local function update_selection(range, selection_mode)
2020
vim.cmd.normal({ selection_mode, bang = true })
2121
end
2222

23-
local end_col_offset = 1
23+
-- end positions with `col=0` mean "up to the end of the previous line, including the newline character"
24+
if end_col == 0 then
25+
end_row = end_row - 1
26+
-- +1 is needed because we are interpreting `end_col` to be exclusive afterwards
27+
end_col = #api.nvim_buf_get_lines(0, end_row, end_row + 1, true)[1] + 1
28+
end
2429

30+
local end_col_offset = 1
2531
if selection_mode == 'v' and vim.o.selection == 'exclusive' then
2632
end_col_offset = 0
2733
end
34+
end_col = end_col - end_col_offset
2835

2936
-- Position is 1, 0 indexed.
3037
api.nvim_win_set_cursor(0, { start_row + 1, start_col })
3138
vim.cmd('normal! o')
32-
api.nvim_win_set_cursor(0, { end_row + 1, end_col - end_col_offset })
39+
api.nvim_win_set_cursor(0, { end_row + 1, end_col })
3340
end
3441

3542
local M = {}

0 commit comments

Comments
 (0)