diff --git a/myst_nb/core/read.py b/myst_nb/core/read.py index 2b3dae4b..1d8e819c 100644 --- a/myst_nb/core/read.py +++ b/myst_nb/core/read.py @@ -31,6 +31,8 @@ class NbReader: """The configuration for parsing markdown cells.""" read_fmt: dict | None = dc.field(default=None) """The type of the reader, if known.""" + support_cell_ids: bool = False + """Whether the format supports stable cell IDs""" def standard_nb_read(text: str) -> nbf.NotebookNode: @@ -75,7 +77,11 @@ def create_nb_reader( if commonmark_only: # Markdown cells should be read as Markdown only md_config = dc.replace(md_config, commonmark_only=True) - return NbReader(partial(reader, **(reader_kwargs or {})), md_config) # type: ignore + return NbReader( + partial(reader, **(reader_kwargs or {})), + md_config, + support_cell_ids=suffix == ".ipynb", + ) # type: ignore # a Markdown file is a special case, since we only treat it as a notebook, # if it starts with certain "top-matter" @@ -89,6 +95,7 @@ def create_nb_reader( ), md_config, {"type": "plugin", "name": "myst_nb_md"}, + support_cell_ids=False, ) # if we get here, we did not find a reader diff --git a/myst_nb/core/render.py b/myst_nb/core/render.py index 0110d3dc..084f6a34 100644 --- a/myst_nb/core/render.py +++ b/myst_nb/core/render.py @@ -182,7 +182,7 @@ def render_nb_cell_code(self: SelfType, token: SyntaxTreeNode) -> None: ) cell_id = token.meta["id"] - if cell_id: + if cell_id and not cell_id.startswith("RANDOM_CELL_ID"): self.document.note_implicit_target(cell_container, cell_container) slug = "cell-id=" + cell_id cell_container["slug"] = slug diff --git a/myst_nb/sphinx_.py b/myst_nb/sphinx_.py index dba36531..344a7779 100644 --- a/myst_nb/sphinx_.py +++ b/myst_nb/sphinx_.py @@ -87,6 +87,12 @@ def parse(self, inputstring: str, document: nodes.document) -> None: return super().parse(inputstring, document) notebook = nb_reader.read(inputstring) + if not nb_reader.support_cell_ids: + # mark randomly generated cell IDs + for cell in notebook["cells"]: + if "id" in cell: + cell["id"] = "RANDOM_CELL_ID_" + cell["id"] + # update the global markdown config with the file-level config warning = lambda wtype, msg: create_warning( # noqa: E731 document, msg, line=1, append_to=document, subtype=wtype