local userregs = require("vim.userregs") -- ASCII-safe register name local regname = "\22" -- Return the contents of the last visual selection local function read_last_visual() local bufnr = vim.api.nvim_get_current_buf() local start_pos = vim.fn.getpos("'<") local end_pos = vim.fn.getpos("'>") if not start_pos or not end_pos then vim.notify("[userregs] No visual selection", vim.log.levels.WARN) return { lines = {}, type = "V" } end local start_lnum = start_pos[2] - 1 -- 0-indexed local end_lnum = end_pos[2] -- end line is exclusive local lines = vim.api.nvim_buf_get_lines(bufnr, start_lnum, end_lnum, false) return { lines = lines, type = "V", -- Assume linewise for now additional_data = {}, } end -- Replace the last visual selection with new content local function write_last_visual(_, content) local bufnr = vim.api.nvim_get_current_buf() local start_pos = vim.fn.getpos("'<") local end_pos = vim.fn.getpos("'>") if not start_pos or not end_pos then vim.notify("[userregs] No visual selection to write into", vim.log.levels.ERROR) return end local start_lnum = start_pos[2] - 1 local end_lnum = end_pos[2] -- Replace the range with the new content vim.api.nvim_buf_set_lines(bufnr, start_lnum, end_lnum, false, content.lines or {}) end userregs.register_handler(regname, { put = function() return read_last_visual() end, yank = write_last_visual, })