I stumbled upon this snippet source:
augroup yank_restore_cursor
autocmd!
autocmd VimEnter,CursorMoved *
\ let s:cursor = getpos('.')
autocmd TextYankPost *
\ if v:event.operator ==? 'y' |
\ call setpos('.', s:cursor) |
\ endif
augroup END
I already know how to convert get v:event --> vim.event.operator
. The problem is that we have two autocommands, VimEnter,CursorMoved
to store the cursor position and a third and separate event to restore the cursor position TextYankPost
.
I already have this:
yank_restore_cursor = {
event = "TextYankPost",
pattern = "*",
callback = function()
local cursor = vim.fn.getpos('.')
if vim.v.event.operator == 'y' then
vim.fn.setpos('.', cursor)
end
end,
},
If we use a print like print("event match")
we see it captures the YnakPost, the problem is the missing part.
It seems like I figured out a solution, I have only one question about the variable where I store the cursor position, if is needed and how to restrict this variable to the augroups.yankpost scope.
local augroups = {}
augroups.yankpost = {
save_cursor_position = {
event = { "VimEnter", "CursorMoved" },
pattern = "*",
callback = function()
cursor_pos = vim.fn.getpos('.')
end,
},
highlight_yank = {
event = "TextYankPost",
pattern = "*",
callback = function ()
vim.highlight.on_yank{higroup="IncSearch", timeout=400, on_visual=true}
end,
},
yank_restore_cursor = {
event = "TextYankPost",
pattern = "*",
callback = function()
local cursor = vim.fn.getpos('.')
if vim.v.event.operator == 'y' then
vim.fn.setpos('.', cursor_pos)
end
end,
},
}
for group, commands in pairs(augroups) do
local augroup = vim.api.nvim_create_augroup("AU_"..group, {clear = true})
for _, opts in pairs(commands) do
local event = opts.event
opts.event = nil
opts.group = augroup
vim.api.nvim_create_autocmd(event, opts)
end
end
Bonus mappings to allow you to copy “inner line” and a whole line:
map("x", "al", ":<C-u>norm! 0v$<cr>", { desc = "Line text object" })
map("x", "il", ":<C-u>norm! _vg_<cr>", { desc = "Line text object" })
map("o", "al", ":norm! 0v$<cr>", { desc = "Line text object" })
map("o", "il", ":norm! _vg_<cr>", { desc = "Line text object" })