Skip to content

Commit ae612b0

Browse files
authored
Expand Markdown detection to all Python language names (#268)
1 parent da9b455 commit ae612b0

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

CHANGELOG.rst

+2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ Changelog
66

77
Thanks to initial work from Matthew Anderson in `PR #246 <https://github.com/adamchainz/blacken-docs/pull/246>`__.
88

9+
* Expand Markdown detection to all Python language names from Pygments: ``py``, ``sage``, ``python3``, ``py3``, and ``numpy``.
10+
911
* Remove ``language_version`` from ``.pre-commit-hooks.yaml``.
1012
This change allows ``default_language_version`` in ``.pre-commit-config.yaml` to take precedence.
1113

src/blacken_docs/__init__.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@
1313
from black.mode import TargetVersion
1414

1515

16+
PYGMENTS_PY_LANGS = frozenset(("python", "py", "sage", "python3", "py3", "numpy"))
17+
PYGMENTS_PY_LANGS_RE_FRAGMENT = f"({'|'.join(PYGMENTS_PY_LANGS)})"
1618
MD_RE = re.compile(
17-
r"(?P<before>^(?P<indent> *)```\s*python( .*?)?\n)"
19+
r"(?P<before>^(?P<indent> *)```\s*" + PYGMENTS_PY_LANGS_RE_FRAGMENT + r"( .*?)?\n)"
1820
r"(?P<code>.*?)"
1921
r"(?P<after>^(?P=indent)```\s*$)",
2022
re.DOTALL | re.MULTILINE,
@@ -25,7 +27,6 @@
2527
r"(?P<after>^(?P=indent)```.*$)",
2628
re.DOTALL | re.MULTILINE,
2729
)
28-
RST_PY_LANGS = frozenset(("python", "py", "sage", "python3", "py3", "numpy"))
2930
BLOCK_TYPES = "(code|code-block|sourcecode|ipython)"
3031
DOCTEST_TYPES = "(testsetup|testcleanup|testcode)"
3132
RST_RE = re.compile(
@@ -117,7 +118,7 @@ def _md_match(match: Match[str]) -> str:
117118

118119
def _rst_match(match: Match[str]) -> str:
119120
lang = match["lang"]
120-
if lang is not None and lang not in RST_PY_LANGS:
121+
if lang is not None and lang not in PYGMENTS_PY_LANGS:
121122
return match[0]
122123
min_indent = min(INDENT_RE.findall(match["code"]))
123124
trailing_ws_match = TRAILING_NL_RE.search(match["code"])

tests/test_blacken_docs.py

+6
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ def test_format_src_markdown_leading_whitespace():
2929
assert after == ("``` python\n" "f(1, 2, 3)\n" "```\n")
3030

3131

32+
def test_format_src_markdown_short_name():
33+
before = "``` py\n" "f(1,2,3)\n" "```\n"
34+
after, _ = blacken_docs.format_str(before, BLACK_MODE)
35+
assert after == ("``` py\n" "f(1, 2, 3)\n" "```\n")
36+
37+
3238
def test_format_src_markdown_options():
3339
before = "```python title='example.py'\n" + "f(1,2,3)\n" + "```\n"
3440
after, _ = blacken_docs.format_str(before, BLACK_MODE)

0 commit comments

Comments
 (0)