Skip to content

Commit

Permalink
fix: Ensure that start_col and end_col selection is awlays within bounds
Browse files Browse the repository at this point in the history
Closes #432

Signed-off-by: Tomas Slusny <[email protected]>
  • Loading branch information
deathbeam committed Oct 30, 2024
1 parent 6f0a5e1 commit e172d73
Showing 1 changed file with 27 additions and 8 deletions.
35 changes: 27 additions & 8 deletions lua/CopilotChat/select.lua
Original file line number Diff line number Diff line change
@@ -1,27 +1,46 @@
local M = {}

local function get_selection_lines(bufnr, start_line, start_col, finish_line, finish_col, full_line)
-- Exit if no actual selection
if start_line == finish_line and start_col == finish_col then
return nil
end

-- Get line lengths before swapping
local function get_line_length(line)
return #vim.api.nvim_buf_get_lines(bufnr, line - 1, line, false)[1]
end

-- Swap positions if selection is backwards
if start_line > finish_line or (start_line == finish_line and start_col > finish_col) then
start_line, finish_line = finish_line, start_line
start_col, finish_col = finish_col, start_col
end

-- Handle full line selection
if full_line then
start_col = 1
finish_col = get_line_length(finish_line)
end

-- Ensure columns are within valid bounds
start_col = math.max(1, math.min(start_col, get_line_length(start_line)))
finish_col = math.max(start_col, math.min(finish_col, get_line_length(finish_line)))

-- Get selected text
local ok, lines = pcall(
vim.api.nvim_buf_get_text,
bufnr,
start_line - 1,
start_col - 1,
finish_line - 1,
finish_col,
{}
)
if not ok then
return nil
end

local finish_line_len = #vim.api.nvim_buf_get_lines(bufnr, finish_line - 1, finish_line, false)[1]
if finish_col > finish_line_len or full_line then
finish_col = finish_line_len
end

local lines =
vim.api.nvim_buf_get_text(bufnr, start_line - 1, start_col - 1, finish_line - 1, finish_col, {})

local lines_content = table.concat(lines, '\n')
if vim.trim(lines_content) == '' then
return nil
Expand Down

0 comments on commit e172d73

Please sign in to comment.