Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In Vim, can I supply a format string, yank it, and paste it with formatted values in a range?. An example in Python 2 would be:

for i in range(1, 3): print "This is line %d" % i

If this is not possible in Vim, would it be so in Emacs, or another editor?

share|improve this question
up vote 0 down vote accepted

It's not completely clear to me what you want, but in Vim you could do something like this:

:for i in range(line('$')) | call append(i+i, printf("this is line %d:", i+1)) | endfor

The reason I use "i+i" is that, as lines are inserted into the buffer the line numbers change, and this corrects for that. (If you have a different "starting point" in your range, your correction algorithm will have to be more complicated.)

Or if you want to modify the existing lines in the buffer instead:

:for i in range(1, line('$')) | call setline(i, printf("this is line %2d: %s", i, getline(i))) | endfor

Of course, if you don't want to change the buffer, but just print to the screen, use "echo" instead of "call" and remove the append() / setline() chunks from around the printf().


:help :for
:help :call
:help :echo
:help range()
:help line()
:help append()
:help setline()
:help getline()
:help printf()
share|improve this answer
Perfect; thank you. I apologize for not being concise, but your second code example did exactly what I wanted. Since I'm new I cannot upvote, but I will when I can. – doubleshot Feb 17 '12 at 22:49
Of course, there's another, arguably simpler way to do it: :%s/^/\=printf("This is line %d: ", line('.'))/ – Heptite Feb 18 '12 at 2:36

In Emacs try:

M: (dotimes (i 3) (insert (format "This is line %2d.\n" (1+ i))))

Here M: stands for eval-expression

share|improve this answer
For those who don't know Emacs: It's Alt + : – Tom Feb 17 '12 at 17:13

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.