Skip to content

Plugin API

Plugins bundle opinionated HTML post-processors and asset helpers so you can extend TeXSmith without patching the core read → IR → write pipeline.

texsmith.plugins exposes a namespace package populated by the MkDocs hook in docs/hooks/mkdocs_hooks.py, re-exporting the maintained plugin modules under texsmith.adapters.plugins.

Loading plugins

import texsmith.plugins.snippet  # noqa: F401

from texsmith import Document, convert_documents

bundle = convert_documents([Document.from_markdown(Path("intro.md"))])

Authoring your own plugin

  1. Create a module (e.g., texsmith.plugins.acme) exposing a Markdown extension and/or the HTML rewriting helpers your documents need.
  2. Declare entry points or instruct consumers to import texsmith.plugins.acme before rendering.
  3. Optionally provide a MkDocs plugin/hook so documentation builds load your plugin automatically.

Keep plugin modules small and focused.

Reference

Compatibility layer exposing plugin integrations to documentation.

TeXSmith consolidated its plugin utilities under texsmith.adapters.plugins. mkdocstrings still references the historical texsmith.plugins namespace, so we re-export the maintained modules here to keep the public import path available.

Plugin rendering fenced snippet blocks into standalone PDF assets.

SnippetBlock dataclass

SnippetBlock(
    content: str | None,
    front_matter: dict[str, Any],
    sources: list[Path],
    layout: tuple[int, int] | None,
    preview_dogear: bool,
    preview_fold_size: float | None,
    template_id: str | None,
    cwd: Path | None,
    caption: str | None,
    label: str | None,
    figure_width: str | None,
    template_overrides: dict[str, Any],
    digest: str,
    bibliography_files: list[Path],
    promote_title: bool,
    drop_title: bool,
    suppress_title_metadata: bool,
)

Parsed representation of a snippet fence.

asset_filename

asset_filename(digest: str, suffix: str) -> str

Return the deterministic filename for a snippet artefact.

Source code in src/texsmith/adapters/plugins/snippet.py
470
471
472
def asset_filename(digest: str, suffix: str) -> str:
    """Return the deterministic filename for a snippet artefact."""
    return f"{_SNIPPET_PREFIX}{digest}{suffix}"

ensure_snippet_assets

ensure_snippet_assets(
    block: SnippetBlock,
    *,
    output_dir: Path,
    source_path: Path | str | None = None,
    emitter: DiagnosticEmitter | None = None,
) -> _SnippetAssets

Render snippet assets into the provided directory when missing.

Source code in src/texsmith/adapters/plugins/snippet.py
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
def ensure_snippet_assets(
    block: SnippetBlock,
    *,
    output_dir: Path,
    source_path: Path | str | None = None,
    emitter: DiagnosticEmitter | None = None,
) -> _SnippetAssets:
    """Render snippet assets into the provided directory when missing."""
    destination = Path(output_dir).resolve()
    destination.mkdir(parents=True, exist_ok=True)
    pdf_path = destination / asset_filename(block.digest, ".pdf")
    png_path = destination / asset_filename(block.digest, ".png")

    host_path = Path(source_path) if source_path is not None else destination / "snippet.md"
    host_dir = _resolve_base_dir(block, host_path)
    host_name = host_path.stem or "snippet"

    documents: list[Document] = []
    inline_document = _build_document(block, host_dir=host_dir, host_name=host_name)
    if inline_document is not None:
        documents.append(inline_document)

    bibliography_files = list(block.bibliography_files)
    document_sources: list[Path] = []
    for path in block.sources:
        suffix = path.suffix.lower()
        if suffix in {".bib", ".bibtex", ".ris"}:
            if path not in bibliography_files:
                bibliography_files.append(path)
            continue
        document_sources.append(path)

    if document_sources:
        documents.extend(
            _build_documents_from_sources(
                document_sources,
                promote_title=block.promote_title,
                drop_title=block.drop_title,
                suppress_title=block.suppress_title_metadata,
            )
        )

    if not documents:
        raise InvalidNodeError("Snippet block is empty; provide inline content or sources.")

    runtime = _resolve_template_runtime(block, documents, host_dir)
    merged_overrides = _merge_fragment_defaults(block.template_overrides, runtime)
    merged_overrides.setdefault("glossary_inline", True)
    dogear_enabled = _frame_dogear_enabled(merged_overrides) or block.preview_dogear
    preview_fold_px: int | None = None
    if dogear_enabled:
        preview_fold_px = _frame_fold_size_px(
            merged_overrides,
            (0, 0),
        )

    caches = _resolve_caches()
    template_version = None
    if caches:
        info = getattr(runtime.instance, "info", None)
        if info is not None:
            version = getattr(info, "version", None)
            template_version = str(version) if version is not None else None

    pdf_missing = not pdf_path.exists()
    png_missing = not png_path.exists()
    assets = _SnippetAssets(pdf=pdf_path, png=png_path)

    def _flush_caches() -> None:
        for cache in caches:
            cache.flush()

    def _store_in_caches() -> None:
        if not caches:
            return
        for cache in caches:
            cache.store(
                block.digest,
                pdf_path,
                png_path,
                template_version=template_version,
                block=block,
                source_path=Path(source_path) if source_path is not None else None,
            )
        _flush_caches()

    if not pdf_missing and not png_missing:
        _store_in_caches()
        return assets

    if caches and (pdf_missing or png_missing):
        for cache in caches:
            cached_assets = cache.lookup(block.digest, template_version=template_version)
            if cached_assets is None:
                continue
            try:
                if pdf_missing:
                    shutil.copy2(cached_assets.pdf, pdf_path)
                    pdf_missing = False
                if png_missing:
                    shutil.copy2(cached_assets.png, png_path)
                    png_missing = False
            except OSError:
                cache.discard(block.digest)
                continue
            if not pdf_missing and not png_missing:
                _store_in_caches()
                return assets
        _flush_caches()

    if not pdf_missing and png_missing:
        _pdf_to_png_grid(
            pdf_path,
            png_path,
            layout=block.layout,
            transparent_corner=dogear_enabled,
            spacing=None if block.layout else 0,
            fold_size=preview_fold_px,
        )
        png_missing = False
        _store_in_caches()
        return assets

    _announce_build(block, source_path, emitter)

    settings = ConversionRequest(
        copy_assets=True,
        convert_assets=False,
        hash_assets=False,
        manifest=False,
    )
    session = TemplateSession(runtime=runtime, settings=settings, emitter=emitter)
    for document in documents:
        session.add_document(document)
    if bibliography_files:
        session.add_bibliography(*bibliography_files)
    if merged_overrides:
        session.update_options(merged_overrides)

    work_dir = destination / f".build-{block.digest}"
    shutil.rmtree(work_dir, ignore_errors=True)
    work_dir.mkdir(parents=True, exist_ok=True)

    debug_dir: Path | None = None
    try:
        render_result = session.render(work_dir)
        compiled_pdf = _compile_pdf(render_result)
        shutil.copy2(compiled_pdf, pdf_path)
    except Exception as exc:
        # Preserve the work directory for post-mortem inspection when compilation fails.
        try:
            cache_root = _resolve_cache_root() or Path(tempfile.gettempdir()) / "texsmith"
            debug_dir = (cache_root / "snippet-fail" / block.digest).resolve()
            if debug_dir.exists():
                shutil.rmtree(debug_dir, ignore_errors=True)
            shutil.copytree(work_dir, debug_dir, dirs_exist_ok=True)
        except Exception:
            debug_dir = None
        if debug_dir is not None:
            raise exc.__class__(f"{exc} (debug: {debug_dir})") from exc
        raise
    else:
        dump_dir = _resolve_snippet_dump_dir()
        if dump_dir is not None:
            target_dir = dump_dir / block.asset_basename
            if target_dir.exists():
                shutil.rmtree(target_dir, ignore_errors=True)
            shutil.copytree(work_dir, target_dir, dirs_exist_ok=True)
        shutil.rmtree(work_dir, ignore_errors=True)

    total_cells = 1
    if block.layout:
        cols, rows = block.layout
        total_cells = max(cols, 1) * max(rows, 1)
    _pdf_to_png_grid(
        pdf_path,
        png_path,
        layout=block.layout,
        transparent_corner=dogear_enabled,
        spacing=None if total_cells > 1 else 0,
        decorate_page=None,
        fold_size=preview_fold_px,
    )

    _store_in_caches()
    return assets

