1

I am using following code (from somewhere on the net but I forgot the page) to add line numbers to text files:

:%s/^/\=printf('%d] ' , line('.'))/g 

I have tried to modify it to accept ranges:

command -range=% Addln <line1>,<line2>s/^/\=printf('%d] ' , line('.'))/g 

It works for whole file all right, but when I try to apply it to a selection, it adds line numbers starting from file line number and not 1. How can I change it so that it adds line numbers to the selection starting from 1? Thanks.

rnso
  • 23,686
  • 25
  • 112
  • 234
  • 1
    Without the command, use `line("'<")`, see https://stackoverflow.com/questions/252766/add-line-numbers-to-source-code-in-vim – Luc Hermitte May 30 '17 at 09:33

1 Answers1

0

As the <line1> identifier will be replaced by Vim with the actual first line number of the command's range, you can use that to do arithmetic with it: Just subtract it from the current line('.') and add one for a 1-based numbering:

command -range=% Addln <line1>,<line2>s/^/\=printf('%d] ' , line('.') - <line1> + 1)/g
Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324