After expanding on the other answer, I thought I should also share my own personal solution for these renaming/refactoring type problems.
nnoremap * :'<,'>s/\C\<<C-r><C-w>\>//g<C-f>$F/i
vnoremap * y:'<,'>s/\C\<<C-r>"\>//g<C-f>$F/i
nnoremap & :%s/\C\<<C-r><C-w>\>//g<C-f>$F/i
vnoremap & y:%s/\C\<<C-r>"\>//g<C-f>$F/i
This provides two handy dual-mode key mappings. To replace all instances of
foo in a document, while your cursor is over an instance of
To replace all instances of not-strictly-word
foo-bar simply make a visual selection and enter
If you want to limit your renaming to a single section (e.g. a function or class), define the area you want to operate in with a visual selection first—I generally use VVY (which technically yanks the selected area, but serves our purpose)—then much as above, while hovering or visually selecting a word, enter:
How it works
Using the remapping for * as it is the more complex, pressing it will cause an ex command line to appear, which will look something like this:
XXX represents where your cursor will be, allowing you to type a replacement and press enter immediately.
\> match the beginning and ending of words respectively, this can sometimes be undesirable (e.g. if you are replacing
bar(1)) and in those cases it is necessary to remove one of the anchors.
Some people may already use the * key binding, whose default action serves a similar purpose (finding the next instance of the word under the cursor), obviously you can bind to something else—and let me know if you find a reliable cross-platform way to bind Shift-Alt-* or some such, otherwise
<leader>* doesn't do anything terribly useful.
I have found that this binding can work (to a limited degree) in some Vim emulators, e.g. VsVim for Visual Studio—if it defined in simpler terms
nnoremap * :'<,'>s/\C\<<c-r><c-w>\>/
nnoremap & :%s/\C\<<c-r><c-w>\>/
It can also be modified (on the fly, or as part of the binding) to use everybody's favorite Vim plugin author's magic
:S search, and therefore replace
BAR. As someone else put it, "We do not deserve Tim Pope." https://stackoverflow.com/a/23144847/912236
If anyone would like to write a more complex version that automatically dropped the begin/end of word anchors, when the search string didn't begin/end with a word: that would be great.
There are other instance:
var foo, and
# comment foo where differentiation might be handy, and there are times when it might be nice to have a copy of the original text duplicated so you can make a tiny edit. I generally find these cases to be less common/annoying that you might think. If you want that kind of smart refactoring, use an IDE.