Skip to content

Commit c9ff80c

Browse files
committed
fix: suggestion acceptance now follows text wrapping
1 parent 07aa571 commit c9ff80c

1 file changed

Lines changed: 49 additions & 2 deletions

File tree

lua/copilot/suggestion/init.lua

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -595,6 +595,52 @@ function M.prev()
595595
end, ctx)
596596
end
597597

598+
local function feedkeys(keys, mode)
599+
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(keys, true, false, true), mode or "i", true)
600+
end
601+
602+
local function longest_prefix_suffix_overlap(left_text, new_text)
603+
local max = math.min(#left_text, #new_text)
604+
for k = max, 1, -1 do
605+
if left_text:sub(-k) == new_text:sub(1, k) then
606+
return k
607+
end
608+
end
609+
return 0
610+
end
611+
612+
local function accept_in_insert_mode(new_text, range)
613+
local cursor = vim.api.nvim_win_get_cursor(0)
614+
local line = cursor[1] - 1
615+
local col = cursor[2]
616+
617+
local current_line = vim.api.nvim_get_current_line()
618+
local left_text = current_line:sub(1, col)
619+
620+
-- Rimuovi da new_text l'eventuale prefisso già scritto dall'utente
621+
local overlap = longest_prefix_suffix_overlap(left_text, new_text)
622+
if overlap > 0 then
623+
new_text = new_text:sub(overlap + 1)
624+
end
625+
626+
local right_delete_count = 0
627+
if range["end"].line == line and range["end"].character > col then
628+
right_delete_count = range["end"].character - col
629+
end
630+
631+
vim.g.__copilot_accept_text = new_text
632+
633+
local recall
634+
if new_text:find("\n", 1, true) then
635+
recall = "<C-R><C-O>=g:__copilot_accept_text<CR>"
636+
else
637+
recall = "<C-R><C-R>=g:__copilot_accept_text<CR>"
638+
end
639+
640+
local keys = string.rep("<Del>", right_delete_count) .. recall .. "<End>"
641+
feedkeys(keys, "i")
642+
end
643+
598644
---@param modifier? (fun(suggestion: copilot_get_completions_data_completion): copilot_get_completions_data_completion)
599645
function M.accept(modifier)
600646
local ctx = get_ctx()
@@ -677,11 +723,12 @@ function M.accept(modifier)
677723
newText = newText .. "\n"
678724
end
679725

680-
vim.lsp.util.apply_text_edits({ { range = range, newText = newText } }, bufnr, encoding)
726+
-- vim.lsp.util.apply_text_edits({ { range = range, newText = newText } }, bufnr, encoding)
727+
accept_in_insert_mode(newText, range)
681728

682729
-- Position cursor at the end of the last inserted line
683730
local new_cursor_line = range["start"].line + #lines
684-
vim.api.nvim_win_set_cursor(0, { new_cursor_line, last_col })
731+
-- vim.api.nvim_win_set_cursor(0, { new_cursor_line, last_col })
685732

686733
if accepted_partial then
687734
suggestion.partial_text = nil

0 commit comments

Comments
 (0)