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. C++ port (canonical TS:
// src/lib/css-minify.ts; Go twin: cli/css-minify). One scanner masks string
// literals as "\x00n\x00" sentinels and drops /* */ comments; every textual
// rule then runs on the masked text — <regex>'s ECMAScript grammar carries
// the TS backreferences natively, and every replacement goes through a
// regex_iterator + callback so no format-string group ambiguity ($10) can
// drift from the TS. 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 own semicolon. Errors travel in FormatResult::error (nullptr
// mirrors TS null); empty input is a successful empty output, never an
// error.
#include <regex>
#include <string>
#include <vector>

namespace cssminify {

struct FormatResult {
    std::string output;
    const char* error = nullptr; // nullptr mirrors TS `error: null`
};

// JS-style trim: ASCII whitespace only, never the \x00 sentinel bytes.
inline std::string jsTrim(const std::string& s) {
    const std::string ws = " \t\n\v\f\r";
    size_t b = s.find_first_not_of(ws);
    if (b == std::string::npos) return "";
    size_t e = s.find_last_not_of(ws);
    return s.substr(b, e - b + 1);
}

// Scan CSS into masked text where every string literal is replaced by a
// \x00n\x00 sentinel (n = index into strings) and every /* ... */ comment
// is dropped. A backslash escapes the next character. Returns false with
// err set on an unterminated string or comment.
inline bool mask(const std::string& raw, std::string& out,
                 std::vector<std::string>& strings, const char*& err) {
    out.clear();
    strings.clear();
    size_t i = 0;
    while (i < raw.size()) {
        char ch = raw[i];
        if (ch == '"' || ch == '\'') {
            size_t start = i++;
            while (i < raw.size() && raw[i] != ch) {
                if (raw[i] == '\\' && i + 1 < raw.size()) i++; // escaped char
                i++;
            }
            if (i >= raw.size()) { err = "Unterminated string"; return false; }
            i++;
            strings.push_back(raw.substr(start, i - start));
            out += '\0';
            out += std::to_string(strings.size() - 1);
            out += '\0';
        } else if (ch == '/' && i + 1 < raw.size() && raw[i + 1] == '*') {
            size_t end = raw.find("*/", i + 2);
            if (end == std::string::npos) { err = "Unterminated comment"; return false; }
            i = end + 2;
        } else {
            out += ch;
            i++;
        }
    }
    err = nullptr;
    return true;
}

// Substitute the sentinels back with the original string literals.
inline std::string unmask(const std::string& text, const std::vector<std::string>& strings) {
    std::string out;
    size_t i = 0;
    while (i < text.size()) {
        if (text[i] == '\0') {
            size_t j = i + 1;
            while (j < text.size() && text[j] >= '0' && text[j] <= '9') j++;
            if (j < text.size() && text[j] == '\0' && j > i + 1) {
                int idx = std::stoi(text.substr(i + 1, j - i - 1));
                if (idx >= 0 && static_cast<size_t>(idx) < strings.size()) {
                    out += strings[static_cast<size_t>(idx)];
                    i = j + 1;
                    continue;
                }
            }
        }
        out += text[i];
        i++;
    }
    return out;
}

// JS-semantics replace-all: leftmost, non-overlapping matches through a
// regex_iterator, replacement built by callback (no $10-format ambiguity).
inline std::string replaceAll(
    const std::string& s, const std::regex& re,
    const std::function<std::string(const std::smatch&)>& fn) {
    std::string out;
    std::ptrdiff_t last = 0;
    for (auto it = std::sregex_iterator(s.begin(), s.end(), re);
         it != std::sregex_iterator(); ++it) {
        const std::smatch& m = *it;
        out.append(s, static_cast<size_t>(m.position()),
                   static_cast<size_t>(m.position() - last));
        out += fn(m);
        last = m.position() + m.length();
    }
    out.append(s, static_cast<size_t>(last), std::string::npos);
    return out;
}

inline std::string lowerCopy(const std::string& s) {
    std::string out = s;
    for (char& c : out)
        if (c >= 'A' && c <= 'Z') c = static_cast<char>(c - 'A' + 'a');
    return out;
}

// Conservative minification — see the header for the exact rule list.
inline FormatResult minifyCss(const std::string& raw) {
    static const std::regex ws(R"(\s+)");
    static const std::regex structStrip(R"(\s*([{};:,>])\s*)");
    static const std::regex trailingSemis(R"(;+})");
    static const std::regex hexLower(R"(#[0-9a-fA-F]{3,8})");
    static const std::regex hexPair(R"(#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3([^0-9a-f]|$))");
    static const std::regex leadingZero(R"((^|[^A-Za-z0-9_.#$%-])0+(\.[0-9]+))");
    static const std::regex fractionZeros(R"((\.[0-9]*[1-9])0+([^0-9]|$))");
    static const std::regex integralZeros(R"((^|[^A-Za-z0-9_.#$%-])([0-9]+)\.0+([^0-9]|$))");
    static const std::regex dotZeros(R"((^|[^A-Za-z0-9_.#$%-])\.0+([^0-9]|$))");

    FormatResult res;
    std::string text = jsTrim(raw);
    if (text.empty()) return res; // empty/whitespace-only input is NOT an error
    std::string masked;
    std::vector<std::string> strings;
    if (!mask(text, masked, strings, res.error)) {
        res.output.clear();
        return res;
    }
    std::string css = replaceAll(masked, ws, [](const std::smatch&) { return " "; });
    css = replaceAll(css, structStrip, [](const std::smatch& m) { return m[1].str(); });
    css = replaceAll(css, trailingSemis, [](const std::smatch&) { return "}"; });
    css = jsTrim(css);
    css = replaceAll(css, hexLower, [](const std::smatch& m) { return lowerCopy(m[0].str()); });
    css = replaceAll(css, hexPair, [](const std::smatch& m) {
        return "#" + m[1].str() + m[2].str() + m[3].str() + m[4].str();
    });
    css = replaceAll(css, leadingZero, [](const std::smatch& m) { return m[1].str() + m[2].str(); });
    css = replaceAll(css, fractionZeros, [](const std::smatch& m) { return m[1].str() + m[2].str(); });
    css = replaceAll(css, integralZeros, [](const std::smatch& m) {
        return m[1].str() + m[2].str() + m[3].str();
    });
    css = replaceAll(css, dotZeros, [](const std::smatch& m) {
        return m[1].str() + "0" + m[2].str(); // TS '$10$2' = group 1 + '0' + group 2
    });
    res.output = unmask(css, strings);
    return res;
}

// Structural beautifier — 2-space indentation, declarations one per line;
// empty declarations (;;, dangling ;) are skipped.
inline FormatResult beautifyCss(const std::string& raw) {
    FormatResult res;
    std::string text = jsTrim(raw);
    if (text.empty()) return res;
    std::string masked;
    std::vector<std::string> strings;
    if (!mask(text, masked, strings, res.error)) {
        res.output.clear();
        return res;
    }
    static const std::regex ws(R"(\s+)");
    std::string css = replaceAll(masked, ws, [](const std::smatch&) { return " "; });
    std::string out;
    std::string buf;
    int depth = 0;
    auto pad = [&out, depth]() { out.append(static_cast<size_t>(2 * depth), ' '); };
    auto flushDecl = [&out, &buf, &depth, &pad](bool semi) {
        // Whitespace was already collapsed to single spaces, so only
        // trimming remains; empty declarations are skipped.
        std::string decl = jsTrim(buf);
        if (!decl.empty()) {
            pad();
            out += decl;
            if (semi) out += ';';
            out += '\n';
        }
        buf.clear();
    };
    for (char ch : css) {
        if (ch == '{') {
            std::string sel = jsTrim(buf);
            buf.clear();
            if (sel.empty()) { res.error = "Block without a selector"; return res; }
            pad();
            out += sel + " {\n";
            depth++;
        } else if (ch == '}') {
            flushDecl(false);
            depth--;
            if (depth < 0) { res.error = "Unbalanced }"; return res; }
            pad();
            out += "}\n";
        } else if (ch == ';') {
            flushDecl(true);
        } else {
            buf += ch;
        }
    }
    if (depth != 0) { res.error = "Unclosed block"; return res; }
    flushDecl(false);
    res.output = unmask(out, strings);
    return res;
}

} // namespace cssminify

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 →