From 555ec318e31202041d43f73b9acc87770b6a86a4 Mon Sep 17 00:00:00 2001 From: Harutaka Kawamura Date: Sun, 28 Jan 2024 15:52:46 +0900 Subject: [PATCH] Ignore language specifiers after newlines in Markdown code blocks (#283) Co-Authored-By: Adam Johnson --- CHANGELOG.rst | 4 ++++ src/blacken_docs/__init__.py | 8 +++++--- tests/test_blacken_docs.py | 28 ++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 8017910..28af491 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -11,6 +11,10 @@ Changelog Thanks to Peter Cock in `PR #313 `__. +* Ignore language specifiers after newlines in Markdown code blocks. + + Thanks to Harutaka Kawamura in `PR #283 `__. + 1.16.0 (2023-08-16) ------------------- diff --git a/src/blacken_docs/__init__.py b/src/blacken_docs/__init__.py index b51a252..826255c 100644 --- a/src/blacken_docs/__init__.py +++ b/src/blacken_docs/__init__.py @@ -16,13 +16,15 @@ PYGMENTS_PY_LANGS = frozenset(("python", "py", "sage", "python3", "py3", "numpy")) PYGMENTS_PY_LANGS_RE_FRAGMENT = f"({'|'.join(PYGMENTS_PY_LANGS)})" MD_RE = re.compile( - r"(?P^(?P *)```\s*" + PYGMENTS_PY_LANGS_RE_FRAGMENT + r"( .*?)?\n)" + r"(?P^(?P *)```[^\S\r\n]*" + + PYGMENTS_PY_LANGS_RE_FRAGMENT + + r"( .*?)?\n)" r"(?P.*?)" - r"(?P^(?P=indent)```\s*$)", + r"(?P^(?P=indent)```[^\S\r\n]*$)", re.DOTALL | re.MULTILINE, ) MD_PYCON_RE = re.compile( - r"(?P^(?P *)```\s*pycon( .*?)?\n)" + r"(?P^(?P *)```[^\S\r\n]*pycon( .*?)?\n)" r"(?P.*?)" r"(?P^(?P=indent)```.*$)", re.DOTALL | re.MULTILINE, diff --git a/tests/test_blacken_docs.py b/tests/test_blacken_docs.py index c4ec19a..45d964e 100644 --- a/tests/test_blacken_docs.py +++ b/tests/test_blacken_docs.py @@ -53,6 +53,20 @@ def test_format_src_markdown_leading_whitespace(): ) +def test_format_src_markdown_python_after_newline(): + before = dedent( + """\ + ``` + python --version + echo "python" + ``` + """ + ) + after, errors = blacken_docs.format_str(before, BLACK_MODE) + assert errors == [] + assert after == before + + def test_format_src_markdown_short_name(): before = dedent( """\ @@ -144,6 +158,20 @@ def test_format_src_markdown_pycon(): ) +def test_format_src_markdown_pycon_after_newline(): + before = dedent( + """\ + ``` + pycon is great + >>> yes it is + ``` + """ + ) + after, errors = blacken_docs.format_str(before, BLACK_MODE) + assert errors == [] + assert after == before + + def test_format_src_markdown_pycon_options(): before = ( "hello\n"