Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Vimscript loop


May 24, 2021 Vim


Table of contents


You may be surprised to find that, as a book on programming languages, we didn't mention looping at all in the first 35 chapters! Vimscript provides a lot of ways to manipulate text (for example, normal! so looping is not as necessary as in most other languages.

Even so, one day you'll need it, so let's explore the two main loops that Vim supports.

For loop

The first loop is the for loop. I f you're used to the for loop in Java, C, for it looks a bit odd. B ut you'll find this writing very elegant. Execute the following command:

:let c = 0

:for i in [1, 2, 3, 4]
:  let c += i
:endfor

:echom c

Vim 10 which is the result of the addition of each element in the list. Vimscript's for traverses the entire list (or the dictionary we'll mention a few years from now).

There is no C-style for in for (int i = 0; i < foo; i++) It may be hard to adapt at first, but once you get used to it you won't miss the C-style for loop.

While loop

Vim also supports classic while Follow these commands:

:let c = 1
:let total = 0

:while c <= 4
:  let total += c
:  let c += 1
:endwhile

:echom total

Vim shows 10 A lmost every program ape is familiar with this loop, so we don't waste time explaining it. Y ou will rarely use it. Keep it in mind in case of need.

Practice

Read :help for .

Read :help while .