Skip to content

Instantly share code, notes, and snippets.

@flying-sheep
Last active August 27, 2024 10:58
Show Gist options
  • Save flying-sheep/b1ebbbd85388b4efbdb16201562b563f to your computer and use it in GitHub Desktop.
Save flying-sheep/b1ebbbd85388b4efbdb16201562b563f to your computer and use it in GitHub Desktop.

MyST include reproducer

Run via something like

uv run conf.py

or

pipx run conf.py
#!/usr/bin/env python3
#
# /// script
# dependencies = [
# "sphinx",
# "myst-parser",
# ]
# ///
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
from docutils import nodes
from sphinx.util.docutils import SphinxDirective
from sphinx.util.parsing import nested_parse_to_nodes
if TYPE_CHECKING:
from collections.abc import Sequence
from typing import ClassVar
from sphinx.application import Sphinx
class Test(SphinxDirective):
required_arguments: ClassVar = 1
def run(self) -> Sequence[nodes.Node]:
path = Path(self.arguments[0])
if not path.is_absolute():
src_file = Path(self.get_source_info()[0])
assert src_file.is_file()
path = src_file.parent / self.arguments[0]
return self.render_include(path)
def render_include(self, path: Path) -> list[nodes.Element]:
included = nested_parse_to_nodes(
self.state,
path.read_text(),
source=path.as_posix(),
offset=self.content_offset, # no clue what this is for, 0 also doesn’t work.
)
section = nodes.section(
"",
nodes.title("", nodes.Text(path.name)),
*included,
ids=[path.stem],
)
return [section]
def setup(app: Sphinx) -> None:
app.add_directive("test", Test)
# Config
exclude_patterns = ["inc.md", "_build"]
extensions = [
"myst_parser",
]
if __name__ == "__main__":
import sys
from sphinx.cmd.build import main
sys.exit(main(["-M", "html", ".", "_build", "--fresh-env", "-T"]))

Included

Hi!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment