Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/using.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,16 @@ token = Token("paragraph_open", "p", 1, block=True, map=[1, 2])
token == tokens[0]
```

For tokens that are expected to have a source map, use `require_map()` to get it as a `list[int]`:

```{jupyter-execute}
token.require_map()
```

This returns the existing `map` list without copying it.
If `map` is `None`, it raises `ValueError` with the token type in the message.
The `map` attribute remains optional for tokens without source positions.

The `'inline'` type token contain the inline tokens as children:

```{jupyter-execute}
Expand Down
9 changes: 9 additions & 0 deletions markdown_it/token.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,15 @@ class Token:
def __post_init__(self) -> None:
self.attrs = convert_attrs(self.attrs)

def require_map(self) -> list[int]:
"""Return the source map, raising ``ValueError`` if it is absent.

The returned list is the token's existing ``map``, not a copy.
"""
if self.map is None:
raise ValueError(f"Token of type {self.type!r} has no source map")
return self.map

def attrIndex(self, name: str) -> int:
warnings.warn( # noqa: B028
"Token.attrIndex should not be used, since Token.attrs is a dictionary",
Expand Down
49 changes: 49 additions & 0 deletions tests/test_api/test_token.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import warnings

import pytest

from markdown_it import MarkdownIt
from markdown_it.token import Token


Expand Down Expand Up @@ -36,3 +39,49 @@ def test_token():
def test_serialization():
token = Token("name", "tag", 0, children=[Token("other", "tag2", 0)])
assert token == Token.from_dict(token.as_dict())


@pytest.mark.parametrize(
"source,token_type,expected",
[
("```python\nprint('hello')\n```\n", "fence", [0, 3]),
("<div>\nhello\n</div>\n", "html_block", [0, 3]),
],
)
def test_require_map_from_parser(source, token_type, expected):
token = MarkdownIt().parse(source)[0]
before = token.as_dict()

assert token.type == token_type
assert token.require_map() == expected
assert token.require_map() is token.map
assert token.as_dict() == before


@pytest.mark.parametrize("source_map", [[0, 2], [0, 0], []])
def test_require_map_returns_existing_list(source_map):
token = Token("custom", "", 0, map=source_map)
assert token.require_map() is source_map


def test_require_map_missing():
inline = MarkdownIt().parseInline("text")[0]
assert inline.children is not None
token = inline.children[0]
assert token.map is None

with pytest.raises(ValueError, match="text"):
token.require_map()
assert token.map is None


def test_require_map_after_reassignment():
token = Token("custom", "", 0, map=[0, 2])
original = token.require_map()
token.map = [3, 5]
assert token.require_map() == [3, 5]
assert token.require_map() is not original

token.map = None
with pytest.raises(ValueError, match="custom"):
token.require_map()