-
I want to insert undo breakpoints when performing a completion so it's easy to go return when e.g. selecting the wrong snippet. My current solution looks like this, utilzing an autocommand to combine vim mapping and calling lua func vim.api.nvim_create_user_command("CmpComplete", function()
if cmp.visible() then
cmp.mapping.confirm({
behavior = cmp.ConfirmBehavior.Insert,
select = true,
})()
end
end, {})
vim.keymap.set("i", "<c-i>", "<c-g>u<cmd>CmpComplete<CR>", {}) Any advice on a more ellegant way on achiveing this? E.g. though the mapping option? I couldn't find a way to create breakpoints from lua myself. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I think in your cmp mapping you can do something like this mapping = {
['<C-i>'] = cmp.mapping({
i = function(fallback)
if cmp.visible() then
local CTRLg_u = vim.api.nvim_replace_termcodes('<C-g>u', true, true, true)
vim.api.nvim_feedkeys(CTRLg_u, 'n', true)
return cmp.confirm({
behavior = cmp.ConfirmBehavior.Insert,
select = true,
})
end
fallback()
end,
}),
} |
Beta Was this translation helpful? Give feedback.
-
I really like being able to undo the autocompletion, however one thing is really annoying for me: I put it down here for anyone that may be interested. -- return the timestamp of the last (or second last if inverse_index = 1) undo breaks set
local last_edit_ts = function(inverse_index)
local tree = vim.fn.undotree().entries
if #tree <= inverse_index then return 0 end
return tree[#tree-inverse_index].time
end
-- when an autocompletion is performed we set an undo breaks first, so that if I undo I don't loose the text I manually typed
local keys = vim.api.nvim_replace_termcodes("<C-g>u", true, false, true)
local confirm_fn = cmp.mapping.confirm({ select = true })
local last_tab_undo_ts = 0
local confirm_fn_with_undo_checkpoint = function(fallback)
if cmp.visible() then
vim.api.nvim_feedkeys(keys, "i", false)
last_tab_undo_ts = last_edit_ts(0)
confirm_fn(fallback)
else
fallback()
end
end
-- when I undo, if the last break was set by the nvim_cmp autocompletion I also perform a jump
-- to the previous cursor position (this is because if the autocompletion has automatically added
-- some imports, the cursor would be teleported at the top of the file)
vim.keymap.set("n", "u", function()
if last_edit_ts(1) == last_tab_undo_ts then
return vim.api.nvim_replace_termcodes("u`'", true, false, true)
else
return vim.api.nvim_replace_termcodes("u", true, false, true)
end
end, { expr = true })
cmp.setup({
mapping = cmp.mapping.preset.insert({
["<Tab>"] = confirm_fn_with_undo_checkpoint,
}),
...
}) |
Beta Was this translation helpful? Give feedback.
I think in your cmp mapping you can do something like this