Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions myst_nb/core/read.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from pathlib import Path
from typing import Callable, Iterator

from docutils import nodes
from docutils.parsers.rst import Directive
from markdown_it.renderer import RendererHTML
from myst_parser.config.main import MdParserConfig
Expand Down Expand Up @@ -382,10 +383,9 @@ class UnexpectedCellDirective(Directive):
which are picked up by the MyST Markdown reader to convert them into notebooks.

If any are left in the parsed Markdown, it probably means that they were nested
inside another directive, which is not allowed.

Therefore, we log a warning if it is triggered, and discard it.
inside another directive, so they cannot be converted into notebook cells.

Therefore, we log a warning and fall back to rendering the source as a code block.
"""

optional_arguments = 1
Expand All @@ -408,4 +408,8 @@ def run(self):
else:
logger = DocutilsDocLogger(document) # type: ignore
logger.warning(message, line=self.lineno, subtype="nbcell")
return []
source = "\n".join(self.content)
node = nodes.literal_block(source, source)
if self.arguments:
node["language"] = self.arguments[0]
return [node]
23 changes: 23 additions & 0 deletions tests/notebooks/nested_code_cell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
file_format: mystnb
kernelspec:
display_name: Python 3
language: python
name: python3
---

# Nested code cells

## Control: standalone code cell (should render)

```{code-cell} python
print("hello from standalone cell")
```

## Reproducer: code cell nested in another directive (should still render source)

````{note}
```{code-cell} python
print("hello from nested cell")
```
````
14 changes: 14 additions & 0 deletions tests/test_text_based.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,17 @@ def test_basic_nometadata(sphinx_run):
sphinx_run.build()
# print(sphinx_run.status())
assert "Found an unexpected `code-cell`" in sphinx_run.warnings()


@pytest.mark.sphinx_params(
"nested_code_cell.md",
conf={"nb_execution_mode": "off", "source_suffix": {".md": "myst-nb"}},
)
def test_nested_code_cell_renders_source(sphinx_run):
"""Nested code-cell directives cannot become notebook cells, but source must show."""
sphinx_run.build()
assert "Found an unexpected `code-cell`" in sphinx_run.warnings()
html = sphinx_run.get_html()
sources = [block.get_text() for block in html.find_all("div", class_="highlight")]
assert any("hello from standalone cell" in s for s in sources)
assert any("hello from nested cell" in s for s in sources)