« Back to Search  |  Reader Mode  |  Switch to Full Retro Site View Links: Stay in Reader  |  Retro Mode: ON  |  Original »
GitHub · Extracted in 1491 ms

🐛 FIX: Keep inline and image child edits in SyntaxTreeNode.to_tokens ... · executablebooks/markdown-it-py@4d7bf9e

Source: https://github.com/executablebooks/markdown-it-py/commit/4d7bf9e948d948860fa68394dfa1ef6d74812b92

Repository navigation

Commit 4d7bf9e


Browse files
KennyMcSimpson authored 🐛 FIX: Keep inline and image child edits in SyntaxTreeNode.to_tokens (#453 ) `SyntaxTreeNode.to_tokens()` appended inline and image tokens unchanged, so edits to their children in the tree were silently dropped. Their `children` lists are now rebuilt from the tree. The original Token objects are reused and their `children` are replaced in place, so the token stream the tree was built from sees the edits too; this is documented and tested.
1 parent 1b604f7 commit 4d7bf9e

3 files changed

Lines changed: 113 additions & 1 deletion

File tree

‎docs/using.md‎

Lines changed: 8 additions & 0 deletions
Original file line number Diff line number Diff line change
@@ -286,6 +286,14 @@ print(node[0])
286 286 node[0].next_sibling
287 287 ```
288 288
289 +Use `node.to_tokens()` to recover the linear token stream after modifying the
290 +tree's `children`, including those of inline and image nodes. This reuses the
291 +original token objects and updates their child lists to match the tree.
292 +The child lists are replaced in place, so the token stream the tree was built
293 +from sees the same edits. Another tree built from the same tokens keeps its own
294 +nodes, and its `to_tokens()` writes its own children back.
295 +Build the tree from `copy.deepcopy(tokens)` to avoid sharing.
296 +
289 297 ## Renderers
290 298
291 299 +++

‎markdown_it/tree.py‎

Lines changed: 17 additions & 1 deletion
Original file line number Diff line number Diff line change
@@ -91,13 +91,29 @@ def __getitem__(self, item: int | slice) -> Self | list[Self]:
91 91 return self.children[item]
92 92
93 93 def to_tokens(self) -> list[Token]:
94 - """Recover the linear token stream."""
94 + """Recover the linear token stream, including changes to the tree.
95 +
96 + The original tokens are reused, with their child lists updated to match
97 + the tree.
98 +
99 + The ``children`` of inline and image tokens are replaced in place.
100 + These ``Token`` objects are shared with the token stream the tree was
101 + built from, so that stream sees the edits too.
102 + Another tree built from the same tokens keeps its own nodes,
103 + and its ``to_tokens()`` writes its own children back.
104 + Build the tree from ``copy.deepcopy(tokens)`` to avoid sharing.
105 + """
95 106
96 107 def recursive_collect_tokens(node: Self, token_list: list[Token]) -> None:
97 108 if node.type == "root":
98 109 for child in node.children:
99 110 recursive_collect_tokens(child, token_list)
100 111 elif node.token:
112 + if node.token.children is not None:
113 + children: list[Token] = []
114 + for child in node.children:
115 + recursive_collect_tokens(child, children)
116 + node.token.children = children
101 117 token_list.append(node.token)
102 118 else:
103 119 assert node.nester_tokens

‎tests/test_tree.py‎

Lines changed: 88 additions & 0 deletions
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
1 +import pytest
2 +
1 3 from markdown_it import MarkdownIt
2 4 from markdown_it.tree import SyntaxTreeNode
3 5
@@ -10,8 +12,94 @@
10 12
11 13 def test_tree_to_tokens_conversion():
12 14 tokens = MarkdownIt().parse(EXAMPLE_MARKDOWN)
15 + serialized_tokens = [token.as_dict() for token in tokens]
13 16 tokens_after_roundtrip = SyntaxTreeNode(tokens).to_tokens()
14 17 assert tokens == tokens_after_roundtrip
18 + assert [token.as_dict() for token in tokens_after_roundtrip] == serialized_tokens
19 + assert all(
20 + before is after
21 + for before, after in zip(tokens, tokens_after_roundtrip, strict=True)
22 + )
23 +
24 +
25 +def _node_at(tree, path):
26 + node = tree
27 + for index in path:
28 + node = node[index]
29 + return node
30 +
31 +
32 +@pytest.mark.parametrize(
33 + "source,path,expected",
34 + [
35 + ("one\n\ntwo", (), "<p>two</p>\n<p>one</p>\n"),
36 + (
37 + "before *nested* after",
38 + (0, 0),
39 + "<p> after<em>nested</em>before </p>\n",
40 + ),
41 + (
42 + "![before *nested* after](image.png)",
43 + (0, 0, 0),
44 + '<p><img src="image.png" alt=" afternestedbefore " /></p>\n',
45 + ),
46 + ],
47 + ids=["blocks", "inline", "image"],
48 +)
49 +def test_tree_to_tokens_reordered_children(source, path, expected):
50 + md = MarkdownIt()
51 + tree = SyntaxTreeNode(md.parse(source))
52 + _node_at(tree, path).children.reverse()
53 +
54 + assert md.renderer.render(tree.to_tokens(), md.options, {}) == expected
55 +
56 +
57 +@pytest.mark.parametrize(
58 + "source,path,expected",
59 + [
60 + ("before *nested* after", (0, 0), "<p></p>\n"),
61 + ("before *nested* after", (0, 0, 1), "<p>before <em></em> after</p>\n"),
62 + (
63 + "![old alt](image.png)",
64 + (0, 0, 0),
65 + '<p><img src="image.png" alt="" /></p>\n',
66 + ),
67 + ],
68 + ids=["inline", "nested-inline", "image"],
69 +)
70 +def test_tree_to_tokens_cleared_children(source, path, expected):
71 + md = MarkdownIt()
72 + tree = SyntaxTreeNode(md.parse(source))
73 + _node_at(tree, path).children.clear()
74 +
75 + assert md.renderer.render(tree.to_tokens(), md.options, {}) == expected
76 +
77 +
78 +def test_tree_to_tokens_replaced_empty_inline_children():
79 + md = MarkdownIt()
80 + tree = SyntaxTreeNode(md.parseInline(""))
81 + replacement = SyntaxTreeNode(md.parseInline("*new*"))
82 + tree[0].children = replacement[0].children
83 +
84 + assert md.renderer.render(tree.to_tokens(), md.options, {}) == "<em>new</em>"
85 +
86 +
87 +def test_tree_to_tokens_updates_original_tokens():
88 + """Inline child edits are written in place on the shared tokens.
89 +
90 + This pins the documented behaviour of ``to_tokens``: the token stream the
91 + tree was built from sees the edit as well.
92 + """
93 + md = MarkdownIt()
94 + tokens = md.parse("before *nested* after")
95 + tree = SyntaxTreeNode(tokens)
96 + tree[0][0].children.clear()
97 +
98 + tree.to_tokens()
99 +
100 + assert tokens[1].type == "inline"
101 + assert tokens[1].children == []
102 + assert md.renderer.render(tokens, md.options, {}) == "<p></p>\n"
15 103
16 104
17 105 def test_property_passthrough():