render_snippet_latex

render_snippet_latex(
    html: str, context: RenderContextLike
) -> str

Render a preserved .snippet HTML element to a figure string.

Single entry point used by the writer: it unwraps the stored snippet markup, parses the fence (resolving file inclusions against the document via the render context), compiles the preview assets, registers the artefact and emits the figure. Keeps all snippet-HTML handling inside this plugin instead of leaking BeautifulSoup and the block internals into the writer.

Source code in src/texsmith/adapters/plugins/snippet.py
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
def render_snippet_latex(html: str, context: RenderContextLike) -> str:
    """Render a preserved ``.snippet`` HTML element to a LaTeX figure string.

    Single entry point used by the LaTeX writer: it unwraps the stored snippet
    markup, parses the fence (resolving file inclusions against the document via
    the render context), compiles the preview assets, registers the artefact and
    emits the figure. Keeps all snippet-HTML handling inside this plugin instead
    of leaking BeautifulSoup and the block internals into the writer.
    """
    from bs4 import BeautifulSoup

    soup = BeautifulSoup(html, "html.parser")
    element = soup.find(["div", "pre"])
    if element is None:
        return ""

    host_path = _resolve_host_path(
        context.runtime.get("document_path"), context.runtime.get("source_dir")
    )
    block = _extract_snippet_block(element, host_path=host_path)
    if block is None:
        return ""

    assets = _render_snippet_assets(block, context)
    context.assets.register(f"snippet::{block.digest}", assets.pdf)
    return str(_render_figure(context, assets, block))

rewrite_html_snippets

rewrite_html_snippets(
    html: str,
    resolver: Callable[[SnippetBlock], tuple[str, str]],
    *,
    source_path: Path | str | None = None,
) -> str

Replace snippet fences in an HTML fragment with linked previews.

Source code in src/texsmith/adapters/plugins/snippet.py
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
def rewrite_html_snippets(
    html: str,
    resolver: Callable[[SnippetBlock], tuple[str, str]],
    *,
    source_path: Path | str | None = None,
) -> str:
    """Replace snippet fences in an HTML fragment with linked previews."""
    if "snippet" not in html:
        return html
    host_path = Path(source_path) if source_path is not None else None

    soup = BeautifulSoup(html, "html.parser")
    mutated = False
    for element in soup.find_all(["div", "pre"]):
        block = _extract_snippet_block(element, host_path=host_path)
        if block is None:
            continue
        pdf_url, png_url = resolver(block)
        anchor = soup.new_tag(
            "a",
            href=pdf_url,
            target="_blank",
            rel="noopener noreferrer",
        )
        image_attrs = {"src": png_url, "alt": block.caption or "Snippet", "class": ["ts-snippet"]}
        if block.figure_width:
            image_attrs["width"] = block.figure_width
        image = soup.new_tag("img", **image_attrs)
        anchor.append(image)
        element.replace_with(anchor)
        mutated = True

    return str(soup) if mutated else html