views:

477

answers:

2

Using vi, how do I substitute the current line number somewhere into the current line? For example, if the cursor is on line 10, I would like to put the number 10 somewhere on that line.

+6  A: 

You want to physically insert the line number, not just display it in the margin? If so -

:s/$/\=line(".")/

This will append it the the end of the line. Replace $ with ^ to prepend to the line.

eduffy
+4  A: 

First: the following are assuming you are using vim, not vi or a workalike or the Heirloom project vi.

Here are a couple of options:

First, if you're going to use :s, then put the cursor on your chosen line and:

 :s/texttoreplace/<C-R>=line(".")<CR>/

where <C-R>= means actually hit ctrl-R then type an equal sign. The prompt will change and you can enter:

 line(".")

and then hit return, as indicated by <CR>. At this point you'll be back at your :s command with the line number inserted. You can do the same trick in insert mode as well (<C-R>=line(".")<CR>).

Second, you can use \= to insert the line number in a regular expression in the same way, but this doesn't work in insert mode or in other places.

Finally, these are useful if you want Control-A in insert and command line mode to insert the current line number:

 :imap <silent> <C-A> <C-R>=line(".")<CR>
 :cmap <C-A> <C-R>=line(".")<CR>

don't add the silent attribute to the cmap line: it inhibits output of the line into the command you're typing until you backspace.

Thomas Kammeyer