Created
September 3, 2010 10:12
-
-
Save sortega/563712 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl -w | |
use Getopt::Long; | |
use strict; | |
sub usage { | |
print <<EOB ; | |
usage: $0 --tabwidth 2 <files> | |
Compacts the indentation to the desired fixed step. | |
-t | |
--tabwidth Tabwidth in spaces. 2 spaces by default. | |
EOB | |
exit -1; | |
} | |
GetOptions( | |
"tabwidth|t=i" => \(my $tabwidth), | |
) or usage(); | |
$tabwidth = 2 unless $tabwidth; | |
my @indents = (); | |
my $indent = { | |
Level => 0, | |
Spaces => 0, | |
}; | |
while(<>) { | |
if (/^\s*$/) { # skip empty lines | |
print; | |
next; | |
} | |
my ($spaces, $line) = /^(\s*)(.*)$/; | |
my $indented_spaces = length $spaces; | |
if ($indented_spaces > $indent->{Spaces}) { | |
# New level | |
my $new_indent = { | |
Level => $indent->{Level} + 1, | |
Spaces => $indented_spaces, | |
}; | |
push @indents, $indent; | |
$indent = $new_indent; | |
} else { | |
while ($indented_spaces < $indent->{Spaces}) { | |
$indent = pop @indents; | |
} | |
} | |
print " "x($indent->{Level} * $tabwidth), $line, "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment