Skip to content

Commit 48c45c6

Browse files
aleivagcholdgrafpre-commit-ci[bot]agoose77dependabot[bot]
authored
UPGRADE: myst-parser 1.0 (#479)
Co-authored-by: Chris Holdgraf <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Angus Hollands <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Chris Holdgraf <[email protected]> Co-authored-by: Josh Mitchell <[email protected]> Co-authored-by: Michael Aye <[email protected]> Co-authored-by: Jan-Hendrik Müller <[email protected]> Co-authored-by: Oriol Abril-Pla <[email protected]> Co-authored-by: mmcky <[email protected]> Co-authored-by: mmcky <[email protected]>
1 parent 46c58de commit 48c45c6

File tree

15 files changed

+191
-97
lines changed

15 files changed

+191
-97
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ repos:
4848
args: [--config-file=pyproject.toml]
4949
additional_dependencies:
5050
- importlib_metadata
51-
- myst-parser~=0.18.0
51+
- myst-parser~=1.0.0
5252
- "sphinx~=5.0"
5353
- nbclient
5454
- types-PyYAML

CHANGELOG.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ WARNING: 'jupyter_execute_notebooks' is deprecated for 'nb_execution_mode' [myst
9292

9393
`nb_render_priority` has been removed and replaced by `nb_mime_priority_overrides`, which has a different format and is more flexible. See [Outputs MIME priority](docs/render/format_code_cells.md) for more information.
9494

95-
As per the changes in [`myst_parser`](myst:develop/_changelog), the `dollarmath` syntax extension is no longer included by default.
95+
As per the changes in [`myst_parser`](inv:myst#develop/_changelog), the `dollarmath` syntax extension is no longer included by default.
9696
To re-add this extension, ensure that it is specified in your `conf.py`: `myst_enable_extensions = ["dollarmath"]`.
9797

9898
For cell-level configuration the top-level key `render` has now been deprecated for `mystnb`.
@@ -168,7 +168,7 @@ See [Embedding outputs as variables](docs/render/glue.md) for more details.
168168
- `nbconvert`
169169
- Updated:
170170
- `Python`: `3.6+ -> 3.7+`
171-
- `myst_parser`: [`0.15 -> 0.17`](myst:develop/_changelog)
171+
- `myst_parser`: [`0.15 -> 0.17`](inv:myst#develop/_changelog)
172172
- `jupyter-cache`: [`0.4 -> 0.5`](https://github.com/executablebooks/jupyter-cache/blob/master/CHANGELOG.md)
173173
- `sphinx-togglebutton`: [`0.1 -> 0.3`](https://sphinx-togglebutton.readthedocs.io/en/latest/changelog.html)
174174

docs/authoring/custom-formats.Rmd

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ nb_custom_formats = {
2121
```
2222

2323
- The string should be a Python function that will be loaded by `import mylibrary.converter_function`
24-
- The function should take a file's contents (as a `str`) and return an [nbformat.NotebookNode](nbformat:api)
24+
- The function should take a file's contents (as a `str`) and return an [nbformat.NotebookNode](inv:nbformat#api)
2525

2626
If the function takes additional keyword arguments, then you can specify these as dictionary in a second argument.
2727
For example this is what the default conversion would look like:

docs/authoring/jupyter-notebooks.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,13 @@ Sphinx using the MyST parser.[^download]
1616

1717
:::{seealso}
1818
For more information about what you can write with MyST Markdown, see the
19-
[MyST Parser documentation](myst:intro/get-started).
19+
[MyST Parser documentation](inv:myst#intro/get-started).
2020
:::
2121

2222
### Configuration
2323

24-
The MyST-NB parser derives from [the base MyST-Parser](myst:intro/get-started), and so all the same configuration options are available.
25-
See the [MyST configuration options](myst:sphinx/config-options) for the full set of options, and [MyST syntax guide](myst:syntax/core) for all the syntax options.
24+
The MyST-NB parser derives from [the base MyST-Parser](inv:myst#intro/get-started), and so all the same configuration options are available.
25+
See the [MyST configuration options](inv:myst#sphinx/config-options) for the full set of options, and [MyST syntax guide](inv:myst#syntax/core) for all the syntax options.
2626

2727
To build documentation from this notebook, the following options are set:
2828

@@ -38,7 +38,7 @@ myst_url_schemes = ("http", "https", "mailto")
3838
```
3939

4040
:::{note}
41-
Loading the `myst_nb` extension also activates the [`myst_parser`](myst:index) extension, for enabling the MyST flavour of Markdown.
41+
Loading the `myst_nb` extension also activates the [`myst_parser`](inv:myst#index) extension, for enabling the MyST flavour of Markdown.
4242
It is not required to add this explicitly in the list of `extensions`.
4343
:::
4444

@@ -53,7 +53,7 @@ For example, here's the MyST-NB logo:
5353

5454
![myst-nb logo](../_static/logo-wide.svg)
5555

56-
By adding `"html_image"` to the `myst_enable_extensions` list in the sphinx configuration ([see here](myst:syntax/images)), you can even add HTML `img` tags with attributes:
56+
By adding `"html_image"` to the `myst_enable_extensions` list in the sphinx configuration ([see here](inv:myst#syntax/images)), you can even add HTML `img` tags with attributes:
5757

5858
```html
5959
<img src="../_static/logo-wide.svg" alt="logo" width="200px" class="shadow mb-2">
@@ -66,7 +66,7 @@ For example, here's a note admonition block:
6666

6767
:::::{note}
6868
**Wow**, a note!
69-
It was generated with this code ([as explained here](myst:syntax/admonitions)):
69+
It was generated with this code ([as explained here](inv:myst:std:label#syntax/admonitions)):
7070

7171
````md
7272
:::{note}
@@ -77,7 +77,7 @@ It was generated with this code ([as explained here](myst:syntax/admonitions)):
7777
:::::
7878

7979
If you wish to use "bare" LaTeX equations, then you should add `"amsmath"` to the `myst_enable_extensions` list in the sphinx configuration.
80-
This is [explained here](myst:syntax/amsmath), and works as such:
80+
This is [explained here](inv:myst:std:label#syntax/amsmath), and works as such:
8181

8282
```latex
8383
\begin{equation}
@@ -110,7 +110,7 @@ $$e^{i\pi} + 1 = 0$$ (euler)
110110
Euler's identity, equation {math:numref}`euler`, was elected one of the
111111
most beautiful mathematical formulas.
112112

113-
You can see the syntax used for this example [here in the MyST documentation](myst:syntax/math).
113+
You can see the syntax used for this example [here in the MyST documentation](inv:myst:std:label#syntax/math).
114114

115115
## Code cells and outputs
116116

docs/index.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ Build single or collections of documents into multiple formats (HTML, PDF, ...).
8686

8787
MyST-NB is a module within the [Executable Books Project](https://executablebooks.org),
8888
an international collaboration to build open source tools that facilitate publishing computational narratives using the Jupyter ecosystem.
89-
It is also a core component of [Jupyter Book](jb:intro).
89+
It is also a core component of [Jupyter Book](inv:jb#intro).
9090

9191
Check out the [Gallery of Jupyter Books](https://executablebooks.org/en/latest/gallery),
9292
for inspiration from across the community.

myst_nb/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
"""A docutils/sphinx parser for Jupyter Notebooks."""
2-
__version__ = "0.17.2"
2+
__version__ = "0.18.0"
33

44

55
def setup(app):

myst_nb/core/config.py

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Configuration for myst-nb."""
22
import dataclasses as dc
33
from enum import Enum
4+
import sys
45
from typing import Any, Callable, Dict, Iterable, Optional, Sequence, Tuple
56

67
from myst_parser.config.dc_validators import (
@@ -12,7 +13,13 @@
1213
optional,
1314
validate_fields,
1415
)
15-
from typing_extensions import Literal
16+
17+
if sys.version_info >= (3, 8):
18+
from typing import Literal
19+
else:
20+
from typing_extensions import Literal # noqa: F401
21+
22+
from myst_nb.warnings_ import MystNBWarnings
1623

1724

1825
def custom_formats_converter(value: dict) -> Dict[str, Tuple[str, dict, bool]]:
@@ -130,7 +137,7 @@ def __post_init__(self):
130137
default_factory=dict,
131138
metadata={
132139
"help": "Custom formats for reading notebook; suffix -> reader",
133-
"docutils_exclude": True,
140+
"omit": ["docutils"],
134141
"sections": (Section.global_lvl, Section.read),
135142
},
136143
)
@@ -184,7 +191,7 @@ def __post_init__(self):
184191
"validator": deep_mapping(instance_of(str), instance_of(str)),
185192
"help": "Mapping of kernel name regex to replacement kernel name"
186193
"(applied before execution)",
187-
"docutils_exclude": True,
194+
"omit": ["docutils"],
188195
"sections": (Section.global_lvl, Section.execute),
189196
},
190197
)
@@ -228,7 +235,7 @@ def __post_init__(self):
228235
"validator": deep_iterable(instance_of(str)),
229236
"help": "Exclude (POSIX) glob patterns for notebooks",
230237
"legacy_name": "execution_excludepatterns",
231-
"docutils_exclude": True,
238+
"omit": ["docutils"],
232239
"sections": (Section.global_lvl, Section.execute),
233240
},
234241
)
@@ -395,7 +402,7 @@ def __post_init__(self):
395402
"help": "Overrides for the base render priority of mime types: "
396403
"list of (builder name, mime type, priority)",
397404
# TODO how to allow this in docutils?
398-
"docutils_exclude": True,
405+
"omit": ["docutils"],
399406
"sections": (Section.global_lvl, Section.file_lvl, Section.render),
400407
},
401408
repr=False,
@@ -462,7 +469,7 @@ def __post_init__(self):
462469
metadata={
463470
"validator": deep_mapping(instance_of(str), instance_of((str, int))),
464471
"help": "Options for image outputs (class|alt|height|width|scale|align)",
465-
"docutils_exclude": True,
472+
"omit": ["docutils"],
466473
# TODO backward-compatible change to "image_options"?
467474
"cell_key": "image",
468475
"sections": (
@@ -479,7 +486,7 @@ def __post_init__(self):
479486
metadata={
480487
"validator": deep_mapping(instance_of(str), instance_of((str, int))),
481488
"help": "Options for figure outputs (classes|name|caption|caption_before)",
482-
"docutils_exclude": True,
489+
"omit": ["docutils"],
483490
"cell_key": "figure",
484491
"sections": (
485492
Section.global_lvl,
@@ -513,7 +520,7 @@ def __post_init__(self):
513520
instance_of(str), deep_mapping(instance_of(str), instance_of(str))
514521
),
515522
"help": "Javascript to be loaded on pages containing ipywidgets",
516-
"docutils_exclude": True,
523+
"omit": ["docutils"],
517524
"sections": (Section.global_lvl, Section.render),
518525
},
519526
repr=False,
@@ -575,7 +582,7 @@ def get_cell_level_config(
575582
self,
576583
field_name: str,
577584
cell_metadata: Dict[str, Any],
578-
warning_callback: Callable[[str, str], Any],
585+
warning_callback: Callable[[str, MystNBWarnings], Any],
579586
) -> Any:
580587
"""Get a configuration value at the cell level.
581588
@@ -601,7 +608,7 @@ def get_cell_level_config(
601608
warning_callback(
602609
f"Deprecated `cell_metadata_key` 'render' "
603610
f"found, replace with {self.cell_metadata_key!r}",
604-
"cell_metadata_key",
611+
MystNBWarnings.CELL_METADATA_KEY,
605612
)
606613
cell_meta = cell_metadata["render"]
607614
else:
@@ -619,7 +626,10 @@ def get_cell_level_config(
619626
field.metadata["validator"](self, field, value)
620627
return value
621628
except Exception as exc:
622-
warning_callback(f"Cell metadata invalid: {exc}", "cell_config")
629+
warning_callback(
630+
f"Cell metadata invalid: {exc}",
631+
MystNBWarnings.CELL_CONFIG,
632+
)
623633

624634
# default/global/file level should have already been merged
625635
return getattr(self, field.name)

myst_nb/core/read.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -312,25 +312,22 @@ class _MockDirective:
312312

313313

314314
def _read_fenced_cell(token, cell_index, cell_type):
315-
from myst_parser.parsers.directives import (
316-
DirectiveParsingError,
317-
parse_directive_text,
318-
)
315+
from myst_parser.parsers.directives import parse_directive_text
319316

320-
try:
321-
_, options, body_lines, _ = parse_directive_text(
322-
directive_class=_MockDirective,
323-
first_line="",
324-
content=token.content,
325-
validate_options=False,
326-
)
327-
except DirectiveParsingError as err:
317+
result = parse_directive_text(
318+
directive_class=_MockDirective,
319+
first_line="",
320+
content=token.content,
321+
validate_options=False,
322+
)
323+
if result.warnings:
328324
raise MystMetadataParsingError(
329325
"{} cell {} at line {} could not be read: {}".format(
330-
cell_type, cell_index, token.map[0] + 1, err
326+
cell_type, cell_index, token.map[0] + 1, result.warnings[0]
331327
)
332328
)
333-
return options, body_lines
329+
330+
return result.options, result.body
334331

335332

336333
def _read_cell_metadata(token, cell_index):

myst_nb/core/render.py

Lines changed: 15 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,9 @@
2828

2929
from myst_nb.core.config import NbParserConfig
3030
from myst_nb.core.execute import NotebookClientBase
31-
from myst_nb.core.loggers import DEFAULT_LOG_TYPE, LoggerType
31+
from myst_nb.core.loggers import LoggerType # DEFAULT_LOG_TYPE,
3232
from myst_nb.core.utils import coalesce_streams
33+
from myst_nb.warnings_ import MystNBWarnings, create_warning
3334

3435
if TYPE_CHECKING:
3536
from markdown_it.tree import SyntaxTreeNode
@@ -57,7 +58,6 @@ class MditRenderMixin:
5758
# required by mypy
5859
md_options: dict[str, Any]
5960
document: nodes.document
60-
create_warning: Any
6161
render_children: Any
6262
add_line_and_source_path: Any
6363
add_line_and_source_path_r: Any
@@ -95,8 +95,8 @@ def get_cell_level_config(
9595
:param cell_metadata: the metadata for the cell
9696
"""
9797

98-
def _callback(msg: str, subtype: str):
99-
self.create_warning(msg, line=line, subtype=subtype)
98+
def _callback(msg: str, subtype: MystNBWarnings):
99+
create_warning(self.document, msg, line=line, subtype=subtype)
100100

101101
return self.nb_config.get_cell_level_config(field, cell_metadata, _callback)
102102

@@ -222,10 +222,11 @@ def _get_nb_source_code_lexer(
222222
# TODO this will create a warning for every cell, but perhaps
223223
# it should only be a single warning for the notebook (as previously)
224224
# TODO allow user to set default lexer?
225-
self.create_warning(
225+
create_warning(
226+
self.document,
226227
f"No source code lexer found for notebook cell {cell_index + 1}",
227-
wtype=DEFAULT_LOG_TYPE,
228-
subtype="lexer",
228+
# wtype=DEFAULT_LOG_TYPE,
229+
subtype=MystNBWarnings.LEXER,
229230
line=line,
230231
append_to=self.current_node,
231232
)
@@ -310,11 +311,6 @@ class MimeData:
310311
"""Index of the output in the cell"""
311312
line: int | None = None
312313
"""Source line of the cell"""
313-
md_headings: bool = False
314-
"""Whether to render headings in text/markdown blocks."""
315-
# we can only do this if know the content will be rendered into the main body
316-
# of the document, e.g. not inside a container node
317-
# (otherwise it will break the structure of the AST)
318314

319315
@property
320316
def string(self) -> str:
@@ -598,9 +594,7 @@ def render_markdown(self, data: MimeData) -> list[nodes.Element]:
598594
fmt = self.renderer.get_cell_level_config(
599595
"render_markdown_format", data.cell_metadata, line=data.line
600596
)
601-
return self._render_markdown_base(
602-
data, fmt=fmt, inline=False, allow_headings=data.md_headings
603-
)
597+
return self._render_markdown_base(data, fmt=fmt, inline=False)
604598

605599
def render_text_plain(self, data: MimeData) -> list[nodes.Element]:
606600
"""Render a notebook text/plain mime data output."""
@@ -753,9 +747,7 @@ def render_markdown_inline(self, data: MimeData) -> list[nodes.Element]:
753747
fmt = self.renderer.get_cell_level_config(
754748
"render_markdown_format", data.cell_metadata, line=data.line
755749
)
756-
return self._render_markdown_base(
757-
data, fmt=fmt, inline=True, allow_headings=data.md_headings
758-
)
750+
return self._render_markdown_base(data, fmt=fmt, inline=True)
759751

760752
def render_text_plain_inline(self, data: MimeData) -> list[nodes.Element]:
761753
"""Render a notebook text/plain mime data output."""
@@ -796,7 +788,7 @@ def render_widget_view_inline(self, data: MimeData) -> list[nodes.Element]:
796788
return self.render_widget_view(data)
797789

798790
def _render_markdown_base(
799-
self, data: MimeData, *, fmt: str, inline: bool, allow_headings: bool
791+
self, data: MimeData, *, fmt: str, inline: bool
800792
) -> list[nodes.Element]:
801793
"""Base render for a notebook markdown mime output (block or inline)."""
802794
psuedo_element = nodes.Element() # element to hold the parsed markdown
@@ -832,7 +824,6 @@ def _render_markdown_base(
832824
data.string,
833825
data.line or 0,
834826
inline=inline,
835-
allow_headings=allow_headings,
836827
)
837828
finally:
838829
# restore the parser
@@ -986,11 +977,12 @@ def create_figure_context(
986977
caption.source = self.document["source"]
987978
caption.line = line
988979
elif not (isinstance(first_node, nodes.comment) and len(first_node) == 0):
989-
self.create_warning(
980+
create_warning(
981+
self.document,
990982
"Figure caption must be a paragraph or empty comment.",
991983
line=line,
992-
wtype=DEFAULT_LOG_TYPE,
993-
subtype="fig_caption",
984+
# wtype=DEFAULT_LOG_TYPE,
985+
subtype=MystNBWarnings.FIG_CAPTION,
994986
)
995987

996988
self.current_node.append(figure_node)

0 commit comments

Comments
 (0)