colspec-fix.pl 1.87 KB
Newer Older
unknown's avatar
unknown committed
1 2 3 4 5 6
#!/usr/bin/perl -w

#
# Script to rewrite colspecs from relative values to absolute values
#

7 8
# arjen 2002-03-14 append "cm" specifier to colwidth field.

unknown's avatar
unknown committed
9 10
use strict;

unknown's avatar
unknown committed
11 12
my $table_width  = 12.75; # Specify the max width of the table in cm
my $gutter_width =  0.55; # Specify the width of the gutters in cm
unknown's avatar
unknown committed
13

unknown's avatar
unknown committed
14
my $str = join '', <>; # Push stdin (or file)
unknown's avatar
unknown committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

$str =~ s{([\t ]*(<colspec colwidth=\".+?\" />\s*)+)}
         {&rel2abs($1)}ges;

print STDOUT $str;
exit;

#
# Definitions for helper sub-routines
#

sub msg {
    print STDERR shift, "\n";
}

sub rel2abs {
31 32
    my $str           = shift;
    my $colnum        = 1;
33
    
34 35 36 37 38 39 40 41
    my @widths        = ();
    my $total         = 0;
    my $output        = '';
    
    my $gutters;
    my $content_width;
    my $total_width;
    my @num_cache;
unknown's avatar
unknown committed
42 43 44 45 46 47 48 49 50
    
    $str =~ /^(\s+)/;
    my $ws = $1;
    
    while ($str =~ m/<colspec colwidth="(\d+)\*" \/>/g) {
        $total += $1;
        push @widths, $1;
    }

51 52 53 54 55 56 57 58 59
    msg("!!! WARNING: Total Percent > 100%: $total%") if $total > 100;

    if (! $total) {
        die 'Something bad has happened - the script believes that there are no columns';
    }

    $gutters = $#widths * $gutter_width;
    $content_width = $table_width - $gutters;
    # Don't forget that $#... is the last offset not the count
unknown's avatar
unknown committed
60 61

    foreach (@widths) {
62 63 64 65 66 67 68 69 70 71 72
        my $temp = sprintf ("%0.2f", $_/100 * $content_width);
        $total_width += $temp;

        if ($total_width > $content_width) {
            $temp -= $total_width - $content_width;
            msg("!!! WARNING: Column width reduced from " .
                ($temp + ($total_width - $content_width)) . " to $temp !!!");
            $total_width -= $total_width - $content_width;
        }
        
        $output .= $ws . '<colspec colnum="'. $colnum .'" colwidth="'. $temp .'cm" />' . "\n";
73
        ++$colnum;
74
        push @num_cache, $temp;
unknown's avatar
unknown committed
75
    }
76
   
unknown's avatar
unknown committed
77 78
    return $output . "\n$ws";
}