Skip to content

Commit

Permalink
Merge branch 'master' into patch-2
Browse files Browse the repository at this point in the history
  • Loading branch information
agoose77 authored Nov 13, 2022
2 parents 1a7d0a0 + 91b5ecc commit 9c9a13e
Show file tree
Hide file tree
Showing 29 changed files with 1,232 additions and 182 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
- name: Set up Python 3.8
uses: actions/setup-python@v1
with:
python-version: 3.8
python-version: 3.9
- uses: pre-commit/[email protected]

tests:
Expand Down
10 changes: 5 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ exclude: >
repos:

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.2.0
rev: v4.3.0
hooks:
- id: check-json
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace

- repo: https://github.com/asottile/pyupgrade
rev: v2.32.1
rev: v2.38.2
hooks:
- id: pyupgrade
args: [--py37-plus]
Expand All @@ -31,18 +31,18 @@ repos:
- id: isort

- repo: https://github.com/psf/black
rev: 22.3.0
rev: 22.8.0
hooks:
- id: black

- repo: https://github.com/PyCQA/flake8
rev: 4.0.1
rev: 5.0.4
hooks:
- id: flake8
additional_dependencies: [flake8-bugbear]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.960
rev: v0.981
hooks:
- id: mypy
args: [--config-file=pyproject.toml]
Expand Down
27 changes: 27 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
# Change Log

## v0.17.1 - 2022-30-09

[Full changelog](https://github.com/executablebooks/MyST-NB/compare/v0.17.0...v0.17.1)

- 👌 IMPROVE: `hide-output` button (#450)
This now uses the same margin color as the cell source and, when the cell source is present, is "connected" to that, to form a single element.
See [Hide cell contents](docs/render/hiding.md) for more information.

## v0.17.0 - 2022-29-09

[Full changelog](https://github.com/executablebooks/MyST-NB/compare/v0.16.0...v0.17.0)

- 👌 IMPROVE: Replace sphinx-togglebutton with built-in functionality (#446)
This allows for tighter integration with myst-nb:

- Nicer rendering of the hidden content buttons
- Customisation of the hide/show prompts

See [Hide cell contents](docs/render/hiding.md) for more information.

- 🐛 FIX: Inline exec variables with multiple outputs (#440)
Previously, it was assumed that a variable evaluation would only ever create 0 or 1 outputs.
Multiple are now allowed.

- 👌 IMPROVE: cache bust changes to CSS (#447)
- 👌 IMPROVE: Move CSS colors to variables (#448)

## v0.16.0 - 2022-06-13

[Full changelog](https://github.com/executablebooks/MyST-NB/compare/v0.15.0...v0.16.0)
Expand Down
55 changes: 47 additions & 8 deletions docs/render/hiding.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ kernelspec:
# Hide cell contents

You can use Jupyter Notebook **cell tags** to control some of the behavior of
the rendered notebook. This uses the [**`sphinx-togglebutton`**](https://sphinx-togglebutton.readthedocs.io/en/latest/)
package to add a little button that toggles the visibility of content.[^download]
the rendered notebook.[^download]

[^download]: This notebook can be downloaded as
**{nb-download}`hiding.ipynb`** and {download}`hiding.md`
Expand All @@ -35,8 +34,7 @@ import numpy as np
data = np.random.rand(2, 100) * 100
```

Here is a cell with a `hide-input` tag. Click the "toggle" button to the
right to show it.
Here is a cell with a `hide-input` tag.

```{code-cell} ipython3
:tags: [hide-input]
Expand All @@ -56,7 +54,17 @@ fig, ax = plt.subplots()
points =ax.scatter(*data, c=data[0], s=data[0])
```

And the following cell has a `hide-cell` tag:
Here's a cell with both `hide-input` and `hide-output` tags:

```{code-cell} ipython3
:tags: [hide-input, hide-output]
# This cell has a hide-output tag
fig, ax = plt.subplots()
points =ax.scatter(*data, c=data[0], s=data[0])
```

Here's a cell with a `hide-cell` tag:

```{code-cell} ipython3
:tags: [hide-cell]
Expand All @@ -66,6 +74,40 @@ fig, ax = plt.subplots()
points =ax.scatter(*data, c=data[0], s=data[0])
```

Finally, a cell with both `remove-input` (see below) and `hide-output` tags:

```{code-cell} ipython3
:tags: [remove-input, hide-output]
fig, ax = plt.subplots()
points = ax.scatter(*data, c=data[0], s=data[0])
```

You can control the hide/show prompts by using the `code_prompt_show` and `code_prompt_hide` configuration options.
The optional `{type}` placeholder will be replaced with `content`, `source`, or `outputs`, depending on the hide tag.
See the {ref}`config/intro` section for more details.

````markdown

```{code-cell} ipython3
:tags: [hide-cell]
:mystnb:
: code_prompt_show: "My show prompt for {type}"
: code_prompt_hide: "My hide prompt for {type}"

print("hallo world")
```
````

```{code-cell} ipython3
:tags: [hide-cell]
:mystnb:
: code_prompt_show: "My show prompt for {type}"
: code_prompt_hide: "My hide prompt for {type}"
print("hallo world")
```

(use/hiding/markdown)=

## Hide markdown cells
Expand Down Expand Up @@ -107,7 +149,6 @@ the page at all.
```{code-cell} ipython3
:tags: [remove-input]
# This cell has a remove-input tag
fig, ax = plt.subplots()
points =ax.scatter(*data, c=data[0], s=data[0])
```
Expand All @@ -117,7 +158,6 @@ Here's a cell with a `remove-output` tag:
```{code-cell} ipython3
:tags: [remove-output]
# This cell has a remove-output tag
fig, ax = plt.subplots()
points = ax.scatter(*data, c=data[0], s=data[0])
```
Expand All @@ -128,7 +168,6 @@ below, since the cell will be gone).
```{code-cell} ipython3
:tags: [remove-cell]
# This cell has a remove-cell tag
fig, ax = plt.subplots()
points = ax.scatter(*data, c=data[0], s=data[0])
```
2 changes: 1 addition & 1 deletion myst_nb/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""A docutils/sphinx parser for Jupyter Notebooks."""
__version__ = "0.16.0"
__version__ = "0.17.1"


def setup(app):
Expand Down
29 changes: 29 additions & 0 deletions myst_nb/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,35 @@ def __post_init__(self):
),
},
)

code_prompt_show: str = dc.field(
default="Show code cell {type}",
metadata={
"validator": instance_of(str),
"help": "Prompt to expand hidden code cell {content|source|outputs}",
"sections": (
Section.global_lvl,
Section.file_lvl,
Section.cell_lvl,
Section.render,
),
},
)

code_prompt_hide: str = dc.field(
default="Hide code cell {type}",
metadata={
"validator": instance_of(str),
"help": "Prompt to collapse hidden code cell {content|source|outputs}",
"sections": (
Section.global_lvl,
Section.file_lvl,
Section.cell_lvl,
Section.render,
),
},
)

number_source_lines: bool = dc.field(
default=False,
metadata={
Expand Down
4 changes: 2 additions & 2 deletions myst_nb/core/execute/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,13 @@ def code_cell_outputs(
cell = cells[cell_index]
return cell.get("execution_count", None), cell.get("outputs", [])

def eval_variable(self, name: str) -> NotebookNode | None:
def eval_variable(self, name: str) -> list[NotebookNode]:
"""Retrieve the value of a variable from the kernel.
:param name: the name of the variable,
must match the regex `[a-zA-Z][a-zA-Z0-9_]*`
:returns: a code cell output
:returns: code cell outputs
:raises NotImplementedError: if the execution mode does not support this feature
"""
raise NotImplementedError
7 changes: 3 additions & 4 deletions myst_nb/core/execute/inline.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,12 @@ def code_cell_outputs(
cell = cells[cell_index]
return cell.get("execution_count", None), cell.get("outputs", [])

def eval_variable(self, name: str) -> NotebookNode | None:
def eval_variable(self, name: str) -> list[NotebookNode]:
return self._client.eval_expression(name)


class ModifiedNotebookClient(NotebookClient):
async def async_eval_expression(self, name: str) -> NotebookNode | None:
async def async_eval_expression(self, name: str) -> list[NotebookNode]:
"""Evaluate an expression in the kernel.
This is a modified version of `async_execute_cell`,
Expand Down Expand Up @@ -202,7 +202,6 @@ async def async_eval_expression(self, name: str) -> NotebookNode | None:
task_poll_output_msg.cancel()
finally:
raise

return cell.outputs[0] if cell.outputs else None
return cell.outputs

eval_expression = run_sync(async_eval_expression)
3 changes: 2 additions & 1 deletion myst_nb/core/loggers.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ def process(self, msg, kwargs):
for keyword in self.KEYWORDS:
if keyword in kwargs:
kwargs["extra"][keyword] = kwargs.pop(keyword)
return f"{msg} [{self.extra['type']}{subtype}]", kwargs
etype = "" if not self.extra else self.extra.get("type", "")
return f"{msg} [{etype}{subtype}]", kwargs


class DocutilsLogHandler(logging.Handler):
Expand Down
40 changes: 31 additions & 9 deletions myst_nb/core/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,38 +128,49 @@ def render_nb_cell_raw(self: SelfType, token: SyntaxTreeNode) -> None:
def render_nb_cell_code(self: SelfType, token: SyntaxTreeNode) -> None:
"""Render a notebook code cell."""
cell_index = token.meta["index"]
cell_line = token_line(token, 0) or None
tags = token.meta["metadata"].get("tags", [])

exec_count, outputs = self._get_nb_code_cell_outputs(token)

classes = ["cell"]
for tag in tags:
classes.append(f"tag_{tag.replace(' ', '_')}")

# TODO do we need this -/_ duplication of tag names, or can we deprecate one?
hide_cell = "hide-cell" in tags
remove_input = (
self.get_cell_level_config(
"remove_code_source",
token.meta["metadata"],
line=token_line(token, 0) or None,
"remove_code_source", token.meta["metadata"], line=cell_line
)
or ("remove_input" in tags)
or ("remove-input" in tags)
)
hide_input = "hide-input" in tags
remove_output = (
self.get_cell_level_config(
"remove_code_outputs",
token.meta["metadata"],
line=token_line(token, 0) or None,
"remove_code_outputs", token.meta["metadata"], line=cell_line
)
or ("remove_output" in tags)
or ("remove-output" in tags)
)
hide_output = "hide-output" in tags

# if we are remove both the input and output, we can skip the cell
if remove_input and remove_output:
return

hide_mode = None
if hide_cell:
hide_mode = "all"
elif hide_input and hide_output:
hide_mode = "input+output"
elif hide_input:
hide_mode = "input"
elif hide_output:
hide_mode = "output"

# create a container for all the input/output
classes = ["cell"]
for tag in tags:
classes.append(f"tag_{tag.replace(' ', '_')}")
cell_container = nodes.container(
nb_element="cell_code",
cell_index=cell_index,
Expand All @@ -168,6 +179,17 @@ def render_nb_cell_code(self: SelfType, token: SyntaxTreeNode) -> None:
cell_metadata=token.meta["metadata"],
classes=classes,
)
if hide_mode:
cell_container["hide_mode"] = hide_mode
code_prompt_show = self.get_cell_level_config(
"code_prompt_show", token.meta["metadata"], line=cell_line
)
code_prompt_hide = self.get_cell_level_config(
"code_prompt_hide", token.meta["metadata"], line=cell_line
)
cell_container["prompt_show"] = code_prompt_show
cell_container["prompt_hide"] = code_prompt_hide

self.add_line_and_source_path(cell_container, token)
with self.current_node_context(cell_container, append=True):

Expand Down
Loading

0 comments on commit 9c9a13e

Please sign in to comment.