# For-loop snippet

**URL:** <https://discuss.kakoune.com/t/for-loop-snippet/1915>\
**Category:** Recipes & Guides\
**Created:** [November 2, 2021, 2:41pm UTC](https://discuss.kakoune.com/t/for-loop-snippet/1915 "2021-11-02T14:41:44Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![xfoo](https://discuss.kakoune.com/letter_avatar_proxy/v4/letter/x/cdc98d/32.png) [@xfoo](https://discuss.kakoune.com/u/xfoo)\
**Post date:** [November 2, 2021, 2:41pm UTC](https://discuss.kakoune.com/t/for-loop-snippet/1915/1 "2021-11-02T14:41:44Z")

</div>

A post-fix snippet for writing for-loops in insert mode.  
Write the snippet and then press `<c-f>` to expand it. (Or optionally press `<c-f>` before writing the snippet, and `<c-f>` again after writing it).

Examples:

Type `int i<size` and press `<c-f>`:  
Output: `for (int i = 0; i < size; i++) {`  
(the variable is initialized to 0 by default)

`int i=1<argc` turns into:  
`for (int i = 1; i < argc; i++) {`

`int value=min<=max` turns into:  
`for (int value = min; value <= max; value++) {`

`auto &x:collection` turns into:  
`for (auto &x : collection) {`

`auto it=a.begin()!=a.end()` turns into:  
`for (auto it = a.begin(); it != a.end(); it++) {`

Press `<c-f><c-f>` to get:  
`for (;;) {`

* * *

kakrc:

```auto
map global insert <c-f> '<a-;>Gi<a-;>| expand-for.sh<ret><end>'

```

Shell script: (`expand-for.sh`)

```bash
#!/bin/sh

sed 's/^for \?(\(.\)/\1/' |
sed 's/ \?\([!<>]\?=\|[<>]\|:\) \?/\n\1 /g' | awk '
BEGIN {
    init = 0
}

$0 == "for (" {
    empty = 1
    exit
}

NR == 1 {
    decl = $0
    var = $NF
    step = var "++"
    next
}

$1 == "=" {
    init = $2
    for (i = 3; i <= NF; i++) init = init " " $i
    next
}

$1 ~ /^(!=|[<>]=?)$/ {
    cond = var " " $0
    if ($1 ~ /^>/) step = var "--"
    next
}

$1 == ":" {
    collection = $2
    for (i = 3; i <= NF; i++) collection = collection " " $i
    next
}

END {
    if (empty) {
        printf "for (;;) {\n"
    } else if (!decl) {
        printf "for (\n"
    } else if (collection) {
        printf "for (%s : %s) {\n", decl, collection
    } else {
        printf "for ("
        if (decl) printf "%s = %s", decl, init
        printf ";"
        if (cond) printf " %s", cond
        printf ";"
        if (step) printf " %s", step
        printf ") {\n"
    }
}
'

```
