Table of contents
Problem #1
When you want to replace one word with another, you have to do the following actions:
- Copy a word or some text
- Turn on the VISUAL_MODE by pressing
v - Select a word or text that you want to replace
- Hit
p to replace the word
Which is not what you usually want.
Let's consider the real-case scenario. You have the following code:
const hello = 'Hello World.';
const hi = 'Hi Word.';
You want to replace
fW - go to the wordWorld yiw - copy the wordj - go downFW - go to the wordWord v - enter the VISUAL_MODEe - select the full wordp - paste previously copied word
Problem #2
Another problem is when you want to replace multiple places with the same word.
We have:
const hello = 'Hello World.';
const hi = 'Hi Word.';
const greetings = 'Greetings Word.';
fW - go to the wordWorld yiw - copy the wordj - go downFW - go to the wordWord v - enter the VISUAL_MODEe - select the full wordp - paste previously copied word
And now, you need to replace the word
yiw - copy the wordWorld at the place where you arej - go downfW - go to the wordWorld v - enter the VISUAL_MODEe - select the full wordp - paste previously copied word
A lot of extra work, right?
Instead, you can use the an alternative register.
For example, to copy to register
But it looks like a long sequence of keys to press.
Solution #1
We can implement our own operator, which will help with the substitution. The current operator works with motions as well.
nnoremap <expr> x SpecialChange()
function! SpecialChange(type = '')
if a:type == ''
set opfunc=SpecialChange
return 'g@'
endif
execute 'normal! `[v`]"_d"' .. v:register .. 'P'
endfunction
So, the formula is
Let's try to solve Problem #1 with this operator.
fW - go to the wordWorld yiw - copy the wordj - go downFW - go to the wordWord
From this point, we don't need to select the word, as we can replace it by simply using the motion:
xiw - replace the current word (Word ) withWorld by using the previously implemented custom operator
Now, let's try to solve Problem #2:
fW - go to the wordWorld yiw - copy the wordj - go downFW - go to the wordWord xiw - replaceWord with the wordWorld
Our operator gives us the ability to replace the word without overriding the word that copied to the default register.
j - go downfW - go to the wordWorld xiw - replace the current word (Word ) withWorld by using the previously implemented custom operator
Solution #2
There is a plugin called vim-subversive.
It can do everything described in Solution #1 and much more.
Summary
If you hesitate and don't know what to choose, I recommend installing and playing with the plugin. After some time, if you realize you're using a single feature from the plugin, you can switch to the operator we wrote above. Personally, I use a custom operator as it covers all my needs.