CSS Minify & Beautify — Kotlin 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 Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.
// css-minify — CSS minifier & beautifier. Kotlin port (canonical TS:
// src/lib/css-minify.ts; Go twin: cli/css-minify). One scanner masks string
// literals as \u0000n\u0000 sentinels and drops /* */ comments; every
// textual rule then runs on the masked text with JVM regexes carrying no
// lookaround (backreferences are supported) 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 FormatResult.error (null
// mirrors TS null); empty input is a successful empty output, never an
// error.
data class FormatResult(val output: String, val error: String?)
/** Scan CSS into a masked text where every string literal is replaced by a
* \u0000n\u0000 sentinel (n = index into `strings`); comments are dropped.
* error is non-null on failure (pinned TS strings). */
class Masked(val masked: String, val strings: List<String>, val error: String?)
private fun mask(raw: String): Masked {
val out = StringBuilder()
val strings = mutableListOf<String>()
var i = 0
while (i < raw.length) {
val ch = raw[i]
if (ch == '"' || ch == '\'') {
val start = i
i++
while (i < raw.length && raw[i] != ch) {
if (raw[i] == '\\' && i + 1 < raw.length) i++ // escaped char
i++
}
if (i >= raw.length) return Masked("", emptyList(), "Unterminated string")
i++
strings.add(raw.substring(start, i))
out.append('\u0000').append(strings.size - 1).append('\u0000')
} else if (ch == '/' && i + 1 < raw.length && raw[i + 1] == '*') {
val end = raw.indexOf("*/", i + 2)
if (end < 0) return Masked("", emptyList(), "Unterminated comment")
i = end + 2
} else {
out.append(ch)
i++
}
}
return Masked(out.toString(), strings, null)
}
private fun unmask(text: String, strings: List<String>): String =
Regex("\u0000([0-9]+)\u0000").replace(text) { m -> strings[m.groupValues[1].toInt()] }
/** Conservative minification — see header for the exact rule list. */
fun minifyCss(raw: String): FormatResult {
val text = raw.trim()
if (text.isEmpty()) return FormatResult("", null) // empty input is NOT an error
val m = mask(text)
if (m.error != null) return FormatResult("", m.error)
var css = m.masked
.replace(Regex("\\s+"), " ")
.replace(Regex("\\s*([{};:,>])\\s*"), "$1")
.replace(Regex(";+}"), "}")
.trim()
.replace(Regex("#[0-9a-fA-F]{3,8}")) { it.value.lowercase() }
.replace(Regex("#([0-9a-f])\\1([0-9a-f])\\2([0-9a-f])\\3([^0-9a-f]|$)")) {
"#" + it.groupValues[1] + it.groupValues[2] + it.groupValues[3] + it.groupValues[4]
}
css = css.replace(Regex("(^|[^A-Za-z0-9_.#$%-])0+(\\.[0-9]+)"), "$1$2")
css = css.replace(Regex("(\\.[0-9]*[1-9])0+([^0-9]|$)"), "$1$2")
css = css.replace(Regex("(^|[^A-Za-z0-9_.#$%-])([0-9]+)\\.0+([^0-9]|$)"), "$1$2$3")
// group 1 + literal '0' + group 2 (callback avoids the $10 ambiguity)
css = css.replace(Regex("(^|[^A-Za-z0-9_.#$%-])\\.0+([^0-9]|$)")) { it.groupValues[1] + "0" + it.groupValues[2] }
return FormatResult(unmask(css, m.strings), null)
}
/** Structural beautifier — 2-space indentation, declarations one per line. */
fun beautifyCss(raw: String): FormatResult {
val text = raw.trim()
if (text.isEmpty()) return FormatResult("", null)
val m = mask(text)
if (m.error != null) return FormatResult("", m.error)
val css = m.masked.replace(Regex("\\s+"), " ")
val strings = m.strings
val out = StringBuilder()
val buffer = StringBuilder()
var depth = 0
fun flush(semi: Boolean) {
val decl = buffer.toString().trim()
if (decl.isNotEmpty()) out.append(" ".repeat(depth)).append(decl).append(if (semi) ";" else "").append('\n')
buffer.setLength(0)
}
for (ch in css) {
when (ch) {
'{' -> {
val sel = buffer.toString().trim()
buffer.setLength(0)
if (sel.isEmpty()) return FormatResult("", "Block without a selector")
out.append(" ".repeat(depth)).append(sel).append(" {\n")
depth++
}
'}' -> {
flush(false)
depth--
if (depth < 0) return FormatResult("", "Unbalanced }")
out.append(" ".repeat(depth)).append("}\n")
}
';' -> flush(true)
else -> buffer.append(ch)
}
}
if (depth != 0) return FormatResult("", "Unclosed block")
flush(false)
return FormatResult(unmask(out.toString(), strings), null)
}
fun main() {
val sheet = "@media (max-width: 600px) { /* comment */ body { color : #AABBCC; margin : 0.50px; content : \"a, b\" ; }}"
println(minifyCss(sheet).output) // @media (max-width: 600px){body{color:#abc;margin:.5px;content:"a, b"}}
print(beautifyCss(sheet).output)
}
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 →