Skip to content

CSS Minify & Beautify — C source

Minify CSS (strip comments and whitespace, shorten hexes and decimals) or beautify it back to readable one-declaration-per-line form. Strings stay intact. Runs locally with a shareable link.

This is the C implementation — the same logic the interactive tool runs, in a shareable, citable form.

/* css-minify — CSS minifier & beautifier. C11 port (canonical TS:
 * src/lib/css-minify.ts; Go twin: cli/css-minify). No stdlib regex: every
 * textual rule is re-implemented as an explicit scan with the TS match
 * semantics (leftmost match, greedy runs, one-char advance on failure) so
 * the Go twin reproduces byte-identical output. One scanner masks string
 * literals as \x01n\x01 sentinels (C strings cannot hold NUL) and drops
 * comments; then: minify — collapse whitespace, strip spaces around
 * {} ; : , > (sibling + and ~ combinators keep theirs), drop the last
 * semicolon before }, lowercase hexes, shorten #aabbcc → #abc (never
 * 8-digit alpha), strip leading zeros (0.5 → .5) and trailing fraction
 * zeros (1.50 → 1.5, 1.00 → 1, .00 → 0). beautify — one selector per
 * block, one declaration per line at 2-space depth, each declaration
 * keeping its semicolon. Errors are the pinned TS strings; empty input is
 * a successful empty output. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct { char *s; size_t n, cap; } Str;
typedef struct { char **v; size_t n; } StrList;
typedef struct { char *output; const char *error; } CssResult;

static void str_init(Str *b) { b->s = malloc(1); b->s[0] = '\0'; b->n = 0; b->cap = 1; }
static void str_ch(Str *b, char c)
{
    if (b->n + 2 > b->cap) { b->cap *= 2; b->s = realloc(b->s, b->cap); }
    b->s[b->n++] = c;
    b->s[b->n] = '\0';
}
static void str_putn(Str *b, const char *s, size_t n) { for (size_t i = 0; i < n; i++) str_ch(b, s[i]); }
static void str_puts(Str *b, const char *s) { str_putn(b, s, strlen(s)); }
static void str_free(Str *b) { free(b->s); b->s = NULL; b->n = b->cap = 0; }

static int is_ws(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'; }
static int is_digit(char c) { return c >= '0' && c <= '9'; }
static int is_lower_hex(char c) { return is_digit(c) || (c >= 'a' && c <= 'f'); }
static int is_upper_hex(char c) { return c >= 'A' && c <= 'F'; }
static int is_hex_any(char c) { return is_lower_hex(c) || is_upper_hex(c); }
/* TS numeric-context exclusion class [A-Za-z0-9_.#$%-]: a leading zero may
 * only be stripped when the preceding char is NOT one of these. */
static int is_wordish(char c)
{
    return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || is_digit(c) ||
           c == '_' || c == '.' || c == '#' || c == '$' || c == '%' || c == '-';
}
static int is_struct(char c) { return c == '{' || c == '}' || c == ';' || c == ':' || c == ',' || c == '>'; }

/* JS-style trim (ASCII whitespace; never strips the \x01 sentinel). */
static char *js_trim(const char *s)
{
    size_t a = 0, e = strlen(s);
    while (a < e && is_ws(s[a])) a++;
    while (e > a && is_ws(s[e - 1])) e--;
    char *p = malloc(e - a + 1);
    memcpy(p, s + a, e - a);
    p[e - a] = '\0';
    return p;
}

/* Scan CSS into a masked text where every string literal is replaced by a
 * \x01n\x01 sentinel (n = index into strs). Comments are dropped; a
 * backslash escapes the next character inside a literal. Returns NULL on
 * success, else the pinned error string. */
static const char *mask(const char *raw, Str *out, StrList *strs)
{
    size_t i = 0;
    while (raw[i]) {
        char ch = raw[i];
        if (ch == '"' || ch == '\'') {
            size_t start = i;
            i++;
            while (raw[i] && raw[i] != ch) {
                if (raw[i] == '\\' && raw[i + 1]) i++; /* escaped char */
                i++;
            }
            if (!raw[i]) return "Unterminated string";
            i++;
            strs->v = realloc(strs->v, (strs->n + 1) * sizeof *strs->v);
            char *lit = malloc(i - start + 1);
            memcpy(lit, raw + start, i - start);
            lit[i - start] = '\0';
            strs->v[strs->n++] = lit;
            char idx[32];
            snprintf(idx, sizeof idx, "\x01%zu\x01", strs->n - 1);
            str_puts(out, idx);
        } else if (ch == '/' && raw[i + 1] == '*') {
            const char *end = strstr(raw + i + 2, "*/");
            if (!end) return "Unterminated comment";
            i = (size_t)(end - raw) + 2;
        } else {
            str_ch(out, ch);
            i++;
        }
    }
    return NULL;
}

