For-loop snippet

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:

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

Shell script: (expand-for.sh)

#!/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"
    }
}
'