Skip to content

ddocs.latex.pdflatex_utils

Locate, verify, and install pdfLaTeX using TinyTeX as the backend. Confirms that pdflatex (and biber) are callable, downloads and runs the root-free TinyTeX installer when missing, prepends its bin directory to PATH, and installs the tlmgr package collections that mirror the texlive-* packages. Also provides a MiKTeX-style helper that installs packages reported missing in a LaTeX build log.

ddocs.latex.pdflatex_utils

Locate, verify, and install pdfLaTeX (via TinyTeX) for the ddocs pipeline.

Building PDFs from the generated LaTeX needs a TeX engine (pdflatex) plus a set of packages and biber. Unlike pandoc there is no single downloadable binary, so this module uses TinyTeX -- a lightweight, root-free, cross-platform distribution built on TeX Live -- as the install backend:

  1. sanity_check -- is pdflatex (or biber) already callable?
  2. check_pdflatex_installed -- if not, install a TeX distribution. On Debian/Ubuntu it uses apt-get install texlive-* (fast); elsewhere it falls back to TinyTeX (root-free, cross-platform) and tlmgr installs the requested packages. Either way the packages a bare pdflatex needs for Deltares documents are provided. Tune via ddocs pdflatex download --backend apt|tinytex|auto, --packages ..., or --no-packages.
  3. install_missing_packages -- a MiKTeX-style helper that scans a LaTeX build log for missing files and tlmgr installs them on demand (TeX Live does not do this natively). build_pdf uses it to fetch any package a document still needs.

The PATH change affects only the current process and the subprocesses it spawns, not the parent shell.

sanity_check

sanity_check(command: str = 'pdflatex') -> bool

Check whether a TeX command is callable from the command line.

Runs <command> --version as a subprocess. This only inspects what is already reachable on PATH -- it never downloads or installs anything.

Parameters:

Name Type Description Default
command str

The executable to probe, e.g. "pdflatex" or "biber".

'pdflatex'

Returns:

Type Description
bool

True if <command> --version runs successfully, False otherwise.

Examples:

  • Branch on whether pdflatex is available:
    >>> from ddocs.latex.pdflatex_utils import sanity_check
    >>> if sanity_check():  # doctest: +SKIP
    ...     print("ready to build PDFs")
    ready to build PDFs
    
  • Probe a different tool such as biber:
    >>> from ddocs.latex.pdflatex_utils import sanity_check
    >>> sanity_check("biber")  # doctest: +SKIP
    True
    
See Also

check_pdflatex_installed: Verify pdflatex and install TinyTeX when missing.

Source code in src\ddocs\latex\pdflatex_utils.py
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def sanity_check(command: str = "pdflatex") -> bool:
    """Check whether a TeX command is callable from the command line.

    Runs `<command> --version` as a subprocess. This only inspects what is already
    reachable on `PATH` -- it never downloads or installs anything.

    Args:
        command: The executable to probe, e.g. `"pdflatex"` or `"biber"`.

    Returns:
        True if `<command> --version` runs successfully, False otherwise.

    Examples:
        - Branch on whether pdflatex is available:
            ```python
            >>> from ddocs.latex.pdflatex_utils import sanity_check
            >>> if sanity_check():  # doctest: +SKIP
            ...     print("ready to build PDFs")
            ready to build PDFs

            ```
        - Probe a different tool such as biber:
            ```python
            >>> from ddocs.latex.pdflatex_utils import sanity_check
            >>> sanity_check("biber")  # doctest: +SKIP
            True

            ```

    See Also:
        check_pdflatex_installed: Verify pdflatex and install TinyTeX when missing.
    """
    try:
        result = subprocess.run(
            [command, "--version"],
            capture_output=True,
            text=True,
            check=True,
        )
        first_line = result.stdout.splitlines()[0] if result.stdout else command
        print(f"Found {command}: {first_line}")
        found = True
    except (subprocess.CalledProcessError, FileNotFoundError, OSError):
        found = False
    return found

find_tex_bin_dir

find_tex_bin_dir() -> str | None

Locate the TinyTeX bin directory that contains pdflatex.

TinyTeX installs the binaries under <root>/bin/<platform> (e.g. bin/x86_64-linux or bin/windows); the exact platform folder is resolved by globbing so it works across architectures.

