# Copyright (C) 2011 John Collins, under CC BY-SA 3.0
# (from https://tex.stackexchange.com/a/31952)
# "recursive" tex->pdf dependencies, for triggering a rebuild when the
# tex file of a pdf dependency changes
add_cus_dep('tex', 'pdf', 0, 'maketex2pdf');
sub maketex2pdf {
    # Make pdf file from tex file, recording dependencies
    my $dep_file = "$_[0].dep";
    system("latexmk -xelatex -deps -deps-out=$dep_file $_[0]");

    # Read the list of dependencies, which is in the
    #   format of a fragment of a makefile.
    # In the precise format written by latexmk, source filenames on a
    #   are each on a separate line starting with white space; these
    #   lines often end with a continuation character.
    my $fh = new FileHandle "< $dep_file";
    if (! defined $fh ) {
        warn "maketex2pdf: Cannot read '$dep_file'\n";
        return;
    }
    while ( <$fh> ) {
        # Ignore comment lines:
        if ( /^\s*#/ ) { next; }
        if ( /^\s+(.*)$/ ) {
            # Line containing name of source file
            my $dep = $1;
            # Remove continuation character:
            $dep =~ s/\\$//;
            # Make sure this file is in the list of source files for the
            # current rule, by calling rdb_ensure_rule.  This is an 
            # internal latexmk subroutine.  The first argument to this
            # subroutine is $rule, which is a global variable that
            # indicates what rule is currently being processed.
            rdb_ensure_file( $rule, $dep );
        }
    }
    close $fh;
    return 0;
}
