-
Notifications
You must be signed in to change notification settings - Fork 576
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
feat: add NumberedHeadingsPreprocessor #2187
Open
sapristi
wants to merge
5
commits into
jupyter:main
Choose a base branch
from
sapristi:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+177
−0
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
490bb79
feat: add NumberedHeadingsPreprocessor
cf5b6e8
Merge branch 'main' into main
krassowski eda0794
Merge branch 'main' into main
krassowski 2141870
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 232d78c
use mistune for numbered headings
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
""" | ||
Preprocessor that transforms markdown cells: Insert numbering in from of heading | ||
""" | ||
|
||
from nbconvert.preprocessors.base import Preprocessor | ||
|
||
try: # for Mistune >= 3.0 | ||
import mistune | ||
from mistune.core import BlockState | ||
from mistune.renderers.markdown import MarkdownRenderer | ||
|
||
MISTUNE_V3 = True | ||
except ImportError: # for Mistune >= 2.0 | ||
MISTUNE_V3 = False | ||
|
||
WRONG_MISTUNE_VERSION_ERROR = "Error: NumberedHeadingsPreprocessor requires mistune >= 3" | ||
|
||
|
||
class NumberedHeadingsPreprocessor(Preprocessor): | ||
"""Pre-processor that will rewrite markdown headings to include numberings.""" | ||
|
||
def __init__(self, *args, **kwargs): | ||
"""Init""" | ||
super().__init__(*args, **kwargs) | ||
if not MISTUNE_V3: | ||
raise Exception(WRONG_MISTUNE_VERSION_ERROR) | ||
self.md_parser = mistune.create_markdown(renderer=None) | ||
self.md_renderer = MarkdownRenderer() | ||
self.current_numbering = [0] | ||
|
||
def format_numbering(self): | ||
"""Return a string representation of the current numbering""" | ||
return ".".join(str(n) for n in self.current_numbering) | ||
|
||
def _inc_current_numbering(self, level): | ||
"""Increase internal counter keeping track of numberings""" | ||
if level > len(self.current_numbering): | ||
self.current_numbering = self.current_numbering + [0] * ( | ||
level - len(self.current_numbering) | ||
) | ||
elif level < len(self.current_numbering): | ||
self.current_numbering = self.current_numbering[:level] | ||
self.current_numbering[level - 1] += 1 | ||
|
||
def preprocess_cell(self, cell, resources, index): | ||
"""Rewrites all the headings in the cell if it is markdown""" | ||
if cell["cell_type"] != "markdown": | ||
return cell, resources | ||
try: | ||
md_ast = self.md_parser(cell["source"]) | ||
assert not isinstance(md_ast, str) # type guard ; str is not returned by ast parser | ||
for element in md_ast: | ||
if element["type"] == "heading": | ||
level = element["attrs"]["level"] | ||
self._inc_current_numbering(level) | ||
if len(element["children"]) > 0: | ||
child = element["children"][0] | ||
if child["type"] == "text": | ||
child["raw"] = self.format_numbering() + " " + child["raw"] | ||
new_source = self.md_renderer(md_ast, BlockState()) | ||
cell["source"] = new_source | ||
return cell, resources | ||
except Exception: | ||
self.log.warning("Failed processing cell headings", exc_info=True) | ||
return cell, resources |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
""" | ||
Module with tests for the Numbered Headings preprocessor. | ||
""" | ||
|
||
from nbformat import v4 as nbformat | ||
|
||
from nbconvert.preprocessors.numbered_headings import NumberedHeadingsPreprocessor | ||
|
||
from .base import PreprocessorTestsBase | ||
|
||
MARKDOWN_1 = """ | ||
# Heading 1 | ||
|
||
## Sub-heading | ||
|
||
some content | ||
""" | ||
|
||
MARKDOWN_1_POST = """ | ||
# 1 Heading 1 | ||
|
||
## 1.1 Sub-heading | ||
|
||
some content | ||
""" | ||
|
||
|
||
MARKDOWN_2 = """ | ||
|
||
## Second sub-heading | ||
|
||
# Another main heading | ||
|
||
## Sub-heading | ||
|
||
|
||
some more content | ||
|
||
### Third heading | ||
""" | ||
|
||
MARKDOWN_2_POST = """ | ||
|
||
## 1.2 Second sub-heading | ||
|
||
# 2 Another main heading | ||
|
||
## 2.1 Sub-heading | ||
|
||
some more content | ||
|
||
### 2.1.1 Third heading | ||
""" | ||
|
||
MARKDOWN_3 = """ | ||
# HEADING | ||
|
||
``` | ||
# this is not a heading | ||
|
||
## this neither | ||
``` | ||
""" | ||
|
||
MARKDOWN_3_POST = """ | ||
# 3 HEADING | ||
|
||
``` | ||
# this is not a heading | ||
|
||
## this neither | ||
``` | ||
""" | ||
|
||
|
||
class TestNumberedHeadings(PreprocessorTestsBase): | ||
def build_notebook(self): | ||
cells = [ | ||
nbformat.new_code_cell(source="$ e $", execution_count=1), | ||
nbformat.new_markdown_cell(source=MARKDOWN_1), | ||
nbformat.new_code_cell(source="$ e $", execution_count=1), | ||
nbformat.new_markdown_cell(source=MARKDOWN_2), | ||
nbformat.new_markdown_cell(source=MARKDOWN_3), | ||
] | ||
|
||
return nbformat.new_notebook(cells=cells) | ||
|
||
def build_preprocessor(self): | ||
"""Make an instance of a preprocessor""" | ||
preprocessor = NumberedHeadingsPreprocessor() | ||
preprocessor.enabled = True | ||
return preprocessor | ||
|
||
def test_constructor(self): | ||
"""Can a NumberedHeadingsPreprocessor be constructed?""" | ||
self.build_preprocessor() | ||
|
||
def test_output(self): | ||
"""Test the output of the NumberedHeadingsPreprocessor""" | ||
nb = self.build_notebook() | ||
res = self.build_resources() | ||
preprocessor = self.build_preprocessor() | ||
nb, res = preprocessor(nb, res) | ||
assert nb.cells[1].source.strip() == MARKDOWN_1_POST.strip() | ||
assert nb.cells[3].source.strip() == MARKDOWN_2_POST.strip() | ||
assert nb.cells[4].source.strip() == MARKDOWN_3_POST.strip() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just added the processor here, otherwise it was not running
python -m nbconvert --to=html --NumberedHeadingsPreprocessor.enabled=true notebook.ipynb
(even though the option to enable it appeared inpython -m nbconvert --help-all