/* Substitute the sentinels back with the original string literals. */
static void unmask(const char *text, StrList *strs, Str *out)
{
    for (size_t i = 0; text[i];) {
        if (text[i] == '\x01') {
            size_t j = i + 1, n = 0;
            while (is_digit(text[j])) n = n * 10 + (size_t)(text[j++] - '0');
            if (text[j] == '\x01' && n < strs->n) { str_puts(out, strs->v[n]); i = j + 1; continue; }
        }
        str_ch(out, text[i++]);
    }
}

/* /\s+/ → " " */
static void collapse_ws(const char *s, Str *out)
{
    for (size_t i = 0; s[i];) {
        if (is_ws(s[i])) { str_ch(out, ' '); while (is_ws(s[i])) i++; }
        else str_ch(out, s[i++]);
    }
}

/* /\s*([{};:,>])\s*/ → "$1" — ws before a structural char is trimmed from
 * the builder, ws after it is skipped. */
static void strip_struct(const char *s, Str *out)
{
    for (size_t i = 0; s[i];) {
        if (is_struct(s[i])) {
            while (out->n && is_ws(out->s[out->n - 1])) { out->n--; out->s[out->n] = '\0'; }
            str_ch(out, s[i++]);
            while (is_ws(s[i])) i++;
        } else str_ch(out, s[i++]);
    }
}

/* /;+}/ → "}" */
static void drop_trailing_semis(const char *s, Str *out)
{
    for (size_t i = 0; s[i];) {
        if (s[i] == '}') {
            while (out->n && out->s[out->n - 1] == ';') { out->n--; out->s[out->n] = '\0'; }
            str_ch(out, s[i++]);
        } else str_ch(out, s[i++]);
    }
}

/* /#[0-9a-fA-F]{3,8}/ → lowercase (greedy: at most 8 hex digits, ≥ 3). */
static void lower_hex(const char *s, Str *out)
{
    for (size_t i = 0; s[i];) {
        if (s[i] == '#') {
            size_t j = i + 1, k = 0;
            while (k < 8 && is_hex_any(s[j])) { j++; k++; }
            if (k >= 3) {
                for (size_t t = i + 1; t < j; t++)
                    str_ch(out, is_upper_hex(s[t]) ? (char)(s[t] - 'A' + 'a') : s[t]);
                i = j;
                continue;
            }
        }
        str_ch(out, s[i++]);
    }
}

/* TS backref pattern '#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3([^0-9a-f]|$)'
 * as a manual pair test: #xyabzc with x==y, a==b, z==c and a non-lower-hex
 * (or end) after the run shrinks to #xyz. */
static void shorten_hex_pair(const char *s, Str *out)
{
    for (size_t i = 0; s[i];) {
        if (s[i] == '#') {
            int pairs = 1;
            for (int p = 0; p < 3; p++) {
                char a = s[i + 1 + 2 * p], b = s[i + 2 + 2 * p];
                if (!a || !b || !is_lower_hex(a) || a != b) { pairs = 0; break; }
            }
            if (pairs) {
                char ctx = s[i + 7];
                if (!ctx || !is_lower_hex(ctx)) {
                    str_ch(out, '#');
                    str_ch(out, s[i + 1]); str_ch(out, s[i + 3]); str_ch(out, s[i + 5]);
                    if (ctx) { str_ch(out, ctx); i = i + 8; } else i = i + 7;
                    continue;
                }
            }
        }
        str_ch(out, s[i++]);
    }
}

/* /(^|[^A-Za-z0-9_.#$%-])0+(\.[0-9]+)/ → "$1$2" (0.5 → .5, 00.5 → .5) */
static void strip_leading_zero(const char *s, Str *out)
{
    size_t i = 0;
    while (s[i]) {
        size_t zpos;
        int fail = 0;
        if (i == 0) zpos = 0;
        else if (!is_wordish(s[i])) zpos = i + 1;
        else fail = 1;
        if (!fail) {
            size_t z = zpos;
            while (s[z] == '0') z++;
            if (z > zpos && s[z] == '.') {
                size_t f = z + 1;
                while (is_digit(s[f])) f++;
                if (f > z + 1) {
                    if (i > 0) str_ch(out, s[i]); /* the prefix char */
                    str_putn(out, s + z, f - z);  /* .digits */
                    i = f;
                    continue;
                }
            }
        }
        str_ch(out, s[i++]);
    }
}

/* /(\.[0-9]*[1-9])0+([^0-9]|$)/ → "$1$2" (1.50 → 1.5): the digit run after
 * '.' is maximal, so the stripped zeros must sit INSIDE it — backtrack the
 * group end k from runlen down to a [1-9] digit followed by only zeros. */
static void strip_fraction_zeros(const char *s, Str *out)
{
    size_t i = 0;
    while (s[i]) {
        if (s[i] == '.') {
            size_t e = i + 1;
            while (is_digit(s[e])) e++;
            size_t runlen = e - (i + 1);
            for (size_t k = runlen - (runlen > 1); k >= 1; k--) {
                char c = s[i + k]; /* run[k-1] */
                if (c >= '1' && c <= '9') {
                    int allz = 1;
                    for (size_t t = k; t < runlen; t++)
                        if (s[i + 1 + t] != '0') { allz = 0; break; }
                    if (allz) { /* group = '.' + run[0..k), zeros inside, ctx = s[e] */
                        str_putn(out, s + i, 1 + k);
                        if (s[e]) { str_ch(out, s[e]); i = e + 1; } else i = e;
                        break;
                    }
                }
                if (k == 1) break;
            }
            continue;
        }
        str_ch(out, s[i++]);
    }
}

/* /(^|[^A-Za-z0-9_.#$%-])([0-9]+)\.0+([^0-9]|$)/ → "$1$2$3" (1.00 → 1) */
static void strip_integral_zeros(const char *s, Str *out)
{
    size_t i = 0;
    while (s[i]) {
        size_t dpos;
        int fail = 0;
        if (i == 0) dpos = 0;
        else if (!is_wordish(s[i])) dpos = i + 1;
        else fail = 1;
        if (!fail) {
            size_t d = dpos;
            while (is_digit(s[d])) d++;
            if (d > dpos && s[d] == '.') {
                size_t z = d + 1;
                while (s[z] == '0') z++;
                if (z > d + 1 && (!s[z] || !is_digit(s[z]))) {
                    if (i > 0) str_ch(out, s[i]);
                    str_putn(out, s + dpos, d - dpos);
                    if (s[z]) { str_ch(out, s[z]); i = z + 1; } else i = z;
                    continue;
                }
            }
        }
        str_ch(out, s[i++]);
    }
}

/* /(^|[^A-Za-z0-9_.#$%-])\.0+([^0-9]|$)/ → "$1" "0" "$2" (.00 → 0) */
static void dot_zeros(const char *s, Str *out)
{
    size_t i = 0;
    while (s[i]) {
        size_t dot;
        int fail = 0;
        if (i == 0) dot = 0;
        else if (!is_wordish(s[i])) dot = i + 1;
        else fail = 1;
        if (!fail && s[dot] == '.') {
            size_t z = dot + 1;
            while (s[z] == '0') z++;
            if (z > dot + 1 && (!s[z] || !is_digit(s[z]))) {
                if (i > 0) str_ch(out, s[i]);
                str_ch(out, '0');
                if (s[z]) { str_ch(out, s[z]); i = z + 1; } else i = z;
                continue;
            }
        }
        str_ch(out, s[i++]);
    }
}

