Sticky Yank: Keep the cursor position when yanking

· Nano Tips for Vim


One of the minor annoyances of vim for me was that yank operations would move the cursor to the beginning of the affected text, for instance, yap would move the cursor to the beginning of the paragraph.

There are plugins such as yanky.nvim that solve this problem, but they have many more features I didn't really need. So I came up with a short snippet that solves the problem for me.

It works by essentially hooking into any yank operation to save the cursor position, and then uses the TextYankPost autocommand to restore the cursor after the yank operation.

 1local cursorPreYank
 2vim.keymap.set({ "n", "x" }, "y", function()
 3	cursorPreYank = vim.api.nvim_win_get_cursor(0)
 4	return "y"
 5end, { expr = true })
 6vim.keymap.set("n", "Y", function()
 7	cursorPreYank = vim.api.nvim_win_get_cursor(0)
 8	return "y$"
 9end, { expr = true })
10
11vim.api.nvim_create_autocmd("TextYankPost", {
12	callback = function()
13		if vim.v.event.operator == "y" and cursorPreYank then
14			vim.api.nvim_win_set_cursor(0, cursorPreYank)
15		end
16	end,
17})