| 1 |
"""A tree representation of a linear markdown-it token stream. |
| 2 |
|
| 3 |
This module is not part of upstream JavaScript markdown-it. |
| 4 |
""" |
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
from collections.abc import Generator, Sequence |
| 8 |
import textwrap |
| 9 |
from typing import Any, NamedTuple, TypeVar, overload |
| 10 |
|
| 11 |
from .token import Token |
| 12 |
|
| 13 |
|
| 14 |
class _NesterTokens(NamedTuple): |
| 15 |
opening: Token |
| 16 |
closing: Token |
| 17 |
|
| 18 |
|
| 19 |
_NodeType = TypeVar("_NodeType", bound="SyntaxTreeNode") |
| 20 |
|
| 21 |
|
| 22 |
class SyntaxTreeNode: |
| 23 |
"""A Markdown syntax tree node. |
| 24 |
|
| 25 |
A class that can be used to construct a tree representation of a linear |
| 26 |
`markdown-it-py` token stream. |
| 27 |
|
| 28 |
Each node in the tree represents either: |
| 29 |
- root of the Markdown document |
| 30 |
- a single unnested `Token` |
| 31 |
- a `Token` "_open" and "_close" token pair, and the tokens nested in |
| 32 |
between |
| 33 |
""" |
| 34 |
|
| 35 |
def __init__( |
| 36 |
self, tokens: Sequence[Token] = (), *, create_root: bool = True |
| 37 |
) -> None: |
| 38 |
"""Initialize a `SyntaxTreeNode` from a token stream. |
| 39 |
|
| 40 |
If `create_root` is True, create a root node for the document. |
| 41 |
""" |
| 42 |
# Only nodes representing an unnested token have self.token |
| 43 |
self.token: Token | None = None |
| 44 |
|
| 45 |
# Only containers have nester tokens |
| 46 |
self.nester_tokens: _NesterTokens | None = None |
| 47 |
|
| 48 |
# Root node does not have self.parent |
| 49 |
self._parent: Any = None |
| 50 |
|
| 51 |
# Empty list unless a non-empty container, or unnested token that has |
| 52 |
# children (i.e. inline or img) |
| 53 |
self._children: list[Any] = [] |
| 54 |
|
| 55 |
if create_root: |
| 56 |
self._set_children_from_tokens(tokens) |
| 57 |
return |
| 58 |
|
| 59 |
if not tokens: |
| 60 |
raise ValueError( |
| 61 |
"Can only create root from empty token sequence." |
| 62 |
" Set `create_root=True`." |
| 63 |
) |
| 64 |
elif len(tokens) == 1: |
| 65 |
inline_token = tokens[0] |
| 66 |
if inline_token.nesting: |
| 67 |
raise ValueError( |
| 68 |
"Unequal nesting level at the start and end of token stream." |
| 69 |
) |
| 70 |
self.token = inline_token |
| 71 |
if inline_token.children: |
| 72 |
self._set_children_from_tokens(inline_token.children) |
| 73 |
else: |
| 74 |
self.nester_tokens = _NesterTokens(tokens[0], tokens[-1]) |
| 75 |
self._set_children_from_tokens(tokens[1:-1]) |
| 76 |
|
| 77 |
def __repr__(self) -> str: |
| 78 |
return f"{type(self).__name__}({self.type})" |
| 79 |
|
| 80 |
@overload |
| 81 |
def __getitem__(self: _NodeType, item: int) -> _NodeType: |
| 82 |
... |
| 83 |
|
| 84 |
@overload |
| 85 |
def __getitem__(self: _NodeType, item: slice) -> list[_NodeType]: |
| 86 |
... |
| 87 |
|
| 88 |
def __getitem__(self: _NodeType, item: int | slice) -> _NodeType | list[_NodeType]: |
| 89 |
return self.children[item] |
| 90 |
|
| 91 |
def to_tokens(self: _NodeType) -> list[Token]: |
| 92 |
"""Recover the linear token stream.""" |
| 93 |
|
| 94 |
def recursive_collect_tokens(node: _NodeType, token_list: list[Token]) -> None: |
| 95 |
if node.type == "root": |
| 96 |
for child in node.children: |
| 97 |
recursive_collect_tokens(child, token_list) |
| 98 |
elif node.token: |
| 99 |
token_list.append(node.token) |
| 100 |
else: |
| 101 |
assert node.nester_tokens |
| 102 |
token_list.append(node.nester_tokens.opening) |
| 103 |
for child in node.children: |
| 104 |
recursive_collect_tokens(child, token_list) |
| 105 |
token_list.append(node.nester_tokens.closing) |
| 106 |
|
| 107 |
tokens: list[Token] = [] |
| 108 |
recursive_collect_tokens(self, tokens) |
| 109 |
return tokens |
| 110 |
|
| 111 |
@property |
| 112 |
def children(self: _NodeType) -> list[_NodeType]: |
| 113 |
return self._children |
| 114 |
|
| 115 |
@children.setter |
| 116 |
def children(self: _NodeType, value: list[_NodeType]) -> None: |
| 117 |
self._children = value |
| 118 |
|
| 119 |
@property |
| 120 |
def parent(self: _NodeType) -> _NodeType | None: |
| 121 |
return self._parent # type: ignore |
| 122 |
|
| 123 |
@parent.setter |
| 124 |
def parent(self: _NodeType, value: _NodeType | None) -> None: |
| 125 |
self._parent = value |
| 126 |
|
| 127 |
@property |
| 128 |
def is_root(self) -> bool: |
| 129 |
"""Is the node a special root node?""" |
| 130 |
return not (self.token or self.nester_tokens) |
| 131 |
|
| 132 |
@property |
| 133 |
def is_nested(self) -> bool: |
| 134 |
"""Is this node nested?. |
| 135 |
|
| 136 |
Returns `True` if the node represents a `Token` pair and tokens in the |
| 137 |
sequence between them, where `Token.nesting` of the first `Token` in |
| 138 |
the pair is 1 and nesting of the other `Token` is -1. |
| 139 |
""" |
| 140 |
return bool(self.nester_tokens) |
| 141 |
|
| 142 |
@property |
| 143 |
def siblings(self: _NodeType) -> Sequence[_NodeType]: |
| 144 |
"""Get siblings of the node. |
| 145 |
|
| 146 |
Gets the whole group of siblings, including self. |
| 147 |
""" |
| 148 |
if not self.parent: |
| 149 |
return [self] |
| 150 |
return self.parent.children |
| 151 |
|
| 152 |
@property |
| 153 |
def type(self) -> str: |
| 154 |
"""Get a string type of the represented syntax. |
| 155 |
|
| 156 |
- "root" for root nodes |
| 157 |
- `Token.type` if the node represents an unnested token |
| 158 |
- `Token.type` of the opening token, with "_open" suffix stripped, if |
| 159 |
the node represents a nester token pair |
| 160 |
""" |
| 161 |
if self.is_root: |
| 162 |
return "root" |
| 163 |
if self.token: |
| 164 |
return self.token.type |
| 165 |
assert self.nester_tokens |
| 166 |
return _removesuffix(self.nester_tokens.opening.type, "_open") |
| 167 |
|
| 168 |
@property |
| 169 |
def next_sibling(self: _NodeType) -> _NodeType | None: |
| 170 |
"""Get the next node in the sequence of siblings. |
| 171 |
|
| 172 |
Returns `None` if this is the last sibling. |
| 173 |
""" |
| 174 |
self_index = self.siblings.index(self) |
| 175 |
if self_index + 1 < len(self.siblings): |
| 176 |
return self.siblings[self_index + 1] |
| 177 |
return None |
| 178 |
|
| 179 |
@property |
| 180 |
def previous_sibling(self: _NodeType) -> _NodeType | None: |
| 181 |
"""Get the previous node in the sequence of siblings. |
| 182 |
|
| 183 |
Returns `None` if this is the first sibling. |
| 184 |
""" |
| 185 |
self_index = self.siblings.index(self) |
| 186 |
if self_index - 1 >= 0: |
| 187 |
return self.siblings[self_index - 1] |
| 188 |
return None |
| 189 |
|
| 190 |
def _add_child( |
| 191 |
self, |
| 192 |
tokens: Sequence[Token], |
| 193 |
) -> None: |
| 194 |
"""Make a child node for `self`.""" |
| 195 |
child = type(self)(tokens, create_root=False) |
| 196 |
child.parent = self |
| 197 |
self.children.append(child) |
| 198 |
|
| 199 |
def _set_children_from_tokens(self, tokens: Sequence[Token]) -> None: |
| 200 |
"""Convert the token stream to a tree structure and set the resulting |
| 201 |
nodes as children of `self`.""" |
| 202 |
reversed_tokens = list(reversed(tokens)) |
| 203 |
while reversed_tokens: |
| 204 |
token = reversed_tokens.pop() |
| 205 |
|
| 206 |
if not token.nesting: |
| 207 |
self._add_child([token]) |
| 208 |
continue |
| 209 |
if token.nesting != 1: |
| 210 |
raise ValueError("Invalid token nesting") |
| 211 |
|
| 212 |
nested_tokens = [token] |
| 213 |
nesting = 1 |
| 214 |
while reversed_tokens and nesting: |
| 215 |
token = reversed_tokens.pop() |
| 216 |
nested_tokens.append(token) |
| 217 |
nesting += token.nesting |
| 218 |
if nesting: |
| 219 |
raise ValueError(f"unclosed tokens starting {nested_tokens[0]}") |
| 220 |
|
| 221 |
self._add_child(nested_tokens) |
| 222 |
|
| 223 |
def pretty( |
| 224 |
self, *, indent: int = 2, show_text: bool = False, _current: int = 0 |
| 225 |
) -> str: |
| 226 |
"""Create an XML style string of the tree.""" |
| 227 |
prefix = " " * _current |
| 228 |
text = prefix + f"<{self.type}" |
| 229 |
if not self.is_root and self.attrs: |
| 230 |
text += " " + " ".join(f"{k}={v!r}" for k, v in self.attrs.items()) |
| 231 |
text += ">" |
| 232 |
if ( |
| 233 |
show_text |
| 234 |
and not self.is_root |
| 235 |
and self.type in ("text", "text_special") |
| 236 |
and self.content |
| 237 |
): |
| 238 |
text += "\n" + textwrap.indent(self.content, prefix + " " * indent) |
| 239 |
for child in self.children: |
| 240 |
text += "\n" + child.pretty( |
| 241 |
indent=indent, show_text=show_text, _current=_current + indent |
| 242 |
) |
| 243 |
return text |
| 244 |
|
| 245 |
def walk( |
| 246 |
self: _NodeType, *, include_self: bool = True |
| 247 |
) -> Generator[_NodeType, None, None]: |
| 248 |
"""Recursively yield all descendant nodes in the tree starting at self. |
| 249 |
|
| 250 |
The order mimics the order of the underlying linear token |
| 251 |
stream (i.e. depth first). |
| 252 |
""" |
| 253 |
if include_self: |
| 254 |
yield self |
| 255 |
for child in self.children: |
| 256 |
yield from child.walk(include_self=True) |
| 257 |
|
| 258 |
# NOTE: |
| 259 |
# The values of the properties defined below directly map to properties |
| 260 |
# of the underlying `Token`s. A root node does not translate to a `Token` |
| 261 |
# object, so calling these property getters on a root node will raise an |
| 262 |
# `AttributeError`. |
| 263 |
# |
| 264 |
# There is no mapping for `Token.nesting` because the `is_nested` property |
| 265 |
# provides that data, and can be called on any node type, including root. |
| 266 |
|
| 267 |
def _attribute_token(self) -> Token: |
| 268 |
"""Return the `Token` that is used as the data source for the |
| 269 |
properties defined below.""" |
| 270 |
if self.token: |
| 271 |
return self.token |
| 272 |
if self.nester_tokens: |
| 273 |
return self.nester_tokens.opening |
| 274 |
raise AttributeError("Root node does not have the accessed attribute") |
| 275 |
|
| 276 |
@property |
| 277 |
def tag(self) -> str: |
| 278 |
"""html tag name, e.g. \"p\" """ |
| 279 |
return self._attribute_token().tag |
| 280 |
|
| 281 |
@property |
| 282 |
def attrs(self) -> dict[str, str | int | float]: |
| 283 |
"""Html attributes.""" |
| 284 |
return self._attribute_token().attrs |
| 285 |
|
| 286 |
def attrGet(self, name: str) -> None | str | int | float: |
| 287 |
"""Get the value of attribute `name`, or null if it does not exist.""" |
| 288 |
return self._attribute_token().attrGet(name) |
| 289 |
|
| 290 |
@property |
| 291 |
def map(self) -> tuple[int, int] | None: |
| 292 |
"""Source map info. Format: `tuple[ line_begin, line_end ]`""" |
| 293 |
map_ = self._attribute_token().map |
| 294 |
if map_: |
| 295 |
# Type ignore because `Token`s attribute types are not perfect |
| 296 |
return tuple(map_) # type: ignore |
| 297 |
return None |
| 298 |
|
| 299 |
@property |
| 300 |
def level(self) -> int: |
| 301 |
"""nesting level, the same as `state.level`""" |
| 302 |
return self._attribute_token().level |
| 303 |
|
| 304 |
@property |
| 305 |
def content(self) -> str: |
| 306 |
"""In a case of self-closing tag (code, html, fence, etc.), it |
| 307 |
has contents of this tag.""" |
| 308 |
return self._attribute_token().content |
| 309 |
|
| 310 |
@property |
| 311 |
def markup(self) -> str: |
| 312 |
"""'*' or '_' for emphasis, fence string for fence, etc.""" |
| 313 |
return self._attribute_token().markup |
| 314 |
|
| 315 |
@property |
| 316 |
def info(self) -> str: |
| 317 |
"""fence infostring""" |
| 318 |
return self._attribute_token().info |
| 319 |
|
| 320 |
@property |
| 321 |
def meta(self) -> dict[Any, Any]: |
| 322 |
"""A place for plugins to store an arbitrary data.""" |
| 323 |
return self._attribute_token().meta |
| 324 |
|
| 325 |
@property |
| 326 |
def block(self) -> bool: |
| 327 |
"""True for block-level tokens, false for inline tokens.""" |
| 328 |
return self._attribute_token().block |
| 329 |
|
| 330 |
@property |
| 331 |
def hidden(self) -> bool: |
| 332 |
"""If it's true, ignore this element when rendering. |
| 333 |
Used for tight lists to hide paragraphs.""" |
| 334 |
return self._attribute_token().hidden |
| 335 |
|
| 336 |
|
| 337 |
def _removesuffix(string: str, suffix: str) -> str: |
| 338 |
"""Remove a suffix from a string. |
| 339 |
|
| 340 |
Replace this with str.removesuffix() from stdlib when minimum Python |
| 341 |
version is 3.9. |
| 342 |
""" |
| 343 |
if suffix and string.endswith(suffix): |
| 344 |
return string[: -len(suffix)] |
| 345 |
return string |