/* Conservative minification — see header for the exact rule list. */
static CssResult minify_css(const char *raw)
{
    char *text = js_trim(raw);
    CssResult res = {NULL, NULL};
    if (!text[0]) { free(text); return res; } /* empty input is NOT an error */
    Str masked; str_init(&masked);
    StrList strs = {NULL, 0};
    const char *err = mask(text, &masked, &strs);
    free(text);
    if (err) { res.error = err; return res; }
    Str b; str_init(&b);
    collapse_ws(masked.s, &b);
    char *t1 = strdup(b.s); str_free(&b); str_init(&b);
    strip_struct(t1, &b); free(t1);
    t1 = strdup(b.s); str_free(&b); str_init(&b);
    drop_trailing_semis(t1, &b); free(t1);
    t1 = js_trim(b.s); str_free(&b); str_init(&b);
    lower_hex(t1, &b); free(t1);
    t1 = strdup(b.s); str_free(&b); str_init(&b);
    shorten_hex_pair(t1, &b); free(t1);
    t1 = strdup(b.s); str_free(&b); str_init(&b);
    strip_leading_zero(t1, &b); free(t1);
    t1 = strdup(b.s); str_free(&b); str_init(&b);
    strip_fraction_zeros(t1, &b); free(t1);
    t1 = strdup(b.s); str_free(&b); str_init(&b);
    strip_integral_zeros(t1, &b); free(t1);
    t1 = strdup(b.s); str_free(&b); str_init(&b);
    dot_zeros(t1, &b); free(t1);
    unmask(b.s, &strs, &b); /* append the unmasked text */
    res.output = b.s;       /* ownership moves to the result */
    return res;
}

/* Structural beautifier — 2-space indentation, declarations one per line. */
static CssResult beautify_css(const char *raw)
{
    char *text = js_trim(raw);
    CssResult res = {NULL, NULL};
    if (!text[0]) { free(text); return res; }
    Str masked; str_init(&masked);
    StrList strs = {NULL, 0};
    const char *err = mask(text, &masked, &strs);
    free(text);
    if (err) { res.error = err; return res; }
    Str css; str_init(&css);
    collapse_ws(masked.s, &css);
    Str out, buf;
    str_init(&out); str_init(&buf);
    int depth = 0;
    for (size_t i = 0; css.s[i]; i++) {
        char ch = css.s[i];
        if (ch == '{') {
            size_t a = 0, e = buf.n;
            while (a < e && is_ws(buf.s[a])) a++;
            while (e > a && is_ws(buf.s[e - 1])) e--;
            if (e == a) return (CssResult){NULL, "Block without a selector"};
            for (int t = 0; t < depth * 2; t++) str_ch(&out, ' ');
            str_putn(&out, buf.s + a, e - a);
            str_puts(&out, " {\n");
            buf.n = 0; buf.s[0] = '\0';
            depth++;
        } else if (ch == '}') {
            if (buf.n) {
                size_t a = 0, e = buf.n;
                while (a < e && is_ws(buf.s[a])) a++;
                while (e > a && is_ws(buf.s[e - 1])) e--;
                if (e > a) {
                    for (int t = 0; t < depth * 2; t++) str_ch(&out, ' ');
                    str_putn(&out, buf.s + a, e - a);
                    str_ch(&out, '\n');
                }
            }
            buf.n = 0; buf.s[0] = '\0';
            depth--;
            if (depth < 0) return (CssResult){NULL, "Unbalanced }"};
            for (int t = 0; t < depth * 2; t++) str_ch(&out, ' ');
            str_puts(&out, "}\n");
        } else if (ch == ';') {
            size_t a = 0, e = buf.n;
            while (a < e && is_ws(buf.s[a])) a++;
            while (e > a && is_ws(buf.s[e - 1])) e--;
            if (e > a) {
                for (int t = 0; t < depth * 2; t++) str_ch(&out, ' ');
                str_putn(&out, buf.s + a, e - a);
                str_puts(&out, ";\n");
            }
            buf.n = 0; buf.s[0] = '\0';
        } else str_ch(&buf, ch);
    }
    if (depth != 0) return (CssResult){NULL, "Unclosed block"};
    if (buf.n) { /* dangling declaration without ';' — TS flushDecl(false) */
        size_t a = 0, e = buf.n;
        while (a < e && is_ws(buf.s[a])) a++;
        while (e > a && is_ws(buf.s[e - 1])) e--;
        if (e > a) {
            for (int t = 0; t < depth * 2; t++) str_ch(&out, ' ');
            str_putn(&out, buf.s + a, e - a);
            str_ch(&out, '\n');
        }
    }
    Str un; str_init(&un);
    unmask(out.s, &strs, &un);
    res.output = un.s;
    return res;
}

int main(void)
{
    CssResult m = minify_css("@media (max-width: 600px) { /* comment */ body { color : #AABBCC; margin : 0.50px; content : \"a, b\" ; }}");
    printf("min: %s\n", m.output ? m.output : m.error);
    CssResult b = beautify_css("a{b:c;d}p{q:r}");
    printf("bea:\n%s", b.output ? b.output : b.error);
    return 0;
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →