CSS Minify & Beautify — Zig 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 Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! css-minify — CSS minifier & beautifier. Zig port (canonical TS:
//! src/lib/css-minify.ts; Go twin: cli/css-minify). Mirrors the sibling
//! ports: one scanner masks string literals as "\x00n\x00" sentinels and
//! drops /* */ comments; every textual rule then runs on the masked text as
//! a single-pass byte scanner with the same leftmost, non-overlapping
//! replace-all semantics as the TS regexes. 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_msg
//! (null = success); empty input is a successful empty output, never an
//! error.
const std = @import("std");
pub const FormatResult = struct {
output: []u8,
error_msg: ?[]const u8,
};
const WS = " \t\n\x0b\x0c\r";
fn isWs(c: u8) bool {
return std.mem.indexOfScalar(u8, WS, c) != null;
}
fn isPunct(c: u8) bool {
return switch (c) {
'{', '}', ';', ':', ',', '>' => true,
else => false,
};
}
fn isDigit(c: u8) bool {
return c >= '0' and c <= '9';
}
fn isLowerHex(c: u8) bool {
return isDigit(c) or (c >= 'a' and c <= 'f');
}
fn isHexAny(c: u8) bool {
return isLowerHex(c) or (c >= 'A' and c <= 'F');
}
/// The TS numeric-context class [^A-Za-z0-9_.#$%-]: true when `c` may
/// directly precede a number being rewritten.
fn ctxOk(c: u8) bool {
return !(std.ascii.isAlphanumeric(c) or c == '_' or c == '.' or c == '#' or c == '$' or c == '%' or c == '-');
}
const Masked = struct {
text: []u8,
strings: [][]u8,
};
const MaskResult = union(enum) { ok: Masked, err: []const u8 };
fn writePad(out: *std.ArrayList(u8), depth: usize) !void {
var p: usize = 0;
while (p < depth) : (p += 1) try out.appendSlice(" ");
}
fn isLowerHexRun(s: []const u8) bool {
for (s) |c| if (!isLowerHex(c)) return false;
return true;
}
/// 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. err_msg is null on
/// success.
fn mask(alloc: std.mem.Allocator, raw: []const u8) !MaskResult {
var out = std.ArrayList(u8).init(alloc);
var strings = std.ArrayList([]u8).init(alloc);
var i: usize = 0;
while (i < raw.len) {
const c = raw[i];
if (c == '"' or c == '\'') {
const start = i;
i += 1;
while (i < raw.len and raw[i] != c) {
if (raw[i] == '\\' and i + 1 < raw.len) i += 1; // escaped char
i += 1;
}
if (i >= raw.len) return .{ .err = "Unterminated string" };
i += 1;
try strings.append(try alloc.dupe(u8, raw[start..i]));
try out.writer().print("\x00{d}\x00", .{strings.items.len - 1});
} else if (c == '/' and i + 1 < raw.len and raw[i + 1] == '*') {
const rest = raw[i + 2 ..];
const end = std.mem.indexOf(u8, rest, "*/") orelse
return .{ .err = "Unterminated comment" };
i += 2 + end + 2;
} else {
try out.append(c);
i += 1;
}
}
return .{ .ok = .{ .text = try out.toOwnedSlice(), .strings = try strings.toOwnedSlice() } };
}
/// Substitute the sentinels back with the original string literals.
fn unmask(alloc: std.mem.Allocator, text: []const u8, strings: [][]u8) ![]u8 {
var out = std.ArrayList(u8).init(alloc);
var i: usize = 0;
while (i < text.len) {
if (text[i] == 0) {
var j = i + 1;
while (j < text.len and isDigit(text[j])) j += 1;
if (j < text.len and text[j] == 0 and j > i + 1) {
const idx = std.fmt.parseInt(usize, text[i + 1 .. j], 10) catch std.math.maxInt(usize);
if (idx < strings.len) {
try out.appendSlice(strings[idx]);
i = j + 1;
continue;
}
}
}
try out.append(text[i]);
i += 1;
}
return out.toOwnedSlice();
}
/// /\s+/g → " "
fn collapseWs(alloc: std.mem.Allocator, s: []const u8) ![]u8 {
var out = std.ArrayList(u8).init(alloc);
var i: usize = 0;
while (i < s.len) {
if (isWs(s[i])) {
while (i < s.len and isWs(s[i])) i += 1;
try out.append(' ');
} else {
try out.append(s[i]);
i += 1;
}
}
return out.toOwnedSlice();
}
/// /\s*([{};:,>])\s*/g → "$1"
fn stripStruct(alloc: std.mem.Allocator, s: []const u8) ![]u8 {
var out = std.ArrayList(u8).init(alloc);
var i: usize = 0;
while (i < s.len) {
var j = i;
while (j < s.len and isWs(s[j])) j += 1;
if (j < s.len and isPunct(s[j])) {
try out.append(s[j]);
var k = j + 1;
while (k < s.len and isWs(s[k])) k += 1;
i = k;
} else {
try out.append(s[i]);
i += 1;
}
}
return out.toOwnedSlice();
}
/// /;+}/g → "}"
fn dropTrailingSemis(alloc: std.mem.Allocator, s: []const u8) ![]u8 {
var out = std.ArrayList(u8).init(alloc);
var i: usize = 0;
while (i < s.len) {
if (s[i] == ';') {
var j = i;
while (j < s.len and s[j] == ';') j += 1;
if (j < s.len and s[j] == '}') {
try out.append('}');
i = j + 1;
continue;
}
}
try out.append(s[i]);
i += 1;
}
return out.toOwnedSlice();
}
/// /#[0-9a-fA-F]{3,8}/g → lowercase
fn lowerHex(alloc: std.mem.Allocator, s: []const u8) ![]u8 {
var out = std.ArrayList(u8).init(alloc);
var i: usize = 0;
while (i < s.len) {
if (s[i] == '#') {
var j = i + 1;
while (j < s.len and j - i - 1 < 8 and isHexAny(s[j])) j += 1;
if (j - i - 1 >= 3) {
for (s[i + 1 .. j]) |c| try out.append(std.ascii.toLower(c));
i = j;
continue;
}
}
try out.append(s[i]);
i += 1;
}
return out.toOwnedSlice();
}
/// The TS backreference rule #([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3([^0-9a-f]|$)
/// → "#$1$2$3$4": shorten #aabbcc to #abc only when both digits of each pair
/// match and no 7th hex digit follows (8-digit #rrggbbaa alpha is never touched).
fn shortenHexPair(alloc: std.mem.Allocator, s: []const u8) ![]u8 {
var out = std.ArrayList(u8).init(alloc);
var i: usize = 0;
while (i < s.len) {
if (s[i] == '#' and i + 6 < s.len and
isLowerHexRun(s[i + 1 .. i + 7]) and
(i + 7 >= s.len or !isLowerHex(s[i + 7])))
{
if (s[i + 1] == s[i + 2] and s[i + 3] == s[i + 4] and s[i + 5] == s[i + 6]) {
try out.append('#');
try out.append(s[i + 1]);
try out.append(s[i + 3]);
try out.append(s[i + 5]);
} else {
try out.appendSlice(s[i .. i + 7]);
}
if (i + 7 < s.len) {
try out.append(s[i + 7]); // the one non-hex context char, re-emitted
i += 8;
} else {
i += 7;
}
continue;
}
try out.append(s[i]);
i += 1;
}
return out.toOwnedSlice();
}
/// /(^|[^A-Za-z0-9_.#$%-])0+(\.[0-9]+)/g → "$1$2" (0.5 → .5)
fn stripLeadingZero(alloc: std.mem.Allocator, s: []const u8) ![]u8 {
var out = std.ArrayList(u8).init(alloc);
var i: usize = 0;
while (i < s.len) {
const z: ?usize = if (i == 0) 0 else if (ctxOk(s[i])) i + 1 else null;
if (z) |zv| {
var j = zv;
while (j < s.len and s[j] == '0') j += 1;
if (j > zv and j + 1 < s.len and s[j] == '.' and isDigit(s[j + 1])) {
if (i > 0) try out.append(s[i]);
var k = j + 2;
while (k < s.len and isDigit(s[k])) k += 1;
try out.appendSlice(s[j..k]);
i = k;
continue;
}
}
try out.append(s[i]);
i += 1;
}
return out.toOwnedSlice();
}
/// /(\.[0-9]*[1-9])0+([^0-9]|$)/g → "$1$2" (1.50 → 1.5)
fn stripFractionZeros(alloc: std.mem.Allocator, s: []const u8) ![]u8 {
var out = std.ArrayList(u8).init(alloc);
var i: usize = 0;
while (i < s.len) {
if (s[i] == '.') {
var d = i + 1;
while (d < s.len and isDigit(s[d])) d += 1;
// the group must end on a non-zero digit, with ≥ 1 zero after it
if (d > i + 1) {
var last_nz: ?usize = null;
var k = d;
while (k > i + 1) {
k -= 1;
if (s[k] != '0') {
last_nz = k;
break;
}
}
if (last_nz) |lnz| {
if (d - 1 > lnz) {
try out.appendSlice(s[i .. lnz + 1]);
if (d < s.len) {
try out.append(s[d]);
i = d + 1;
} else {
i = d;
}
continue;
}
}
}
}
try out.append(s[i]);
i += 1;
}
return out.toOwnedSlice();
}
/// Shared tail of the two all-zero-fraction rules: '.' (with its optional
/// digit run before it already validated) then zeros, ending at a non-digit
/// or end of input. Returns the index of the context char (or s.len) when
/// the rule matches, else null.
fn zeroFractionEnd(s: []const u8, dot: usize) ?usize {
var zz = dot + 1;
while (zz < s.len and s[zz] == '0') zz += 1;
if (zz == dot + 1) return null; // 0+ needs at least one zero
if (zz < s.len and isDigit(s[zz])) return null; // [^0-9]|$ fails
return zz;
}
/// /(^|[^A-Za-z0-9_.#$%-])([0-9]+)\.0+([^0-9]|$)/g → "$1$2$3" (1.00 → 1)
fn stripIntegralZeros(alloc: std.mem.Allocator, s: []const u8) ![]u8 {
var out = std.ArrayList(u8).init(alloc);
var i: usize = 0;
while (i < s.len) {
const z: ?usize = if (i == 0) 0 else if (ctxOk(s[i])) i + 1 else null;
if (z) |zv| {
var d = zv;
while (d < s.len and isDigit(s[d])) d += 1;
if (d > zv and d < s.len and s[d] == '.') {
if (zeroFractionEnd(s, d)) |zz| {
if (i > 0) try out.append(s[i]);
try out.appendSlice(s[zv..d]);
if (zz < s.len) {
try out.append(s[zz]);
i = zz + 1;
} else {
i = zz;
}
continue;
}
}
}
try out.append(s[i]);
i += 1;
}
return out.toOwnedSlice();
}
/// /(^|[^A-Za-z0-9_.#$%-])\.0+([^0-9]|$)/g → "${1}0$2" (.00 → 0)
fn dotZeros(alloc: std.mem.Allocator, s: []const u8) ![]u8 {
var out = std.ArrayList(u8).init(alloc);
var i: usize = 0;
while (i < s.len) {
const z: ?usize = if (i == 0) 0 else if (ctxOk(s[i])) i + 1 else null;
if (z) |zv| {
if (zv < s.len and s[zv] == '.') {
if (zeroFractionEnd(s, zv)) |zz| {
if (i > 0) try out.append(s[i]);
try out.append('0');
if (zz < s.len) {
try out.append(s[zz]);
i = zz + 1;
} else {
i = zz;
}
continue;
}
}
}
try out.append(s[i]);
i += 1;
}
return out.toOwnedSlice();
}
fn flushDecl(out: *std.ArrayList(u8), buf: *std.ArrayList(u8), depth: usize, semi: bool) !void {
const decl = std.mem.trim(u8, buf.items, WS);
if (decl.len != 0) { // empty declarations (;;, dangling ;) are skipped
try writePad(out, depth);
try out.appendSlice(decl);
if (semi) try out.append(';');
try out.append('\n');
}
buf.clearRetainingCapacity();
}
/// Conservative minification — see the header for the exact rule list.
pub fn minify(alloc: std.mem.Allocator, raw: []const u8) !FormatResult {
const text = std.mem.trim(u8, raw, WS);
if (text.len == 0) return .{ .output = try alloc.dupe(u8, ""), .error_msg = null };
const m = switch (try mask(alloc, text)) {
.ok => |v| v,
.err => |e| return .{ .output = try alloc.dupe(u8, ""), .error_msg = e },
};
var css = try collapseWs(alloc, m.text);
css = try stripStruct(alloc, css);
css = try dropTrailingSemis(alloc, css);
css = try lowerHex(alloc, std.mem.trim(u8, css, WS));
css = try shortenHexPair(alloc, css);
css = try stripLeadingZero(alloc, css);
css = try stripFractionZeros(alloc, css);
css = try stripIntegralZeros(alloc, css);
css = try dotZeros(alloc, css);
return .{ .output = try unmask(alloc, css, m.strings), .error_msg = null };
}
/// Structural beautifier — 2-space indentation, declarations one per line.
pub fn beautify(alloc: std.mem.Allocator, raw: []const u8) !FormatResult {
const text = std.mem.trim(u8, raw, WS);
if (text.len == 0) return .{ .output = try alloc.dupe(u8, ""), .error_msg = null };
const m = switch (try mask(alloc, text)) {
.ok => |v| v,
.err => |e| return .{ .output = try alloc.dupe(u8, ""), .error_msg = e },
};
const css = try collapseWs(alloc, m.text);
var out = std.ArrayList(u8).init(alloc);
var buf = std.ArrayList(u8).init(alloc);
var depth: i64 = 0;
for (css) |c| {
switch (c) {
'{' => {
const sel = std.mem.trim(u8, buf.items, WS);
if (sel.len == 0)
return .{ .output = try alloc.dupe(u8, ""), .error_msg = "Block without a selector" };
try writePad(&out, depth);
try out.appendSlice(sel);
try out.appendSlice(" {\n");
depth += 1;
buf.clearRetainingCapacity();
},
'}' => {
try flushDecl(&out, &buf, @intCast(@max(0, depth)), false);
depth -= 1;
if (depth < 0)
return .{ .output = try alloc.dupe(u8, ""), .error_msg = "Unbalanced }" };
try writePad(&out, @intCast(@max(0, depth)));
try out.appendSlice("}\n");
},
';' => try flushDecl(&out, &buf, @intCast(@max(0, depth)), true),
else => try buf.append(c),
}
}
if (depth != 0)
return .{ .output = try alloc.dupe(u8, ""), .error_msg = "Unclosed block" };
try flushDecl(&out, &buf, @intCast(depth), false);
return .{ .output = try unmask(alloc, out.items, m.strings), .error_msg = null };
}
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 →