Vim - Visual Block mode pasting before/after columns

Say you have tons of lines of text that look like this:

123abc
456def
789ghi
...

Say you want to insert some other really long text between the numbers and letters on each line, ending up with:

123SomeReallyLongTextInsertedHereabc
456SomeReallyLongTextInsertedHeredef
789SomeReallyLongTextInsertedHereghi

You can use Visual Block mode (CTRL+V) to highlight some columns, then insert text (using I or A) before or after each column all at once, which is amazingly useful because you only have to type the new text once. But say you don't want to type the new text even once; you want to copy/paste it into each line instead, because the text you want to insert is really long, or you're lazy.

My first instinct would've been to go into Visual Block mode, highlight some columns, then hit p or P. But that fails. It only pastes (and obliterates) the first line of text and leaves the other columns alone. If you look at :h blockwise-operators, you can see that the number of available operators is somewhat limited; insert, append, replace, change, indent. No paste.

One way to do this is to go into Visual Block mode, highlight some columns, use I to go into insert mode, then use ^R" (that's CTRL-R ") to paste register contents. Then hit ESC. (Replace " with the name of the register that contains the text you want to paste.) CTRL-R in Insert mode inserts the contents of a register. See also :h i_CTRL-R.

Another way would be to use a macro (which vim calls "complex-repeat"). In normal mode, something like qq^2lpjq would record a macro that does what we want. Then you put the cursor on the first line and do 3@q in normal mode to run the macro three times, or 100@q to run it 100 times, depending how many lines you have.

I'm sure there are other ways too.

Tags:

2 Responses to “Vim - Visual Block mode pasting before/after columns”

  1. Quoth Ivar Refsdal:

    Nice CTRL+R feature. Thanks. :)

    Just to add:

    You can do :set nowrapscan and then do something like 999@q without having to
    worry about endless repeats on the last line. (Given of course you want to apply the macro on all lines.)

    (Emacs also has rectangles: http://jamesthornton.com/emacs/node/emacs_68.html They work OK too.)

  2. Quoth Brian:

    Oh nice. I'm adding that to my .vimrc.

Leave a Reply

You can use these tags in comments (Note: HTML is automatically escaped inside <pre> tags, nowhere else, so if you post source code, put it in <pre>):

<pre lang="some_programming_language"> 
<em>
<strong>
<a href="url">

NOTE: Comments are automatically spam-filtered. If your comment fails to appear, it was likely munched by the filter. Try not to link-spam or post anything that looks like it was typed by a robot.