1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
#!/usr/bin/perl
#
# A pretty-printer for polynomials. Identifiers, coefficients, exponents
# and indices are written in different colours, and the output is formatted.
# Written by Thierry Bousch, and released into the Public Domain.
# Here is my choice of colours:
$color_normal = '00'; # Normal mode
$color_identifiers = '01'; # Bright
$color_coefficients = '01;31'; # Bright red
$color_exponents = '01;34'; # Bright blue
$color_indices = '01;32'; # Bright green
$en = "\033[${color_normal}m";
$ei = "\033[${color_identifiers}m";
$ec = "\033[${color_coefficients}m";
$ee = "\033[${color_exponents}m";
$et = "\033[${color_indices}m";
if (open(PIPE, "-|") == 0) {
# This is the child. Add space before + and - but not after a
# comma or opening parenthesis. Then reformat the text.
$columns = 0;
$notfirst = 0;
while (<STDIN>) {
s/([\+\-])/ \1/g;
s/([\(,]) /\1/g;
s,\)/,\) /,g;
s,/\(,/ \(,g;
@line = split(" ");
foreach $word (@line) {
$columns += $notfirst + length($word);
if ($notfirst) {
if ($columns > 76) {
print "\n";
$columns = length($word);
}
else { print " "; }
}
print $word;
$notfirst = 1;
}
}
print "\n";
exit(0);
}
# The parent only needs to do the colorizing
while (<PIPE>) {
# Identifiers
s/((\[[^\]]+\])|([a-zA-Z_]\w*))/$ei\1$en/g;
# Coefficients
s/([+\-\/\(,])(\d+)/\1$ec\2$en/g;
s/^(\d+)/$ec\1$en/g;
# Exponents
s/\^(\d+)/\^$ee\1$en/g;
# Tensor indices
s/\!(\d+)/\!$et\1$en/g;
print;
}
|