Many useful mappings need to temporarily save text.Some practical examples are: Move line up/downnnoremap <c-j> ddpnnoremap <c-k> ddkP Substitute word under cursor (use `cc` instead of default `S`)nnoremap SS yiw:s/<c-r>/nnoremap S% yiw:%s/<c-r>/ Substitute selectionvnoremap SS y:s/<c-r>/vnoremap S% y:%s/<c-r>/These mappings has to yank a piece of text for later use. I have always used the default register for this but there is a problem with this approach.By using the default register in the mapping I am overwriting it's previous content.If the user has yanked some text and then executes one of the mappings the yanked text will be overwritten. This is something very minor but it has started to annoy me lately.There has to be a better way to do this.Is there a way to make mappings like these but do not affect the global Vim environment? If not then what is your solution to this problem?
How to make mappings that yank text without overwriting the global registers
key bindings;vimscript;register
Move line up/downnnoremap <key> :<C-u>silent! move+<CR>==nnoremap <key> :<C-u>silent! move-2<CR>==Explanation:<C-u> is used to get rid of any automatically added range (safer but not strictly necessary):silent! prevents useless output:move+ moves the line below the line below:move-2 moves the line below the second line aboveSee::help c_ctrl-u:help :silent:help :move:help rangeSubstitute word under cursornnoremap <key> :s/\<<C-r><C-w>\>/nnoremap <key> :%s/\<<C-r><C-w>\>/Explanation:In the command-line, <C-r><C-w> is used to insert the word under the cursor.\<pattern\> restrict matches to whole words so you match pattern but not mypatterniscoolSee::help c_ctrl-r_ctrl-w:help \<Substitute selectionThis one is a little trickier: we need to yank the visual selection because there's no equivalent of <C-r><C-w> in that context but it's relatively easy to go around that limitation and avoid side effects with a bit of vimscript:function! GetVisualSelection()     save the content of register v (it could be any alphabetic register)    let old_reg = getreg(v)     reselect the visual selection and yank it in register v    normal! gvvy     get the content of register v (what we just yanked)    let raw_search = getreg(v)     restore register v    call setreg(v, old_reg)     return a sanitize version of the yanked text     useful if the text contains special characters or is multiline    return substitute(escape(raw_search, '\/.*$^~[]'), \n, '\\n', g)endfunctionxnoremap <key> :<C-u>s/<C-r>=GetVisualSelection()<CR>/xnoremap <key> :<C-u>%s/<C-r>=GetVisualSelection()<CR>/See::help :function:help :let:help registers:help :normal:help gv:help substitute():help escape():help c_ctrl-r_=