23

I guess, the problem is pretty common. Let's say, we have a source file and wish to replace some string with another string.

Usually, I use the following command:

:%s/test/testValue/gc

But, what if the string is pretty long and we need just to touch it up? It is boring to type something like that:

%s/someLongAndDirtyString/somelongAndDirtystring/gc

Is it possible to place a cursor on someLongAndDirtyString word, press some magic key and get the following in the last line?

%s/someLongAndDirtyString/someLongAndDirtyString/gc

Then we may change the new string a bit and proceed with replacing.

Sure, it is just an idea. Please, provide me with the best way of doing such replacements.

Thanks

Benoit
  • 76,634
  • 23
  • 210
  • 236
Stas
  • 11,571
  • 9
  • 40
  • 58

2 Answers2

29

You might be interested in this answer I gave on how to use registers, but here are four methods to do that:

Method 1

While editing a command, hit CTRLR then CTRLW to insert word under the cursor.

Also see :help c_CTRL-R

Method 2

Go to your word, hit *, and do :%s//replacement/g. When no search pattern is used, last search pattern, taken from register @/, is used.

Method 3 (you will probably like that one)

Do a :nnoremap <f12> :%s/<c-r><c-w>/<c-r><c-w>/gc<c-f>$F/i (ctrl-f is determined by the 'cedit' option)

You can put this mapping into your .vimrc.
This will map the F12 key to what you want, and your cursor will be left where you want.

Method 4

Go to your word, hit *, and do :%s//CTRLR,//gc
CTRL-R then / inserts contents of your search register.

Community
  • 1
  • 1
Benoit
  • 76,634
  • 23
  • 210
  • 236
  • 1
    Thanks a lot! I won't be surprised if there is a way to do in-place replacing (as in snippets :-) It would be really cool! – Stas Nov 05 '10 at 14:08
  • If you want to have on-the-fly correction of common errors, see `:help :iabbrev` or `:help abbreviations` – Benoit Nov 05 '10 at 14:09
14

Well, if your cursor is on the word you want to replace, you can hit * which will highlight and search for the word, and then you can type:

:%s//newstring/gc

and vim will insert the last searched string in between the slashes.

jmans
  • 5,648
  • 4
  • 27
  • 32