diff --git a/lua/copilot/suggestion/init.lua b/lua/copilot/suggestion/init.lua index a11c824b..1d3103c1 100644 --- a/lua/copilot/suggestion/init.lua +++ b/lua/copilot/suggestion/init.lua @@ -595,6 +595,57 @@ function M.prev() end, ctx) end +local function feedkeys(keys, mode) + vim.api.nvim_feedkeys( + vim.api.nvim_replace_termcodes(keys, true, false, true), + mode or "i", + true + ) +end + +local function accept_in_insert_mode(new_text, range) + local cursor = vim.api.nvim_win_get_cursor(0) + local line = cursor[1] - 1 + local col0 = cursor[2] + local col1 = vim.fn.col(".") + + local current_line = vim.api.nvim_get_current_line() + local lines = vim.split(new_text, "\n", { plain = true }) + + local first_line = lines[1] or "" + local adjusted_first_line, outdent = suggestion_util.get_display_adjustments( + first_line, + range.start.character, + col1, + current_line + ) + + lines[1] = adjusted_first_line + new_text = table.concat(lines, "\n") + + local right_delete_count = 0 + if range["end"].line == line and range["end"].character > col0 then + right_delete_count = range["end"].character - col0 + end + + vim.g.__copilot_accept_text = new_text + + local recall + if new_text:find("\n", 1, true) then + recall = "=g:__copilot_accept_text" + else + recall = "=g:__copilot_accept_text" + end + + local keys = + string.rep("", outdent) + .. string.rep("", right_delete_count) + .. recall + .. "" + + feedkeys(keys, "i") +end + ---@param modifier? (fun(suggestion: copilot_get_completions_data_completion): copilot_get_completions_data_completion) function M.accept(modifier) local ctx = get_ctx() @@ -677,11 +728,12 @@ function M.accept(modifier) newText = newText .. "\n" end - vim.lsp.util.apply_text_edits({ { range = range, newText = newText } }, bufnr, encoding) + -- vim.lsp.util.apply_text_edits({ { range = range, newText = newText } }, bufnr, encoding) + accept_in_insert_mode(newText, range) -- Position cursor at the end of the last inserted line local new_cursor_line = range["start"].line + #lines - vim.api.nvim_win_set_cursor(0, { new_cursor_line, last_col }) + -- vim.api.nvim_win_set_cursor(0, { new_cursor_line, last_col }) if accepted_partial then suggestion.partial_text = nil