I just googled something I’ve always wanted to know how to do in vim, and was surprised how quickly I found the answer.
In vim, there are separate modes for searching and commands. This generally works well as they have separate completion buffers and since I do them a lot, it keeps my command history from cluttering up my search history and vice versa. The area where I’ve wished that they were unified is when I want to convert from a search to a substitution expression. Normally in vim you do search expressions in search mode and command expressions in command mode. For example, if I wanted to search for trailing whitespace I might type:
/\s\s*
If I want to replace it with an empty string through the whole file I might type:
:%s/\s\s*//g
I can’t remove the / at the front of the command line with a backspace and replace it with a colon, so until I learned the tip I’m about to reveal I had to retype it. No longer.
The StackOverflow answer I found for the query, Convert vim / search to search and replace without retyping regular expression, suggests this remarkably simple technique:
You can type
/search_termand then
:%s/<ctrl-r>// etcwhere you actually press
ctrl+r
and then/
to insert the search term.
It works! No longer do I desire for search and command modes to be unified.
While `ctrl-r /` certainly has its uses, in the example you’ve given, you could just as well leave the search field of the substitute command empty. When no pattern is provided for the substitute command, it will use the last search pattern.
Drew,
Thanks! That’s the other popular answer in Stack Overflow too. I also remember reading it, ages ago, but somehow I forgot it. The
ctrl-r /
trick is completely new to me, though.I use :%s/\s\s*//gc frequently. Have the c for confirm option has been very useful for me.
I forgot about that! Thanks!