How do I generate multiple lines of text using a Vimscript for loop from the command line?
Answer
:for i in range(1,5) | put ='item '.i | endfor
Explanation
Vimscript's for loop is available directly from Vim's command line and can be used to generate repetitive or parameterized text without a macro or external script. Combined with :put =expression, this technique inserts dynamically computed lines into the buffer instantly.
How it works
:for i in range(start, end)— iterates over a sequence of integers| put ='expression'— inserts the evaluated expression as a new line below the cursor| endfor— closes the loop; all three statements are joined with|for single-line execution
The range(start, end) function produces [start, start+1, ..., end]. An optional third argument sets the step: range(0, 10, 2).
Example
Generate a numbered list:
:for i in range(1,5) | put =' '.i.'. Item '.i | endfor
Produces (inserted below the current line):
1. Item 1
2. Item 2
3. Item 3
4. Item 4
5. Item 5
Generate HTML <li> elements:
:for i in range(1,4) | put ='<li>Entry '.i.'</li>' | endfor
Tips
- Use
put!instead ofputto insert lines above the current line - Generate a sequence of letters:
nr2char(64 + i)converts integers to uppercase letters (A=65) - Compute values inline:
:for i in range(1,5) | put =(i * i) | endforinserts squares 1, 4, 9, 16, 25 - Use
map()for transformations over a list::put =map(range(1,5), '"item_".v:val') - Chain with
executeto run arbitrary commands per iteration