A Markdown syntax tree node. A class that can be used to construct a tree representation of a linear `markdown-it-py` token stream. Each node in the tree represents either: - root of the Markdown document - a single unnested `Token` - a `Token` "_open" and "_close" to
| 21 | |
| 22 | |
| 23 | class SyntaxTreeNode: |
| 24 | """A Markdown syntax tree node. |
| 25 | |
| 26 | A class that can be used to construct a tree representation of a linear |
| 27 | `markdown-it-py` token stream. |
| 28 | |
| 29 | Each node in the tree represents either: |
| 30 | - root of the Markdown document |
| 31 | - a single unnested `Token` |
| 32 | - a `Token` "_open" and "_close" token pair, and the tokens nested in |
| 33 | between |
| 34 | """ |
| 35 | |
| 36 | def __init__( |
| 37 | self, tokens: Sequence[Token] = (), *, create_root: bool = True |
| 38 | ) -> None: |
| 39 | """Initialize a `SyntaxTreeNode` from a token stream. |
| 40 | |
| 41 | If `create_root` is True, create a root node for the document. |
| 42 | """ |
| 43 | # Only nodes representing an unnested token have self.token |
| 44 | self.token: Token | None = None |
| 45 | |
| 46 | # Only containers have nester tokens |
| 47 | self.nester_tokens: _NesterTokens | None = None |
| 48 | |
| 49 | # Root node does not have self.parent |
| 50 | self._parent: Any = None |
| 51 | |
| 52 | # Empty list unless a non-empty container, or unnested token that has |
| 53 | # children (i.e. inline or img) |
| 54 | self._children: list[Any] = [] |
| 55 | |
| 56 | if create_root: |
| 57 | self._set_children_from_tokens(tokens) |
| 58 | return |
| 59 | |
| 60 | if not tokens: |
| 61 | raise ValueError( |
| 62 | "Can only create root from empty token sequence." |
| 63 | " Set `create_root=True`." |
| 64 | ) |
| 65 | elif len(tokens) == 1: |
| 66 | inline_token = tokens[0] |
| 67 | if inline_token.nesting: |
| 68 | raise ValueError( |
| 69 | "Unequal nesting level at the start and end of token stream." |
| 70 | ) |
| 71 | self.token = inline_token |
| 72 | if inline_token.children: |
| 73 | self._set_children_from_tokens(inline_token.children) |
| 74 | else: |
| 75 | self.nester_tokens = _NesterTokens(tokens[0], tokens[-1]) |
| 76 | self._set_children_from_tokens(tokens[1:-1]) |
| 77 | |
| 78 | def __repr__(self) -> str: |
| 79 | return f"{type(self).__name__}({self.type})" |
| 80 |
no outgoing calls
searching dependent graphs…