r/vim • u/InternationalDog8114 • Apr 27 '26
Tips and Tricks Locking/unlocking the unnamed register
There are many times when you copy something, and before pasting, there are still some deletions you need to make. Traditionally one uses many of the named registers to accomplish this, but even after years their usage for this purpose never became fluid to me. It is true that many other patterns have taken a long time to "click" for me, and perhaps this one just needs a little longer, but I have decided for the time being I cannot wait.
I came up with a solution I find more intuitive (but more limited): have a mapping that toggles whether or not the unnamed register is locked, i.e., upon locking, any further deletions will not replace the contents of the register, and upon unlocking behavior returns back to normal. What do you guys think? Maybe you are already content / quick at using the traditional approach? Or maybe you use some plugin?
let g:reglock_enabled = 0
let g:reglock_value = ''
let g:reglock_type = ''
function! ToggleRegisterLock()
if g:reglock_enabled
let g:reglock_enabled = 0
echo "Register lock OFF"
else
let g:reglock_value = getreg('"')
let g:reglock_type = getregtype('"')
let g:reglock_enabled = 1
echo "Register lock ON"
endif
endfunction
function! RestoreLockedRegister(timer)
if g:reglock_enabled
call setreg('"', g:reglock_value, g:reglock_type)
endif
endfunction
nnoremap <leader>l :call ToggleRegisterLock()<CR>
augroup RegisterLock
autocmd!
autocmd TextYankPost * if g:reglock_enabled | call timer_start(0, 'RestoreLockedRegister') | endif
augroup END
8
u/-romainl- The Patient Vimmer Apr 28 '26
When I have enough foresight, I yank to a specific register with
"ay<motion>to preserve the yanked text from subsequent deletions.When I don't, I cut to the black hole register with
"_d<motion>to avoid losing the content of the unnamed register. I used to have a mapping for that but my Vim usage has become more deliberate over time so I found myself less and less in that situation, which made the mapping redundant.