diff --git a/myst_parser/mdit_to_docutils/base.py b/myst_parser/mdit_to_docutils/base.py index 013c9aca..4c746917 100644 --- a/myst_parser/mdit_to_docutils/base.py +++ b/myst_parser/mdit_to_docutils/base.py @@ -1889,8 +1889,20 @@ def render_restructuredtext(self, token: SyntaxTreeNode) -> None: newdoc.reporter = self.reporter # pad the line numbers artificially so they offset with the fence block pseudosource = ("\n" * token_line(token)) + token.content - # actually parse the rst into our document - MockRSTParser().parse(pseudosource, newdoc) + # docutils only binds the reporter's line lookup if it has none, so remove + # any existing one, to let this block's state machine map its own lines + # (which `.. include::` shifts), then restore it afterwards + line_func = getattr(self.reporter, "get_source_and_line", None) + if line_func is not None: + del self.reporter.get_source_and_line + try: + # actually parse the rst into our document + MockRSTParser().parse(pseudosource, newdoc) + finally: + if line_func is not None: + self.reporter.get_source_and_line = line_func + else: + self.reporter.__dict__.pop("get_source_and_line", None) for node in newdoc: if node["names"]: self.document.note_explicit_target(node, node) diff --git a/tests/test_renderers/test_error_reporting.py b/tests/test_renderers/test_error_reporting.py index 17d68bcf..07851c8e 100644 --- a/tests/test_renderers/test_error_reporting.py +++ b/tests/test_renderers/test_error_reporting.py @@ -1,5 +1,6 @@ """Tests of the warning reporting for different MyST Markdown inputs.""" +import re from io import StringIO from pathlib import Path @@ -26,3 +27,43 @@ def test_basic(file_params): "corresponding footnote available", "corresponding footnotes available" ) file_params.assert_expected(text, rstrip=True) + + +@pytest.mark.parametrize("preamble", ["", "```{note}\nA note.\n```\n"]) +def test_eval_rst_include_locations(tmp_path, preamble): + """An ``.. include::`` in ``{eval-rst}`` must not shift later warning locations.""" + included = tmp_path / "inc.rst" + included.write_text("Line 1.\n\nAn *unclosed on line 3.\n", encoding="utf8") + content = preamble + ( + "```{eval-rst}\n" + f".. include:: {included.as_posix()}\n" + "\n" + "Block 1 *unclosed.\n" + "```\n" + "\n" + "```{eval-rst}\n" + "Block 2 *unclosed.\n" + "```\n" + "\n" + "{unknown-role}`x`\n" + ) + offset = preamble.count("\n") + report_stream = StringIO() + publish_doctree( + content, + source_path=str(tmp_path / "index.md"), + parser=Parser(), + settings_overrides={"warning_stream": report_stream}, + ) + locations = [ + (Path(source).name, int(line)) + for source, line in re.findall( + r"^(.+?):(\d+): \(", report_stream.getvalue(), re.MULTILINE + ) + ] + assert set(locations) == { + ("inc.rst", 3), + ("index.md", offset + 4), + ("index.md", offset + 8), + ("index.md", offset + 11), + }