tags:

views:

1928

answers:

7

I am aware that in vim I can often repeat a command by simply adding a number in front of it. For example, one can delete 5 lines by:

5dd

It's also often possible to specify a range of lines to apply a command to, for example

:10,20s:hello:goodbye:gc

How can I perform a 'vertical edit'? I'd like to, for example, insert a particular symbol, say a comma, at the beggining (skipping whitespace, i.e. what you'd get if you types a comma after Shift-I in command mode) of every line in a given range. How can this be achieved (without resorting to down-period-down-period-down-period)?

+8  A: 

:10,20s/^/,/

Or use a macro, record with

q a i , ESC j h q

use with

@ a

Explanation: 'q a' starts recording a macro to register 'a', 'q' ends recording. There are registers 'a' to 'z' available for this.

Svante
Thanks. What if i wanted the equivalent of a shift-i? That is, skipping over the initial whitespace?
saffsd
:s/^\(\s*\)/\1,/
Svante
Explanation: `^\(\s*\)` captures initial whitespace and saves it into a register, which you can then read with `\1`.
Svante
+2  A: 

I think the easiest is to record a macro, and then repeat the macro as many times as you want. For example to add a comma at the start of every line, you type:

q a I , ESC j q

to repeat that 5 times, you enter

5 @ a
Wimmel
+1  A: 

Apart from the macros, as already answered, for the specific case of inserting a comma in a range of lines (say from line 10 to 20), you might do something like:

:10,20s/\(.*\)/,\1

That is, you can create a numbered group match with \( and \), and use \1 in the replacement string to say "replace with the contents of the match".

Paolo Tedesco
+5  A: 

CTRL-Shift-V enters visual mode blockwise. You can then move (HJKL-wise, as normal), and if you want to insert something on multiple lines, use I.

So for the text:

abc123abc
def456def
ghi789ghi

if you hit CTRL-V with your cursor over the 1, hit j twice to go down two columns, then I, ESC , your text would look like this:

abc,123abc
def,456def
ghi,789ghi

(the multi-line insert has a little lag, and won't render until AFTER you hit ESC).

rampion
Nice. Ctrl-V means uppercase, by the way, you could say Ctrl-Shift-v
Svante
actually, it's either CTRL-v or CTRL-V. Vim is case-insensitive for CTRL- codes (see :help CTRL-{char}).
rampion
+1  A: 

That's what the :normal(ize) command is for:

:10,20 normal I,
Leonardo Constantino
+1  A: 

I use block visual mode. This allows you to perform inserts/edits across multiple lines (aka 'vertical edits').

ONODEVO
A: 

I believe the easiest way to do this is

1) record a macro for one line, call it 'a'; in this case one types

q a I , ESC j q

2) select the block of lines that you want to apply the macro to

3) use the 'norm' function to execute macro 'a' over this block of lines, i.e.,

:'<,'>norm@a
Albert