1

In Vim it is possible to insert text in multiple lines at once with the I command, like in an answer Stack Overflow question How do I insert text at beginning of a multi-line selection in vi/Vim?. However, this only works for real inserting. If I want to remove some characters at the same time this doesn't work.

For example, I want to change

000 one
000 two
000 three
000 four

to

111 one
111 two
111 three
000 four

I would do this by calling ^V3ggllx to remove the 000 from the first three lines and then ^V3ggI111^[ to insert the 111 at the same positions, which seems quite awkward to me. (The above means, going to visual blockwise mode, marking all the zeros in the first three lines and removing them. Then go to visual blockwise mode again, marking the start of the first three lines, going to insert mode for multiple lines, inserting the 111 and exiting with Esc.)

There must be a better way to do this. The most annoying thing is that I have to select the region again after removing the zeros. If the region was still selected after the removal it would be fine. Also if would be possible in multiple insert mode to remove characters, it would be fine too. But if I try this, only the first line is changed.

Community
  • 1
  • 1
radlan
  • 2,393
  • 4
  • 33
  • 53
  • Thanks to you all. The best answer for this specific question was of course melpomenes, but the other answers provided other very useful hints, too. – radlan Jan 22 '13 at 09:22

3 Answers3

5

Re-selection is the simple and quick gv; you can then use I111^[ to insert the new text. But, as @melpomene's answer shows, this isn't actually necessary.

(But I thought I'd mention it so you can apply this new knowledge in other situations.)

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
2

Alternatively, since you're replacing with the same character, you can use r after selecting:

^V2jer1

This has the benefit of avoiding insert mode altogether.

By the way, 3G accomplishes the same thing as 3gg.

Nikita Kouevda
  • 5,508
  • 3
  • 27
  • 43
1

Once you have your column of 0s selected, replacing them with 1s is as easy as hitting r1:

<C-v>2jer111

(But Nikita already posted this… aaah multi-tasking…)

Depending on the complexity of your real usecase, a substitution might be a viable alternative:

V2j:s/^000/111<CR>

Since we are at it, using :normal and <C-a> could help you with this specific situation:

V2j:norm 111<C-a>
romainl
  • 186,200
  • 21
  • 280
  • 313
  • Interesting approach with `^A`, but note that if `nrformats` includes `octal` (which it does by default), Vim interprets `000` as octal, and `111^A` on `000` results in `0157`. `73^A` would give `0111`, but still with a leading zero. – Nikita Kouevda Jan 21 '13 at 16:41
  • I always forget that *my* settings are not *everybody*'s settings. ;-) – romainl Jan 21 '13 at 17:06