views:

233

answers:

4

Let's say I have a word selected in visual mode. I would like to perform a substitution on that word and all other instances of that word in a file by using s//. Is there a way to use the highlighted text in the s/<here>/stuff/ part without having to retype it?

+4  A: 

If you searched for your text before you can use

CTRL-R /

to insert the last search item in your search and replace string.

You can check this page for other similar tricks:

http://www.vim.org/htmldoc/insert.html

Vincent
+14  A: 

Sure. If you selected the word, just "y"ank it, and then type:

:%s/<ctrl-r>"/something else/g

Where is pressing ctrl key with r key, and " is just " character.

All keypresses:

y:%s/<ctrl-r>"/what to put/g<enter>
depesz
Wow, cool! Where can I find that trick in the vim documentation?
innaM
Not sure. Ctrl-r is pretty well known thing.
depesz
@Manni: :h c_CTRL-R
Luc Hermitte
A: 

Another way to access register contents from the command line is via @ variables. So if you yank text into the default register, it'll be in a variable called @".

:exe '%s/' . @" . '/stuff/'

Here's a mapping to make this easy to type:

vmap <Leader>s y:exe '%s/' . @" . '//g'<Left><Left><Left>

Now you can highlight something in visual mode, type \s, type your replacement and hit Enter. depesz's version also makes a good mapping (almost exactly as he typed it):

vmap <Leader>s y:%s/<c-r>"//g<Left><Left>
Brian Carper
+4  A: 

You don't have to yank the word, place your cursor on the word and then:

:%s/<C-r><C-w>/bar/g
Pierre-Antoine LaFayette
Sweet! That is another one I was curious about!
j0rd4n