@@ -30,6 +30,16 @@ M.pos_to_index = function(pos)
3030 return # table.concat (buffer .get_lines (1 , pos [1 ] - 1 ), " \n " ) + pos [2 ] + 1
3131end
3232
33+ -- Expands a selection to properly contain multi-byte characters.
34+ --- @param selection selection The given selection.
35+ --- @return selection @The adjusted selection , handling multi-byte characters.
36+ --- @nodiscard
37+ M .adjust_selection = function (selection )
38+ selection .first_pos = buffer .get_first_byte (selection .first_pos )
39+ selection .last_pos = buffer .get_last_byte (selection .last_pos )
40+ return selection
41+ end
42+
3343-- Returns a selection in the buffer based on a Lua pattern.
3444--- @param find string The Lua pattern to find in the buffer.
3545--- @return selection | nil @The closest selection matching the pattern , if any.
@@ -58,10 +68,10 @@ M.get_selection = function(find)
5868 if not b_first or not b_last then
5969 return a_first
6070 and a_last
61- and {
71+ and M . adjust_selection ( {
6272 first_pos = M .index_to_pos (a_first ),
6373 last_pos = M .index_to_pos (a_last ),
64- }
74+ })
6575 end
6676 -- Adjust the selection character-wise
6777 local start_col , end_col = cursor_index , b_first
@@ -83,24 +93,24 @@ M.get_selection = function(find)
8393 end
8494 -- If the cursor is inside the range then return it
8595 if b_last and b_first and b_last >= cursor_index then
86- return {
96+ return M . adjust_selection ( {
8797 first_pos = M .index_to_pos (b_first ),
8898 last_pos = M .index_to_pos (b_last ),
89- }
99+ })
90100 end
91101 -- Else if there's a range found after the cursor, return it
92102 if a_first and a_last then
93- return {
103+ return M . adjust_selection ( {
94104 first_pos = M .index_to_pos (a_first ),
95105 last_pos = M .index_to_pos (a_last ),
96- }
106+ })
97107 end
98108 -- Otherwise return the range found before the cursor, if one exists
99109 if b_first and b_last then
100- return {
110+ return M . adjust_selection ( {
101111 first_pos = M .index_to_pos (b_first ),
102112 last_pos = M .index_to_pos (b_last ),
103- }
113+ })
104114 end
105115end
106116
@@ -142,14 +152,14 @@ M.get_selections = function(selection, pattern)
142152 local selections = {
143153 --- @cast first_index integer
144154 --- @cast last_index integer
145- left = {
155+ left = M . adjust_selection ( {
146156 first_pos = M .index_to_pos (offset + first_index - left_len - 1 ),
147157 last_pos = M .index_to_pos (offset + first_index - 2 ),
148- },
149- right = {
158+ }) ,
159+ right = M . adjust_selection ( {
150160 first_pos = M .index_to_pos (offset + last_index - right_len - 1 ),
151161 last_pos = M .index_to_pos (offset + last_index - 2 ),
152- },
162+ }) ,
153163 }
154164 -- Handle special case where the column is invalid
155165 if selections .left .last_pos [2 ] > # buffer .get_line (selections .left .last_pos [1 ]) then
0 commit comments