Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Add :only: option for code cells #629

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
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
24 changes: 24 additions & 0 deletions docs/computation/execute.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,27 @@ which produces:

```{nb-exec-table}
```

(execute/builder-dep)=
## Builder-dependent execution

```{warning}
This is an experimental feature that is **not** part of the core `MyST` markup specification, and may be removed in the future. Using `:only:` may also not work well with caching and may require deleting previously built files when switching builders.
```

It may be desirable to execute different code depending on the Sphinx builder being used.
For example, one may want to have different setup code for plots to be displayed in a website compared to those in a PDF file obtained via LaTeX.
One can use the `only` option in situations like these, like in the following example:

````md
```{code-cell}
:only: html
import matplotlib.pyplot as plt
plt.style.use('ggplot')
```

```{code-cell}
:only: latex
plt.style.use('fivethirtyeight')
```
````
12 changes: 9 additions & 3 deletions myst_nb/core/read.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Module for reading notebook formats from a string input."""

from __future__ import annotations

import dataclasses as dc
Expand Down Expand Up @@ -86,6 +87,7 @@ def create_nb_reader(
config=md_config,
add_source_map=True,
path=path,
builder=nb_config.builder_name,
),
md_config,
{"type": "plugin", "name": "myst_nb_md"},
Expand Down Expand Up @@ -176,6 +178,7 @@ def read_myst_markdown_notebook(
raw_directive="{raw-cell}",
add_source_map=False,
path: str | Path | None = None,
builder: str = "",
) -> nbf.NotebookNode:
"""Convert text written in the myst format to a notebook.

Expand Down Expand Up @@ -260,9 +263,12 @@ def _flush_markdown(start_line, token, md_metadata):
)
meta = nbf.from_dict(options)
source_map.append(token_map[0] + 1)
notebook.cells.append(
nbf_version.new_code_cell(source="\n".join(body_lines), metadata=meta)
)
if "only" not in options or options["only"] == builder:
notebook.cells.append(
nbf_version.new_code_cell(
source="\n".join(body_lines), metadata=meta
)
)
md_metadata = {}
md_start_line = token_map[1]

Expand Down
2 changes: 2 additions & 0 deletions myst_nb/sphinx_.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""The sphinx parser implementation for myst-nb."""

from __future__ import annotations

from collections import defaultdict
Expand Down Expand Up @@ -80,6 +81,7 @@ def parse(self, inputstring: str, document: nodes.document) -> None:

# get notebook rendering configuration
nb_config: NbParserConfig = self.env.mystnb_config
nb_config.builder_name = self.env.app.builder.name

# create a reader for the notebook
nb_reader = create_nb_reader(document_path, md_config, nb_config, inputstring)
Expand Down
8 changes: 8 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,14 @@ def get_html(self, index=0):
pytest.fail("html not output")
return bs4.BeautifulSoup(_path.read_text(), "html.parser")

def get_latex(self, index=0):
"""Return the built LaTeX file."""
name = self.files[index][0]
_path = self.app.outdir / (name + ".tex")
if not _path.exists():
pytest.fail("tex not output")
return _path.read_text(encoding="utf-8")

def get_nb(self, index=0):
"""Return the output notebook (after any execution)."""
name = self.files[index][0]
Expand Down
24 changes: 24 additions & 0 deletions tests/notebooks/with_only.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
jupytext:
text_representation:
extension: .md
format_name: myst
format_version: '0.8'
jupytext_version: 1.4.1+dev
kernelspec:
display_name: Python 3
language: python
name: python3
---

# Test the `:only:` option

```{code-cell}
:only: html
1+1
```

```{code-cell}
:only: latex
2+2
```
50 changes: 50 additions & 0 deletions tests/test_execute.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Test sphinx builds which execute notebooks."""

import os
from pathlib import Path

Expand Down Expand Up @@ -327,6 +328,55 @@ def test_nb_exec_table(sphinx_run, file_regression):
assert any("nb_exec_table" in row.text for row in rows)


@pytest.mark.sphinx_params(
"with_only.md", conf={"nb_execution_mode": "auto"}, buildername="html"
)
def test_only_html(sphinx_run, file_regression):
"""Test that the table gets output into the HTML,
including a row for the executed notebook.
"""
sphinx_run.build()
# print(sphinx_run.status())
assert not sphinx_run.warnings()
file_regression.check(
sphinx_run.get_doctree().pformat(), extension=".xml", encoding="utf-8"
)
# print(sphinx_run.get_html())
output = sphinx_run.get_html().select("div.output div.highlight pre")
assert len(output) == 1 # check that other cell is not present
assert "2" in output[0].text # check value to ensure correct cell is present


@pytest.mark.sphinx_params(
"with_only.md",
conf={
"nb_execution_mode": "auto",
"latex_documents": [('with_only', 'with_only.tex', "project", "author", 'manual')]
},
buildername="latex"
)
def test_only_latex(sphinx_run, file_regression):
"""Test that the table gets output into the HTML,
including a row for the executed notebook.
"""
sphinx_run.build()
# print(sphinx_run.status())
assert not sphinx_run.warnings()
file_regression.check(
sphinx_run.get_doctree().pformat(), extension=".xml", encoding="utf-8"
)
# print(sphinx_run.get_html())
output = sphinx_run.get_latex()
correct = (
r"\begin{sphinxVerbatim}[commandchars=\\\{\}]" "\n4\n" r"\end{sphinxVerbatim}"
)
assert correct in output # check value to ensure correct cell is present
wrong = (
r"\begin{sphinxVerbatim}[commandchars=\\\{\}]" "\n2\n" r"\end{sphinxVerbatim}"
)
assert wrong not in output # check value to ensure other cell is not present


@pytest.mark.sphinx_params(
"custom-formats.Rmd",
conf={
Expand Down
16 changes: 16 additions & 0 deletions tests/test_execute/test_only_html.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<document source="with_only">
<section ids="test-the-only-option" names="test\ the\ :only:\ option">
<title>
Test the
<literal>
:only:
option
<container cell_index="1" cell_metadata="{'only': 'html'}" classes="cell" exec_count="1" nb_element="cell_code">
<container classes="cell_input" nb_element="cell_code_source">
<literal_block language="ipython3" xml:space="preserve">
1+1
<container classes="cell_output" nb_element="cell_code_output">
<container nb_element="mime_bundle">
<container mime_type="text/plain">
<literal_block classes="output text_plain" language="myst-ansi" xml:space="preserve">
2
16 changes: 16 additions & 0 deletions tests/test_execute/test_only_latex.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<document source="with_only">
<section ids="test-the-only-option" names="test\ the\ :only:\ option">
<title>
Test the
<literal>
:only:
option
<container cell_index="1" cell_metadata="{'only': 'latex'}" classes="cell" exec_count="1" nb_element="cell_code">
<container classes="cell_input" nb_element="cell_code_source">
<literal_block language="ipython3" xml:space="preserve">
2+2
<container classes="cell_output" nb_element="cell_code_output">
<container nb_element="mime_bundle">
<container mime_type="text/plain">
<literal_block classes="output text_plain" language="myst-ansi" xml:space="preserve">
4