Vim is a powerful feature-rich text editor that can make your work with code faster and more efficient. It comes with a variety of built-in functions that simplify everyday actions (: help builtin).
We'll look into one of them: the built-in function repeat (: help repeat) that repeats an expression a specified number of times and returns a concatenated result.
It has the following syntax:
repeat({expr}, {count})
We will look into 2 important cases where the function may come in handy:
Let's see how to use the repeat() function in the context of variables in the command line.
:let separator = repeat('-', 100) # set the variable
:echo separator # echoes separator
When an expression is a List, it's concatenated a specified number of times:
:let names = repeat(['michael', 'joseph'], 3) # expr is a list
:echo names # echoes names
The function can also be used as a method:
:echo [1, 2, 3]->repeat(2) # use repeat as a method
If you have some data you need to insert that is stored in variables, you may use :put to insert them after the cursor (:help :put)
:let names = repeat(['michael', 'joseph'], 3)
:put =names->string()
I’d like to point out that we’ve transformed the result into string names ->string() to insert it as a list in one line.
If you remove ->string(), each item of the list will be on a separate line.
While working with code, we often need to repeat some expressions or fill in structures with some data.
Let's see how we can use repeat() in Insert Mode. When you are in Insert Mode:
<C-r>=repeat('[]', 10)<CR>
It means: Press Ctrl-r, type =repeat('[]', 10), Pres Enter
We’ve added '[][][][][][][][][][]'
and stayed in Insert Mode.
repeat(range(5), 3)->string() # repeats [0, 1, 2, 3, 4] three times
string(repeat(range(5), 3)) # use built-in string()
repeat(tempname() . ': ', 3)->string()
tempname() # generates a temporary file name that doesn't exist
. # concatenate two strings
The built-in repeat() makes working with the code quick and convenient, especially in Insert Mode. It saves us from switching between different modes, which increases the overall flow's speed. Thanks to a variety of built-in functions in Vim, you can generate data of various types for {expr} in a wide range. Put the function into action, and make your life easier.