Using Python to Automate Content for a LaTeX Report

The report in question was a school project for Computational Algebra in the spring of 2025. A requirement was to show the source code for each problem, along with the explanation of the implementation.

I decided to use doit, a framework similar to make, but more flexible. This allowed me to ensure that the report was always up to date with my source code, by listing the relevant source files as dependencies. Below is the rule for generating the final pdf:


def task_compile_pdf():
    report_name = "project4report"
    return {
        "actions": [
            [
                "pdflatex",
                "-interaction=nonstopmode",
                "-output-directory=temp",
                f"{report_name}.tex",
            ]
        ],
        "file_dep": [f"{report_name}.tex"] + list(get_file_refs(f"{report_name}.tex")) +
        [f'temp/func-{module}-{func}.py' for module, func in get_func_code_refs(f"{report_name}.tex")],
        "targets": [f"temp/{report_name}.pdf"],
    }

There are three different kinds of file dependencies here.

[f"{report_name}.tex"] is the main .tex file that should be compiled.

list(get_file_refs(f"{report_name}.tex")) looks through the .tex file for references to local files and lists them as dependencies.

[f'temp/func-{module}-{func}.py' for module, func in get_func_code_refs(f"{report_name}.tex")] looks through the .tex file for file paths that match a pre-defined pattern. These refer to functions in my source code.

This pattern allows me to include the source code of any function, simply by refering to a file named "temp/func-{module}-{func}.py". Doit will then create this file with the correct content, and update it if the source code changes.

The full code is available here.