1<?php
2
3require_once(dirname(__FILE__).'/../../lib/plugins.php');
4
5class projects_plugin_latex_dependency extends Plugin {
6    /**
7     * The name of the parser, a human readable string, a unique identifier
8     */
9    public function name() { return "Latex Dependency"; }
10
11    /**
12     * whether this parser can make a given target
13     */
14    public function can_handle($project, $file) {
15        if ($file->is_target()) return false;
16        return has_extension($file->name(), ".tex");
17    }
18
19    /**
20     * The files used in this file
21     */
22    private function dependency($content) {
23        $inputs = find_command('input', $content);
24        $includes = find_command('include', $content);
25        $graphs = find_command('includegraphics', $content, ".pdf");
26        $bibs = find_command('bibliography', $content, ".bib");
27        $all = array_merge($inputs, $includes, $graphs, $bibs);
28        return array_keys(array_flip($all));
29    }
30
31    public function handle($project, $source_file) {
32        $deps = $source_file->dependency();
33        $uses = array_diff($this->dependency($source_file->content()),
34            $deps);
35        foreach ($uses as $use) $source_file->add_dependency($use);
36        return $source_file;
37    }
38
39}
40
41function match_command($command, $content) {
42    $parameters = '(?i:\[.*?\])?';
43    $pattern = "/\\\\$command *$parameters *\{ *(?P<content>.*?) *\}/";
44    $matched = preg_match_all($pattern, $content, $matches);
45    if ($matched == 0) return NULL;
46    return $matches;
47}
48
49function find_command($command, $content, $file_extension = ".tex") {
50    $deps = array();
51    $matches = match_command($command, $content);
52    if ($matches == NULL) return array();
53    foreach ($matches['content'] as $match)
54        if (has_extension($match, $file_extension))
55            $deps[] = $match;
56        else
57            $deps[] = $match . $file_extension;
58    return $deps;
59}
60