-
Notifications
You must be signed in to change notification settings - Fork 8
👌 IMPROVE: Explicitly parse block attributes #50
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
Open
brunobeltran
wants to merge
1
commit into
executablebooks:master
Choose a base branch
from
brunobeltran:bruno/block-formatting-upstream
base: master
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.
Open
Changes from all commits
Commits
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 hidden or 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 | ||||
|---|---|---|---|---|---|---|
|
|
@@ -2,10 +2,13 @@ | |||||
|
|
||||||
| import re | ||||||
| import textwrap | ||||||
| from typing import Dict | ||||||
|
|
||||||
| from markdown_it import MarkdownIt | ||||||
| from markdown_it.rules_core.state_core import StateCore | ||||||
| import mdformat.plugins | ||||||
| from mdformat.renderer import RenderContext, RenderTreeNode | ||||||
| from mdit_py_plugins.attrs import attrs_block_plugin | ||||||
| from mdit_py_plugins.dollarmath import dollarmath_plugin | ||||||
| from mdit_py_plugins.myst_blocks import myst_block_plugin | ||||||
| from mdit_py_plugins.myst_role import myst_role_plugin | ||||||
|
|
@@ -45,13 +48,80 @@ def update_mdit(mdit: MarkdownIt) -> None: | |||||
| # Enable dollarmath markdown-it extension | ||||||
| mdit.use(dollarmath_plugin) | ||||||
|
|
||||||
| # Enable support for attribute tagging for paragraphs and other "blocks" | ||||||
| mdit.use(attrs_block_plugin) | ||||||
|
|
||||||
| # Trick `mdformat`s AST validation by removing HTML rendering of code | ||||||
| # blocks and fences. Directives are parsed as code fences and we | ||||||
| # modify them in ways that don't break MyST AST but do break | ||||||
| # CommonMark AST, so we need to do this to make validation pass. | ||||||
| mdit.add_render_rule("fence", render_fence_html) | ||||||
| mdit.add_render_rule("code_block", render_fence_html) | ||||||
|
|
||||||
| # Force `mdformat` to treat "equivalent" attribute sets in a given HTML element | ||||||
| # (e.g., `<p id="a" key1="value1">` as equivalent to `<p key1="value1" id="a">` by | ||||||
| # just sorting all such key/value groups. | ||||||
| # | ||||||
| # Multiple block attributes that are stacked on top of each other can create output | ||||||
| # HTML attribute orderings (from mdit_py_plugins.attrs's parsing logic) that cannot | ||||||
| # be replicated if we (nicely, for a formatter) collapse those blocks into a single | ||||||
| # nicely-ordered attr dict. Therefore, there is no way to avoid doing this sorting, | ||||||
| # i.e., we cannot just "preserve" the input ordering. | ||||||
| mdit.core.ruler.push("sort_attrs", _sort_attrs) | ||||||
|
|
||||||
|
|
||||||
| def _sort_attrs(state: StateCore) -> None: | ||||||
| """Sort attributes in all tokens to ensure deterministic HTML rendering. | ||||||
|
|
||||||
| This fixes validation errors where `mdformat` thinks the HTML has changed | ||||||
| simply because the attribute order flipped (e.g. `id="..." class="..."` | ||||||
| vs `class="..." id="..."`). | ||||||
| """ | ||||||
| for token in state.tokens: | ||||||
| if token.attrs: | ||||||
| token.attrs = dict(sorted(token.attrs.items())) | ||||||
|
|
||||||
|
|
||||||
| def _reconstruct_attrs(attrs: Dict[str, str | int | float]) -> str: | ||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| if not attrs: | ||||||
| return "" | ||||||
|
|
||||||
| parts = [] | ||||||
| if "id" in attrs: | ||||||
| parts.append(f"#{attrs['id']}") | ||||||
| if "class" in attrs: | ||||||
| assert isinstance(attrs["class"], str), ( | ||||||
| "mdit_py_plugins.attrs guarantees a string here." | ||||||
| ) | ||||||
| for cls in attrs["class"].split(): | ||||||
| parts.append(f".{cls}") | ||||||
| for k, v in attrs.items(): | ||||||
| if k in {"id", "class"}: | ||||||
| continue | ||||||
| parts.append(f'{k}="{v}"') | ||||||
|
|
||||||
| if not parts: | ||||||
| return "" | ||||||
| return "{" + " ".join(parts) + "}" | ||||||
|
|
||||||
|
|
||||||
| def _append_attrs_postprocessor( | ||||||
| text: str, node: RenderTreeNode, context: RenderContext | ||||||
| ) -> str: | ||||||
| """Prepend MyST attributes to the already-rendered text.""" | ||||||
| attrs_str = _reconstruct_attrs(node.attrs) | ||||||
| if attrs_str: | ||||||
| return f"{attrs_str}\n{text}" | ||||||
| return text | ||||||
|
|
||||||
|
|
||||||
| def _paragraph_postprocessor( | ||||||
| text: str, node: RenderTreeNode, context: RenderContext | ||||||
| ) -> str: | ||||||
| """Encapsulate all paragraph post-processing.""" | ||||||
| text = _escape_paragraph(text, node, context) | ||||||
| return _append_attrs_postprocessor(text, node, context) | ||||||
|
|
||||||
|
|
||||||
| def _role_renderer(node: RenderTreeNode, context: RenderContext) -> str: | ||||||
| role_name = "{" + node.meta["name"] + "}" | ||||||
|
|
@@ -117,7 +187,6 @@ def _escape_paragraph(text: str, node: RenderTreeNode, context: RenderContext) - | |||||
| lines = text.split("\n") | ||||||
|
|
||||||
| for i in range(len(lines)): | ||||||
|
|
||||||
| # Three or more "+" chars are interpreted as a block break. Escape them. | ||||||
| space_removed = lines[i].replace(" ", "") | ||||||
| if space_removed.startswith("+++"): | ||||||
|
|
@@ -155,4 +224,14 @@ def _escape_text(text: str, node: RenderTreeNode, context: RenderContext) -> str | |||||
| "math_block": _math_block_renderer, | ||||||
| "fence": fence, | ||||||
| } | ||||||
| POSTPROCESSORS = {"paragraph": _escape_paragraph, "text": _escape_text} | ||||||
| POSTPROCESSORS = { | ||||||
| "blockquote": _append_attrs_postprocessor, | ||||||
| "colon_fence": _append_attrs_postprocessor, | ||||||
| "fence": _append_attrs_postprocessor, | ||||||
| "heading": _append_attrs_postprocessor, | ||||||
| "table": _append_attrs_postprocessor, | ||||||
| # Paragraphs require special handling to escape strings like "++", but also need to | ||||||
| # be able to have attrs added. | ||||||
| "paragraph": _paragraph_postprocessor, | ||||||
| "text": _escape_text, | ||||||
| } | ||||||
This file contains hidden or 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
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.