CSS Minify & Beautify — Python 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 Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""css-minify — CSS minifier & beautifier. Python 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 with regexes carrying no lookaround (the hex
pair shortener uses backreferences, which `re` supports natively) so the Go
twin reproduces byte-identical output. 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 result["error"] (None = success); empty input is
a successful empty output, never an error."""
import re
_WS = re.compile(r"\s+")
_STRUCT = re.compile(r"\s*([{};:,>])\s*")
_TRAILING_SEMIS = re.compile(r";+}")
_HEX_LOWER = re.compile(r"#[0-9a-fA-F]{3,8}")
_HEX_PAIR = re.compile(r"#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3([^0-9a-f]|$)")
_LEADING_ZERO = re.compile(r"(^|[^A-Za-z0-9_.#$%-])0+(\.[0-9]+)")
_FRACTION_ZEROS = re.compile(r"(\.[0-9]*[1-9])0+([^0-9]|$)")
_INTEGRAL_ZEROS = re.compile(r"(^|[^A-Za-z0-9_.#$%-])([0-9]+)\.0+([^0-9]|$)")
_DOT_ZEROS = re.compile(r"(^|[^A-Za-z0-9_.#$%-])\.0+([^0-9]|$)")
_SENTINEL = re.compile("\x00([0-9]+)\x00")
def _mask(raw):
"""Scan CSS into (masked, strings), masking every string literal as a
\x00n\x00 sentinel and dropping /* */ comments. On failure returns a
dict with only an "error" key carrying the pinned TS string."""
out = []
strings = []
i = 0
n = len(raw)
while i < n:
ch = raw[i]
if ch == '"' or ch == "'":
start = i
i += 1
while i < n and raw[i] != ch:
if raw[i] == "\\" and i + 1 < n:
i += 1 # escaped char
i += 1
if i >= n:
return {"error": "Unterminated string"}
i += 1
strings.append(raw[start:i])
out.append("\x00%d\x00" % (len(strings) - 1))
elif ch == "/" and i + 1 < n and raw[i + 1] == "*":
end = raw.find("*/", i + 2)
if end == -1:
return {"error": "Unterminated comment"}
i = end + 2
else:
out.append(ch)
i += 1
return {"masked": "".join(out), "strings": strings}
def _unmask(text, strings):
return _SENTINEL.sub(lambda m: strings[int(m.group(1))], text)
def minify_css(raw):
"""Conservative minification — see the module docstring for the rules."""
text = raw.strip()
if not text:
return {"output": "", "error": None}
m = _mask(text)
if "error" in m:
return {"output": "", "error": m["error"]}
css = _WS.sub(" ", m["masked"])
css = _STRUCT.sub(r"\g<1>", css)
css = _TRAILING_SEMIS.sub("}", css)
css = css.strip()
css = _HEX_LOWER.sub(lambda h: h.group(0).lower(), css)
css = _HEX_PAIR.sub(r"#\g<1>\g<2>\g<3>\g<4>", css)
css = _LEADING_ZERO.sub(r"\g<1>\g<2>", css)
css = _FRACTION_ZEROS.sub(r"\g<1>\g<2>", css)
css = _INTEGRAL_ZEROS.sub(r"\g<1>\g<2>\g<3>", css)
# \g<1>0 (not \1 0): group 1 + a literal '0', unambiguous.
css = _DOT_ZEROS.sub(r"\g<1>0\g<2>", css)
return {"output": _unmask(css, m["strings"]), "error": None}
def beautify_css(raw):
"""Structural beautifier — 2-space indentation, declarations one per line."""
text = raw.strip()
if not text:
return {"output": "", "error": None}
m = _mask(text)
if "error" in m:
return {"output": "", "error": m["error"]}
css = _WS.sub(" ", m["masked"])
strings = m["strings"]
out = []
buffer = []
depth = 0
def flush(semi):
decl = "".join(buffer).strip()
if decl:
out.append(" " * depth + decl + (";" if semi else "") + "\n")
del buffer[:]
for ch in css:
if ch == "{":
sel = "".join(buffer).strip()
del buffer[:]
if not sel:
return {"output": "", "error": "Block without a selector"}
out.append(" " * depth + sel + " {\n")
depth += 1
elif ch == "}":
flush(False)
depth -= 1
if depth < 0:
return {"output": "", "error": "Unbalanced }"}
out.append(" " * depth + "}\n")
elif ch == ";":
flush(True)
else:
buffer.append(ch)
if depth != 0:
return {"output": "", "error": "Unclosed block"}
flush(False)
return {"output": _unmask("".join(out), strings), "error": None}
# Example:
# minify_css("body { color : #AABBCC; margin : 0.50px; }")["output"]
# → 'body{color:#abc;margin:.5px}'
# beautify_css("a{b:c}")["output"] → 'a {\n b: c;\n}\n'
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 →