Skip to content

Plugin API

Plugins bundle the build-time helpers an IR pass drives — the snippet compiler's nested build, the MkDocs site-side HTML rewriting — so you can extend TeXSmith without patching the core parse → 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 the build-time helpers your documents need, and an IR pass that calls them.
  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.

SnippetAssets dataclass

SnippetAssets(pdf: Path, png: Path)

The rendered pair of a snippet: the PDF (LaTeX) and its PNG preview (web, Typst).

SnippetBlock dataclass

SnippetBlock(
    content: str | None,
    front_matter: dict[str, Any],
    sources: list[Path],
    layout: tuple[int, int] | None,
    preview_dogear: bool,
    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
418
419
420
def asset_filename(digest: str, suffix: str) -> str:
    """Return the deterministic filename for a snippet artefact."""
    return f"{_SNIPPET_PREFIX}{digest}{suffix}"

build_snippet_block

build_snippet_block(
    raw_content: str,
    *,
    language: str | None,
    attributes: Mapping[str, Any] | None = None,
    meta: Mapping[str, str] | None = None,
    host_path: Path | None = None,
) -> SnippetBlock | None

Parse a snippet fence into a :class:SnippetBlock; the pure half of the fence handling.

raw_content is the fence body, language its info-string language, attributes the :data:FENCE_ATTRIBUTES the host element carried (caption, label, width, layout, config) and meta the parsed data-meta tokens of the HTML reader. The HTML path (:func:_extract_snippet_block) and the tmark snippet pass both end here. None when the fence has neither inline content nor sources.

The body is taken without its trailing newlines, so that the readers agree on one text and therefore on one digest: the IR gives a fence body that stops at the closing fence, while the HTML of the same fence ends with the newline the renderer put before </code>, and a file spliced into a fence by include= ends with its own.

Source code in src/texsmith/adapters/plugins/snippet.py
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
def build_snippet_block(
    raw_content: str,
    *,
    language: str | None,
    attributes: Mapping[str, Any] | None = None,
    meta: Mapping[str, str] | None = None,
    host_path: Path | None = None,
) -> SnippetBlock | None:
    """Parse a snippet fence into a :class:`SnippetBlock`; the pure half of the fence handling.

    ``raw_content`` is the fence body, ``language`` its info-string language,
    ``attributes`` the :data:`FENCE_ATTRIBUTES` the host element carried
    (``caption``, ``label``, ``width``, ``layout``, ``config``) and ``meta``
    the parsed ``data-meta`` tokens of the HTML reader. The HTML path
    (:func:`_extract_snippet_block`) and the tmark ``snippet`` pass both end
    here. ``None`` when the fence has neither inline content nor sources.

    The body is taken without its trailing newlines, so that the readers
    agree on one text and therefore on one digest: the IR gives a fence body
    that stops at the closing fence, while the HTML of the same fence ends
    with the newline the renderer put before ``</code>``, and a file spliced
    into a fence by ``include=`` ends with its own.
    """
    raw_content = raw_content.rstrip("\n")
    attrs = dict(attributes or {})
    meta_attrs = dict(meta or {})
    caption = coerce_attribute(attrs.get("caption")) or None
    label = coerce_attribute(attrs.get("label")) or None
    figure_width = coerce_attribute(attrs.get("width")) or None
    layout_literal: Any = coerce_attribute(attrs.get("layout")) or None
    config_literal = coerce_attribute(attrs.get("config")) or None

    config_from_file: dict[str, Any] = {}
    if config_literal:
        config_path = Path(config_literal)
        if not config_path.is_absolute():
            if host_path is None:
                raise InvalidNodeError("Relative snippet configuration requires a host document.")
            config_path = (host_path.parent / config_path).resolve()
        try:
            config_payload = config_path.read_text(encoding="utf-8")
        except OSError as exc:
            raise InvalidNodeError(
                f"Unable to read snippet configuration '{config_path}': {exc}"
            ) from exc
        config_from_file = _load_yaml_mapping(config_payload)

    config_from_body: dict[str, Any] = {}
    inline_content: str | None = None
    if language in {"yaml", "yml"}:
        config_from_body = _load_yaml_mapping(raw_content)
    else:
        metadata, body = split_front_matter(raw_content)
        config_from_body = dict(metadata or {})
        if body.strip():
            inline_content = body
        if not config_from_body and inline_content is not None:
            # Fallback: accept pure-YAML snippet bodies even when the language class is missing.
            try:
                parsed_yaml = _load_yaml_mapping(raw_content)
            except InvalidNodeError:
                parsed_yaml = None
            if isinstance(parsed_yaml, dict) and parsed_yaml:
                config_from_body = parsed_yaml
                inline_content = None

    merged_config: dict[str, Any] = {**config_from_file, **config_from_body}
    figure_width = (
        coerce_attribute(merged_config.pop("width", figure_width))
        or coerce_attribute(meta_attrs.get("width"))
        or figure_width
    )
    caption = coerce_attribute(merged_config.pop("caption", caption)) or caption
    label = coerce_attribute(merged_config.pop("label", label)) or label
    layout_literal = merged_config.pop("layout", layout_literal) or layout_literal
    template_id_raw = merged_config.pop("template", None)
    template_id = coerce_attribute(template_id_raw) or None
    cwd_value = merged_config.pop("cwd", None)
    drop_title_value = _coerce_bool_option(merged_config.pop("drop_title", False), False)
    promote_title_value = _coerce_bool_option(
        merged_config.pop("promote_title", None),
        True,
    )
    suppress_title_value = _coerce_bool_option(
        merged_config.pop("suppress_title_metadata", merged_config.pop("suppress_title", None)),
        False,
    )

    base_dir = _resolve_base_dir_value(cwd_value, host_path)
    sources = _resolve_sources(merged_config.pop("sources", None), base_dir)
    bibliography_files = [
        path for path in sources if path.suffix.lower() in {".bib", ".bibtex", ".ris"}
    ]
    if inline_content is None and not sources:
        return None

    fragments = merged_config.pop("fragments", None)
    press_overrides = merged_config.pop("press", None)
    press_template: str | None = None
    template_overrides: dict[str, Any] = dict(merged_config)
    if press_overrides is not None:
        if not isinstance(press_overrides, Mapping):
            raise InvalidNodeError("The 'press' section must be a mapping.")
        press_payload = dict(press_overrides)
        press_template = coerce_attribute(press_payload.pop("template", None)) or None
        template_overrides["press"] = press_payload
    _merge_press_section(template_overrides, fragments)
    template_overrides.setdefault("glossary_inline", True)

    document_front_matter = (
        _document_front_matter(merged_config, press_overrides) if inline_content is not None else {}
    )

    layout = _resolve_layout_value(layout_literal)
    preview_dogear = _frame_dogear_enabled(template_overrides)
    if template_id is None and press_template:
        template_id = press_template
    if inline_content is not None and not sources and template_id is None:
        template_id = "snippet"
        preview_dogear = True
    elif inline_content is None and sources and template_id is None:
        template_id = "article"
    digest = _hash_payload(
        inline_content or "",
        template_overrides,
        cwd=str(base_dir) if base_dir else None,
        template_id=template_id,
        layout=layout,
        sources=sources,
        promote_title=promote_title_value,
        drop_title=drop_title_value,
        suppress_title=suppress_title_value,
        transparent_corner=preview_dogear,
        front_matter=document_front_matter,
    )

    return SnippetBlock(
        content=inline_content,
        front_matter=document_front_matter,
        sources=sources,
        layout=layout,
        preview_dogear=preview_dogear,
        template_id=template_id,
        cwd=base_dir,
        caption=caption,
        label=label,
        figure_width=figure_width,
        template_overrides=template_overrides,
        digest=digest,
        bibliography_files=bibliography_files,
        promote_title=promote_title_value,
        drop_title=drop_title_value,
        suppress_title_metadata=suppress_title_value,
    )

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
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
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"

    active_emitter = ensure_emitter(emitter)
    documents: list[Document] = []
    inline_document = _build_document(
        block, host_dir=host_dir, host_name=host_name, emitter=active_emitter
    )
    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,
                emitter=active_emitter,
            )
        )

    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
    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,
        )
        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,
    )

    _store_in_caches()
    return assets

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
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
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