How can I insert text in the middle of the line to multiple lines in Vim?

Sasha picture Sasha · Jul 23, 2009 · Viewed 56.9k times · Source

Say I have ten lines and I want to prepend text to some word that occurs in those lines? It does not have to be at the beginning of the line.

From:

sdfsd   foo sdfsd
sfsd    foo fsdf
sdfsdf  foo  sdfsdf

to:

sdfsd   bar(foo sdfsd
sfsd    bar(foo fsdf
sdfsdf  bar(foo  sdfsdf

Is it also possible to not only prepend the bar( but actually surround foo with bar(foo)?

I would also like a quick way to append // comments to multiple lines (C-style comments).

I use Vim/GVim 7.2.

Answer

sth picture sth · Jul 23, 2009

Go to the first foo, press Ctrl-v to enter visual block mode and press down until all the lines with foo are marked. Then press Shift-i to insert at the beginning (of the block). When you are finished and press Esc, the inserted characters will be added to each line at the left of the marked block.

To insert at the end, press again Ctrl-v, move up/down to mark all affected lines and then press End or $ to extend the selection until the end of the lines. Now you can press Shift-a to append at the end of all the lines, just like previously with Shift-i.

The visual selection can also be done with normal movement commands. So to comment a whole block in C you could move to the opening brace and type Ctrl-v % Shift-i // Esc.