#!/usr/bin/perl -w use strict; use diagnostics; # Indent code. Handy for finding nesting errors, # and for autoindenting stuff from the forum. # Bugs: doesn't even attempt to match tokens. # Create hashes of valid in/outdenting strings. # 1-Takes effect this line # 2-Takes effect next line my %incommands=('FUNCTION'=>2,'WHILE'=>2,'REPEAT'=>2, 'IF'=>2,'ELSE'=>2,'FOR'=>2,'DO'=>2); # Create an array of valid unindenting strings. my %outcommands=('ENDFUNCTION'=>1,'ENDWHILE'=>1,'UNTIL'=>1, 'ELSE'=>1,'ENDIF'=>1,'THEN'=>2,'NEXT'=>1,'LOOP'=>1); # Not dealt with/special cases. # 'REMSTART', '','REMEND','RETURN', my $indentThis=0; my $indentNext=0; my $workString=''; my $printString=''; my $inRem=0; # Parse the input. while (<>) { ($workString=$_) =~ s/\s*$//; # Remove trailing whitespace so can detect last character. ($workString=$_) =~ s/^\s*//; # Remove leading whitespace. if ($workString eq '') {print ; next;} #Ignore blank lines. $printString = $workString; # Remove comments, since they do not feature in our calculations. $workString =~ s/REMSTART.*?REMEND//ig; # remstart/remend pairs. if ($inRem) { if ($workString =~ s/.*REMEND//i) { $inRem=0 } else { $workString="" } } if ($workString =~ s/REMSTART.*//i) { $inRem=1 } $workString =~ s/\`.*//; $workString =~ s/REM.*//i; # Keywords. foreach (split /\W/, uc($workString)) { # A command (like else) can be in BOTH simultaneously. if (defined($incommands{$_})) { # print "BINGO!!! $_\n"; $indentThis++ if $incommands{$_}==1; $indentNext++; } if (defined($outcommands{$_})) { # print "BONGO!!! $_\n"; $indentThis-- if $outcommands{$_}==1; $indentNext--; } } $printString = (" " x $indentThis).$printString; print $printString; $indentThis=$indentNext; }