Un naufragio personal

Ángel Ortega

Reformatting / indenting a Cascade Style Sheet file

If you need to compare two CSS files, the freestyle formatting can drive you crazy. You can use this little Perl script to reformat / reindent them. Or if you just want a tidier file.

#!/usr/bin/perl

# Formats a CSS file from STDIN
# Angel Ortega 
# Public domain

my $css = join('', <STDIN>);
$css =~ s/\s+/ /g;

my $in = 0;

foreach my $c (split(/(\s*\{\s*)|(\s*\}\s*)/, $css)) {
    if ($c =~ /\{/) {
        print " {\n";
        $in = 1;
    }
    elsif ($c =~ /\}/) {
        print "}\n";
        $in = 0;
    }
    else {
        if ($in) {
            foreach my $sc (split(/\s*;\s*/, $c)) {
                print "\t$sc;\n";
            }
        }
        else {
            print $c;
        }
    }
}

I agree that, if comparing two CSS files is the aim, sorting the entries alphabetically would also be great; I left that as an exercise for the reader.