views:

3277

answers:

5

How can I add line numbers to a range of rows in vim? Not as in ":set nu" - this just displays numbers, but doesn't add them to the file.

+8  A: 

cat -n adds line numbers to its input. You can pipe the current file to cat -n and replace the current buffer with what it prints to stdout. Fortunately this convoluted solution is less than 10 characters in vim:

 :%!cat -n

Or, if you want just a subselection, visually select the area, and type this:

 :!cat -n

That will automatically put the visual selection markers in, and will look like this after you've typed it:

 :'<,'>!cat -n

In order to erase the line numbers, I recommend using control-v, which will allow you to visually select a rectangle, you can then delete that rectangle with x.

Jerub
+3  A: 

With Unix-like environment, you can use cat or awk to generate a line number easily, because vim has a friendly interface with shell, so everything work in vim as well as it does in shell.

:%!call -n

or

:%!awk '{print NR,$0}'

But, if you use vim in MS-DOS, of win9x, win2000, you loss these tookit. here is a very simple way to archive this only by vim:

fu! LineIt()
  exe ":s/^/".line(".")."/"
endf

Or, a sequence composed with alphabet is as easy as above:

exe "s/^/".nr2char(line("."))."/"

You can also use a subst:

:g/^/exe ":s/^/".line(".")."^I/"


You can also only want to print the lines without adding them to the file:

"Sometimes it could be useful especially be editing large source files to print the line numbers out on paper. To do so you can use the option :set printoptions=number:y to activate and :set printoptions=number:n to deactivate this feature. If the line number should be printed always, place the line set printoptions=number:y in the vimrc."

VonC
+6  A: 

On a GNU system: with the external nl binary.

:%!nl

Martin v. Löwis
+13  A: 

With

:%s/^/\=line('.')/
Luc Hermitte
Tried doing this on a visual selection (where 1 would be the first line in selection) however it starts number at that line numeber in the file. Any way to modify the start number? Thanks!
Jason
Of course. Change "line('.')" to "(offset+line('.'))".
Luc Hermitte
+2  A: 

The "VisIncr" plugin is good for inserting columns of incrementing numbers in general (or letters, dates, roman numerals etc.). You can control the number format, padding, and so on. So insert a "1" in front of every line (via :s or :g or visual-block insert), highlight that column in visual-block mode, and run one of the commands from the plugin.

Brian Carper