Friday, 3 June 2011

Saving me from myself

The great thing about using Perl to schedule the generation of your LaTeX documents, is that you can also use the Perl to catch a bunch of little mistakes that make life unpleasant in non-obvious ways. One of my favourites is to put the \label before the \caption in the figure environment, because, of course, in any sane world you could do that, but not in LaTeX. Thus, Perl to the rescue:

method check_figure_labels {
    my $file = $self->src;
    my ($in_figure, $seen_caption) = 0;
    foreach my $line (read_file($file)) {
      $line =~ s/%.*$//; # strip comments
      given ($line) {
        when (/\\end{document}/) {
          last;
        }
        when (/\\begin{figure}/) {
          $in_figure = 1;
        }
        when (/\\end{figure}/) {
          $seen_caption = 0;
          $in_figure = 0;
        }
        next unless $in_figure;
        when (/\\caption/) {
          $seen_caption = 1;
        }
        when (/\\label{(.*?)}/) {
          die "Label for LATEX figure $1 comes before the \\caption you will hate yourself later\n"
            unless $seen_caption;
        }
      }
    }
}

Also, sometimes I cannot spell the names of famous (and awesome) physicists:

method check_rayleigh {
    my $file = $self->src;
    my $latex = read_file($file);
    if ($latex =~ /raleigh/i) {
       die "YOU ARE A MORON! RAYLEIGH HAS A Y IN IT!";
    }
    return;
}

No comments:

Post a Comment