ncphillips
ncphillips

Reputation: 736

VIM: Insert a line number, with a space after

I need to insert the line number before each line of text using Vim, and there has to be a space after the line number. For example, if this was TestFile:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Morbi nunc enim, vehicula eget, ultricies vel, nonummy in, turpis.

It should look like this

1 Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
2 Morbi nunc enim, vehicula eget, ultricies vel, nonummy in, turpis.

I have been using the command :%s/^/\line('.')/ with a number of variations, but I cannot figure out how to get the space at the end.

Any ideas?

Upvotes: 4

Views: 375

Answers (3)

William Pursell
William Pursell

Reputation: 212674

This is probably easiest with an external tool:

:%!nl -ba -w1 -s' '

Upvotes: 1

chtenb
chtenb

Reputation: 16224

You can use a macro. First make sure you have a 0 before the first line and have your cursor placed on it:

0 Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Morbi nunc enim, vehicula eget, ultricies vel, nonummy in, turpis.
foo
bar
etc...

Then perform this key sequence to store the right macro in register a: qaywjP0<C-A>q. Now press @a to execute the macro. Use a quantifier to execute it multiple times.

Type :help q to find out more about recording macro's.

Upvotes: 0

johnsyweb
johnsyweb

Reputation: 141998

You were very close!

This substitution will do the job by concatenating the string ' ' to the line number:

%s!^!\=line('.').' '!

Upvotes: 8

Related Questions