Returns:

Type Description
str | None

The absolute path of the directory containing the pdflatex executable, or

str | None

None if no TinyTeX installation is found.

Examples:

  • Get the bin directory if TinyTeX is installed:
    >>> from ddocs.latex.pdflatex_utils import find_tex_bin_dir
    >>> bin_dir = find_tex_bin_dir()  # doctest: +SKIP
    >>> bin_dir.endswith("bin") or "bin" in bin_dir  # doctest: +SKIP
    True
    
Source code in src\ddocs\latex\pdflatex_utils.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def find_tex_bin_dir() -> str | None:
    """Locate the TinyTeX `bin` directory that contains `pdflatex`.

    TinyTeX installs the binaries under `<root>/bin/<platform>` (e.g.
    `bin/x86_64-linux` or `bin/windows`); the exact platform folder is resolved by
    globbing so it works across architectures.

    Returns:
        The absolute path of the directory containing the `pdflatex` executable, or
        None if no TinyTeX installation is found.

    Examples:
        - Get the bin directory if TinyTeX is installed:
            ```python
            >>> from ddocs.latex.pdflatex_utils import find_tex_bin_dir
            >>> bin_dir = find_tex_bin_dir()  # doctest: +SKIP
            >>> bin_dir.endswith("bin") or "bin" in bin_dir  # doctest: +SKIP
            True

            ```
    """
    exe = "pdflatex.exe" if platform.system() == "Windows" else "pdflatex"
    found = None
    for root in _tinytex_root_candidates():
        for candidate in sorted(glob.glob(os.path.join(root, "bin", "*"))):
            if os.path.exists(os.path.join(candidate, exe)):
                found = candidate
                break
        if found:
            break
    return found

install_tlmgr_packages

install_tlmgr_packages(packages: tuple[str, ...] | list[str] = REQUIRED_TLMGR_PACKAGES) -> bool

Install TeX packages with tlmgr.

Parameters:

Name Type Description Default
packages tuple[str, ...] | list[str]

The tlmgr package/collection names to install. Defaults to :data:REQUIRED_TLMGR_PACKAGES (empty -- nothing is pre-installed).

REQUIRED_TLMGR_PACKAGES

Returns:

Type Description
bool

True if tlmgr install succeeded (or there was nothing to install), False

bool

otherwise.

Examples:

  • Calling with no packages is a no-op that succeeds:
    >>> from ddocs.latex.pdflatex_utils import install_tlmgr_packages
    >>> install_tlmgr_packages([])
    True
    
  • Install a specific package:
    >>> from ddocs.latex.pdflatex_utils import install_tlmgr_packages
    >>> install_tlmgr_packages(["tikz"])  # doctest: +SKIP
    True
    
Source code in src\ddocs\latex\pdflatex_utils.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def install_tlmgr_packages(packages: tuple[str, ...] | list[str] = REQUIRED_TLMGR_PACKAGES) -> bool:
    """Install TeX packages with `tlmgr`.

    Args:
        packages: The tlmgr package/collection names to install. Defaults to
            :data:`REQUIRED_TLMGR_PACKAGES` (empty -- nothing is pre-installed).

    Returns:
        True if `tlmgr install` succeeded (or there was nothing to install), False
        otherwise.

    Examples:
        - Calling with no packages is a no-op that succeeds:
            ```python
            >>> from ddocs.latex.pdflatex_utils import install_tlmgr_packages
            >>> install_tlmgr_packages([])
            True

            ```
        - Install a specific package:
            ```python
            >>> from ddocs.latex.pdflatex_utils import install_tlmgr_packages
            >>> install_tlmgr_packages(["tikz"])  # doctest: +SKIP
            True

            ```
    """
    package_list = list(packages)
    if not package_list:
        return True
    print(f"Installing TeX packages via tlmgr: {' '.join(package_list)}")
    try:
        subprocess.run([*_tex_command("tlmgr"), "install", *package_list], check=True)
        ok = True
    except (subprocess.CalledProcessError, FileNotFoundError, OSError):
        ok = False
    return ok

find_missing_packages

find_missing_packages(log_text: str) -> list[str]

Extract package names for files reported missing in a LaTeX build log.

