--- a/mdit_py_plugins/section_ref/index.py +++ b/mdit_py_plugins/section_ref/index.py @@ -29,7 +29,12 @@ # ASCII digits only (``[0-9]``, never ``\d`` which also matches unicode digits). _SECTION_REF_PATTERN = re.compile(r"§([0-9]+(?:\.[0-9]+)*)") +# A level longer than nine digits is declined so ``int()`` never hits +# Python's integer string conversion limit (which cannot be configured +# below 640). +_MAX_LEVEL_DIGITS = 9 + def section_ref_plugin(md: MarkdownIt) -> None: """Parse section-sign references such as ``§1``, ``§1.1`` and ``§2.3.4``. @@ -49,6 +54,10 @@ it to a heading target without re-parsing. Leading zeros are normalized (``§01.02`` gives ``[1, 2]``); the original text remains in ``content``. + A level (dot-separated part) longer than nine digits makes the rule + decline, so the text renders literally; this avoids Python's integer + string conversion limit, which cannot be configured below 640. + The default rendering is ``§1.1``. Override it with ``md.add_render_rule("section_ref", ...)``. @@ -67,6 +76,12 @@ def _section_ref_rule(state: StateInline, silent: bool) -> bool: match = _SECTION_REF_PATTERN.match(state.src, state.pos, state.posMax) if not match: + return False + + # reject when any dot-separated level exceeds _MAX_LEVEL_DIGITS, + # to avoid hitting Python's integer string conversion limit + parts = match.group(1).split(".") + if any(len(part) > _MAX_LEVEL_DIGITS for part in parts): return False # reject when directly followed by an ASCII letter (e.g. "§1a", "§1.2b"), --- a/tests/test_section_ref.py +++ b/tests/test_section_ref.py @@ -119,6 +119,37 @@ section_ref_plugin(md) +def test_nine_digit_level_accepted(): + """A level with exactly nine digits is accepted.""" + md = MarkdownIt().use(section_ref_plugin) + html = md.render("§123456789") + assert '§123456789' in html + + +def test_ten_digit_level_renders_literally(): + """A level with ten digits is declined; text renders literally.""" + md = MarkdownIt().use(section_ref_plugin) + html = md.render("§1234567890") + assert "section-ref" not in html + assert "§1234567890" in html + + +def test_long_second_level_declines_whole_reference(): + """A long second level declines the entire reference, not just the suffix.""" + md = MarkdownIt().use(section_ref_plugin) + html = md.render("§1.1234567890") + assert "section-ref" not in html + assert "§1.1234567890" in html + + +def test_very_long_digit_run_does_not_raise(): + """A 4301-digit level does not raise ValueError.""" + md = MarkdownIt().use(section_ref_plugin) + html = md.render("§" + "1" * 4301) + assert "section-ref" not in html + assert "§" + "1" * 4301 in html + + @pytest.mark.parametrize("line,title,input,expected", read_fixture_file(FIXTURE_PATH)) def test_all(line, title, input, expected): md = MarkdownIt("commonmark").use(section_ref_plugin)