Scans for Filename.sty' not found` style errors and returns the file stems (the usual tlmgr package name). Duplicates are removed while preserving order.

Parameters:

Name Type Description Default
log_text str

The contents of a .log file (or pdflatex stdout/stderr).

required

Returns:

Type Description
list[str]

A list of candidate tlmgr package names, in first-seen order.

Examples:

  • Pull one missing package from a log fragment:
    >>> from ddocs.latex.pdflatex_utils import find_missing_packages
    >>> find_missing_packages("! LaTeX Error: File `tikz.sty' not found.")
    ['tikz']
    
  • De-duplicate and keep order across several errors:
    >>> from ddocs.latex.pdflatex_utils import find_missing_packages
    >>> log = "File `a.sty' not found\nFile `b.cls' not found\nFile `a.sty' not found"
    >>> find_missing_packages(log)
    ['a', 'b']
    
Source code in src\ddocs\latex\pdflatex_utils.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def find_missing_packages(log_text: str) -> list[str]:
    """Extract package names for files reported missing in a LaTeX build log.

    Scans for `File `name.sty' not found` style errors and returns the file stems
    (the usual tlmgr package name). Duplicates are removed while preserving order.

    Args:
        log_text: The contents of a `.log` file (or pdflatex stdout/stderr).

    Returns:
        A list of candidate tlmgr package names, in first-seen order.

    Examples:
        - Pull one missing package from a log fragment:
            ```python
            >>> from ddocs.latex.pdflatex_utils import find_missing_packages
            >>> find_missing_packages("! LaTeX Error: File `tikz.sty' not found.")
            ['tikz']

            ```
        - De-duplicate and keep order across several errors:
            ```python
            >>> from ddocs.latex.pdflatex_utils import find_missing_packages
            >>> log = "File `a.sty' not found\\nFile `b.cls' not found\\nFile `a.sty' not found"
            >>> find_missing_packages(log)
            ['a', 'b']

            ```
    """
    names: list[str] = []
    for match in _MISSING_FILE_RE.finditer(log_text):
        stem = match.group(1).rsplit(".", 1)[0]
        if stem not in names:
            names.append(stem)
    return names

install_missing_packages

install_missing_packages(log_text: str) -> list[str]

Install packages for any files a LaTeX log reports as missing.

This is the TeX Live equivalent of MiKTeX's install-on-build behaviour: parse the log, tlmgr install whatever was missing, and let the caller recompile.

Parameters:

Name Type Description Default
log_text str

The contents of a LaTeX .log file (or build output).

required

Returns:

Type Description
list[str]

The list of package names install was attempted for (empty if none missing).

Examples:

  • No missing files means nothing is installed:
    >>> from ddocs.latex.pdflatex_utils import install_missing_packages
    >>> install_missing_packages("This is pdfTeX ... output written")
    []
    
See Also

find_missing_packages: The log parser this builds on. install_tlmgr_packages: Runs the actual tlmgr install.

Source code in src\ddocs\latex\pdflatex_utils.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def install_missing_packages(log_text: str) -> list[str]:
    """Install packages for any files a LaTeX log reports as missing.

    This is the TeX Live equivalent of MiKTeX's install-on-build behaviour: parse the
    log, `tlmgr install` whatever was missing, and let the caller recompile.

    Args:
        log_text: The contents of a LaTeX `.log` file (or build output).

    Returns:
        The list of package names install was attempted for (empty if none missing).

    Examples:
        - No missing files means nothing is installed:
            ```python
            >>> from ddocs.latex.pdflatex_utils import install_missing_packages
            >>> install_missing_packages("This is pdfTeX ... output written")
            []

            ```

    See Also:
        find_missing_packages: The log parser this builds on.
        install_tlmgr_packages: Runs the actual `tlmgr install`.
    """
    packages = find_missing_packages(log_text)
    if packages:
        install_tlmgr_packages(packages)
    return packages

install_texlive_apt

install_texlive_apt(packages: tuple[str, ...] | list[str] = APT_TEXLIVE_PACKAGES) -> bool

Install a TeX Live subset on Debian/Ubuntu via apt-get.

Runs apt-get update then apt-get install -y <packages> (prefixed with sudo when not already root). This is much faster than the TinyTeX / tlmgr backend on CI runners, but it requires apt-get and root privileges.

Parameters:

Name Type Description Default
packages tuple[str, ...] | list[str]

The apt package names to install. Defaults to :data:APT_TEXLIVE_PACKAGES.

APT_TEXLIVE_PACKAGES

Returns:

Type Description
bool

True if the packages were installed, False if apt-get is unavailable or the

bool

install failed (e.g. no usable sudo).

Examples:

  • Install the default TeX Live packages on Ubuntu:
    >>> from ddocs.latex.pdflatex_utils import install_texlive_apt
    >>> install_texlive_apt()  # doctest: +SKIP
    True
    
See Also

check_pdflatex_installed: Selects this backend automatically on Debian/Ubuntu.

Source code in src\ddocs\latex\pdflatex_utils.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
def install_texlive_apt(packages: tuple[str, ...] | list[str] = APT_TEXLIVE_PACKAGES) -> bool:
    """Install a TeX Live subset on Debian/Ubuntu via `apt-get`.

    Runs `apt-get update` then `apt-get install -y <packages>` (prefixed with `sudo`
    when not already root). This is much faster than the TinyTeX / `tlmgr` backend on CI
    runners, but it requires `apt-get` and root privileges.

    Args:
        packages: The apt package names to install. Defaults to
            :data:`APT_TEXLIVE_PACKAGES`.

    Returns:
        True if the packages were installed, False if `apt-get` is unavailable or the
        install failed (e.g. no usable `sudo`).

    Examples:
        - Install the default TeX Live packages on Ubuntu:
            ```python
            >>> from ddocs.latex.pdflatex_utils import install_texlive_apt
            >>> install_texlive_apt()  # doctest: +SKIP
            True

            ```

    See Also:
        check_pdflatex_installed: Selects this backend automatically on Debian/Ubuntu.
    """
    if shutil.which("apt-get") is None:
        return False
    is_root = getattr(os, "geteuid", lambda: 1)() == 0
    sudo = [] if is_root else (["sudo"] if shutil.which("sudo") else [])
    package_list = list(packages)
    print(f"Installing TeX Live via apt-get: {' '.join(package_list)}")
    try:
        subprocess.run([*sudo, "apt-get", "update"], check=True)
        subprocess.run([*sudo, "apt-get", "install", "-y", *package_list], check=True)
        ok = True
    except (subprocess.CalledProcessError, FileNotFoundError, OSError):
        ok = False
    return ok

check_pdflatex_installed

check_pdflatex_installed(install_packages: bool = True, packages: tuple[str, ...] | list[str] = REQUIRED_TLMGR_PACKAGES, backend: str = 'auto') -> bool

Ensure pdflatex is callable, installing a TeX distribution when it is missing.

If pdflatex is already on PATH this returns immediately. Otherwise a backend is used to install it:

  • apt -- on Debian/Ubuntu (with sudo) install the texlive-* packages via apt-get. Much faster on CI than tlmgr.
  • tinytex -- download and run the official TinyTeX installer (root-free, cross-platform), prepend its bin to PATH, and tlmgr install packages.

With backend="auto" (default) apt is used when available, else TinyTeX. Either way the requested packages are installed so a bare pdflatex can compile Deltares documents; build_pdf additionally installs anything still missing on demand.

Parameters:

Name Type Description Default
install_packages bool

When True (default), install the package set (apt: the texlive-* list; tinytex: tlmgr install packages). When False, only the engine is provisioned.

True
packages tuple[str, ...] | list[str]

tlmgr packages/collections for the tinytex backend. Defaults to :data:REQUIRED_TLMGR_PACKAGES. Ignored by the apt backend, which uses :data:APT_TEXLIVE_PACKAGES.

REQUIRED_TLMGR_PACKAGES
backend str

"auto" (default), "apt", or "tinytex".

'auto'

Returns:

Type Description
bool

True if pdflatex is accessible after the call, False otherwise.

Raises:

Type Description
URLError

If the TinyTeX installer cannot be downloaded.

CalledProcessError

If the TinyTeX installer script fails.

Examples:

  • Guard a PDF build on pdflatex being available:
    >>> from ddocs.latex.pdflatex_utils import check_pdflatex_installed
    >>> if check_pdflatex_installed():  # doctest: +SKIP
    ...     print("building pdf")
    building pdf
    
See Also

install_texlive_apt: The apt backend. sanity_check: The PATH-only probe this builds on. pdflatex_download_cli: CLI wrapper mapping the result to an exit code.

Source code in src\ddocs\latex\pdflatex_utils.py
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def check_pdflatex_installed(
    install_packages: bool = True,
    packages: tuple[str, ...] | list[str] = REQUIRED_TLMGR_PACKAGES,
    backend: str = "auto",
) -> bool:
    """Ensure `pdflatex` is callable, installing a TeX distribution when it is missing.

    If pdflatex is already on `PATH` this returns immediately. Otherwise a backend is
    used to install it:

    - **apt** -- on Debian/Ubuntu (with `sudo`) install the `texlive-*` packages via
      `apt-get`. Much faster on CI than `tlmgr`.
    - **tinytex** -- download and run the official TinyTeX installer (root-free,
      cross-platform), prepend its `bin` to `PATH`, and `tlmgr install` `packages`.

    With ``backend="auto"`` (default) apt is used when available, else TinyTeX. Either
    way the requested packages are installed so a bare `pdflatex` can compile Deltares
    documents; `build_pdf` additionally installs anything still missing on demand.

    Args:
        install_packages: When True (default), install the package set (apt: the
            `texlive-*` list; tinytex: `tlmgr install packages`). When False, only the
            engine is provisioned.
        packages: tlmgr packages/collections for the **tinytex** backend. Defaults to
            :data:`REQUIRED_TLMGR_PACKAGES`. Ignored by the apt backend, which uses
            :data:`APT_TEXLIVE_PACKAGES`.
        backend: ``"auto"`` (default), ``"apt"``, or ``"tinytex"``.

    Returns:
        True if pdflatex is accessible after the call, False otherwise.

    Raises:
        urllib.error.URLError: If the TinyTeX installer cannot be downloaded.
        subprocess.CalledProcessError: If the TinyTeX installer script fails.

    Examples:
        - Guard a PDF build on pdflatex being available:
            ```python
            >>> from ddocs.latex.pdflatex_utils import check_pdflatex_installed
            >>> if check_pdflatex_installed():  # doctest: +SKIP
            ...     print("building pdf")
            building pdf

            ```

    See Also:
        install_texlive_apt: The apt backend.
        sanity_check: The PATH-only probe this builds on.
        pdflatex_download_cli: CLI wrapper mapping the result to an exit code.
    """
    installed = sanity_check("pdflatex")
    if not installed:
        if backend == "auto":
            use_apt = platform.system() == "Linux" and shutil.which("apt-get") is not None
        else:
            use_apt = backend == "apt"

        if use_apt:
            apt_packages = APT_TEXLIVE_PACKAGES if install_packages else ("texlive-latex-base",)
            install_texlive_apt(apt_packages)
            installed = sanity_check("pdflatex")
            if installed:
                print("pdflatex is now accessible!")

        if not installed and backend != "apt":
            bin_dir = find_tex_bin_dir()
            if bin_dir is None:
                _install_tinytex()
                bin_dir = find_tex_bin_dir()

            if bin_dir:
                _prepend_to_path(bin_dir)
                if install_packages:
                    install_tlmgr_packages(packages)
                installed = sanity_check("pdflatex")
                if installed:
                    print("pdflatex is now accessible!")

        if not installed:
            print("Warning: pdflatex could not be made available from the command line.")
    return installed

build_pdf

build_pdf(tex_file: str | Path, max_runs: int = 15, install_missing: bool = True) -> Path

Compile a .tex file to PDF with pdflatex, installing missing packages.

Ensures pdflatex is available (installing TinyTeX if needed), then runs it from the source file's directory so a document class and relative assets resolve. After a failed run it parses the log for missing packages and tlmgr installs them before retrying (the MiKTeX-style behaviour); on success it runs a second pass to resolve cross-references and the table of contents.

The retry loop stops as soon as it stops making progress -- when no missing package is reported, the same set is reported twice in a row, or a tlmgr install fails -- so it never spins pointlessly on a package it cannot install.

Parameters:

Name Type Description Default
tex_file str | Path

Path to the .tex file to compile.

required
max_runs int

Upper bound on pdflatex attempts (a safety cap; the loop usually stops earlier once it stops making progress).

15
install_missing bool

When True, tlmgr install packages reported missing in the log between attempts.

True

Returns:

Name Type Description
The Path

class:pathlib.Path of the produced PDF (<stem>.pdf next to the source).

Raises:

Type Description
RuntimeError

If pdflatex cannot be made available, or no PDF is produced (the message includes the first LaTeX error from the build log).

Examples:

  • Build a PDF from a LaTeX file (requires a TeX engine):
    >>> from ddocs.latex.pdflatex_utils import build_pdf
    >>> pdf = build_pdf("report.tex")  # doctest: +SKIP
    >>> pdf.name  # doctest: +SKIP
    'report.pdf'
    
See Also

check_pdflatex_installed: Ensures the engine is present. install_missing_packages: Installs packages reported missing in the log.

Source code in src\ddocs\latex\pdflatex_utils.py
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def build_pdf(tex_file: str | Path, max_runs: int = 15, install_missing: bool = True) -> Path:
    """Compile a `.tex` file to PDF with `pdflatex`, installing missing packages.

    Ensures `pdflatex` is available (installing TinyTeX if needed), then runs it from
    the source file's directory so a document class and relative assets resolve. After a
    failed run it parses the log for missing packages and `tlmgr install`s them before
    retrying (the MiKTeX-style behaviour); on success it runs a second pass to resolve
    cross-references and the table of contents.

    The retry loop stops as soon as it stops making progress -- when no missing package
    is reported, the same set is reported twice in a row, or a `tlmgr install` fails --
    so it never spins pointlessly on a package it cannot install.

    Args:
        tex_file: Path to the `.tex` file to compile.
        max_runs: Upper bound on `pdflatex` attempts (a safety cap; the loop usually
            stops earlier once it stops making progress).
        install_missing: When True, `tlmgr install` packages reported missing in the
            log between attempts.

    Returns:
        The :class:`pathlib.Path` of the produced PDF (`<stem>.pdf` next to the source).

    Raises:
        RuntimeError: If pdflatex cannot be made available, or no PDF is produced (the
            message includes the first LaTeX error from the build log).

    Examples:
        - Build a PDF from a LaTeX file (requires a TeX engine):
            ```python
            >>> from ddocs.latex.pdflatex_utils import build_pdf
            >>> pdf = build_pdf("report.tex")  # doctest: +SKIP
            >>> pdf.name  # doctest: +SKIP
            'report.pdf'

            ```

    See Also:
        check_pdflatex_installed: Ensures the engine is present.
        install_missing_packages: Installs packages reported missing in the log.
    """
    tex_path = Path(tex_file)
    work_dir = tex_path.parent
    pdf_path = work_dir / f"{tex_path.stem}.pdf"

    if not check_pdflatex_installed():
        raise RuntimeError("pdflatex is not available and could not be installed")

    succeeded = False
    log = ""
    previous_missing: list[str] = []
    for _ in range(max_runs):
        result = subprocess.run(
            ["pdflatex", "-interaction=nonstopmode", tex_path.name],
            cwd=str(work_dir),
            capture_output=True,
            text=True,
        )
        log = f"{result.stdout}\n{result.stderr}"
        if result.returncode == 0:
            succeeded = True
            subprocess.run(
                ["pdflatex", "-interaction=nonstopmode", tex_path.name],
                cwd=str(work_dir),
                capture_output=True,
                text=True,
            )
            break
        if not install_missing:
            break
        missing = find_missing_packages(log)
        # Stop if there is nothing to install, no progress since the previous attempt,
        # or the install itself failed -- otherwise the loop would spin pointlessly.
        if not missing or missing == previous_missing or not install_tlmgr_packages(missing):
            break
        previous_missing = missing

    if not (succeeded and pdf_path.exists()):
        raise RuntimeError(f"pdflatex did not produce {pdf_path.name}: {_first_latex_error(log)}")
    return pdf_path

pdflatex_check_cli

pdflatex_check_cli(args: Namespace | None = None) -> int

CLI handler for ddocs pdflatex check: report whether pdflatex is callable.

This only probes PATH (via :func:sanity_check); it never downloads or installs anything. Use ddocs pdflatex download to install it.

Parameters:

Name Type Description Default
args Namespace | None

Parsed CLI arguments from argparse. Unused; accepted for a uniform handler signature. Defaults to None.

None

Returns:

Type Description
int

0 if pdflatex is already callable, 1 otherwise.

Examples:

  • Probe for pdflatex and use the result as an exit code:
    >>> from ddocs.latex.pdflatex_utils import pdflatex_check_cli
    >>> pdflatex_check_cli()  # doctest: +SKIP
    0
    
See Also

pdflatex_download_cli: Installs pdflatex when it is missing.

Source code in src\ddocs\latex\pdflatex_utils.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
def pdflatex_check_cli(args: argparse.Namespace | None = None) -> int:
    """CLI handler for `ddocs pdflatex check`: report whether pdflatex is callable.

    This only probes `PATH` (via :func:`sanity_check`); it never downloads or installs
    anything. Use `ddocs pdflatex download` to install it.

    Args:
        args: Parsed CLI arguments from argparse. Unused; accepted for a uniform handler
            signature. Defaults to None.

    Returns:
        0 if `pdflatex` is already callable, 1 otherwise.

    Examples:
        - Probe for pdflatex and use the result as an exit code:
            ```python
            >>> from ddocs.latex.pdflatex_utils import pdflatex_check_cli
            >>> pdflatex_check_cli()  # doctest: +SKIP
            0

            ```

    See Also:
        pdflatex_download_cli: Installs pdflatex when it is missing.
    """
    return 0 if sanity_check("pdflatex") else 1

pdflatex_download_cli

pdflatex_download_cli(args: Namespace | None = None) -> int

CLI handler for ddocs pdflatex download: install pdflatex and TeX packages.

Ensures pdflatex is available (installing it via apt or TinyTeX if necessary) and maps the result to a process exit code suitable for :func:sys.exit.

Honours optional argparse fields: no_packages (only ensure pdflatex, install no extra TeX packages), packages (a comma/space-separated string overriding the default :data:REQUIRED_TLMGR_PACKAGES), and backend (auto/apt/tinytex).

Parameters:

Name Type Description Default
args Namespace | None

Parsed CLI arguments from argparse, or None to use the defaults.

None

Returns:

Type Description
int

0 if pdflatex is accessible after the call, 1 otherwise.

Examples:

  • Install pdflatex and use the result as a process exit code:
    >>> from ddocs.latex.pdflatex_utils import pdflatex_download_cli
    >>> pdflatex_download_cli()  # doctest: +SKIP
    0
    
See Also

check_pdflatex_installed: The underlying check-and-install routine.

Source code in src\ddocs\latex\pdflatex_utils.py
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
def pdflatex_download_cli(args: argparse.Namespace | None = None) -> int:
    """CLI handler for `ddocs pdflatex download`: install pdflatex and TeX packages.

    Ensures pdflatex is available (installing it via apt or TinyTeX if necessary) and
    maps the result to a process exit code suitable for :func:`sys.exit`.

    Honours optional argparse fields: ``no_packages`` (only ensure pdflatex, install no
    extra TeX packages), ``packages`` (a comma/space-separated string overriding the
    default :data:`REQUIRED_TLMGR_PACKAGES`), and ``backend`` (auto/apt/tinytex).

    Args:
        args: Parsed CLI arguments from argparse, or None to use the defaults.

    Returns:
        0 if pdflatex is accessible after the call, 1 otherwise.

    Examples:
        - Install pdflatex and use the result as a process exit code:
            ```python
            >>> from ddocs.latex.pdflatex_utils import pdflatex_download_cli
            >>> pdflatex_download_cli()  # doctest: +SKIP
            0

            ```

    See Also:
        check_pdflatex_installed: The underlying check-and-install routine.
    """
    install_packages = True
    packages: tuple[str, ...] | list[str] = REQUIRED_TLMGR_PACKAGES
    backend = "auto"

    if args is not None:
        if getattr(args, "no_packages", False):
            install_packages = False
        elif getattr(args, "packages", None):
            packages = [p for p in args.packages.replace(",", " ").split() if p]
        backend = getattr(args, "backend", None) or "auto"

    accessible = check_pdflatex_installed(
        install_packages=install_packages, packages=packages, backend=backend,
    )
    return 0 if accessible else 1