Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expand Markdown detection to all Python language names #268

Merged
merged 1 commit into from Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Expand Up @@ -6,6 +6,8 @@ Changelog

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

* Expand Markdown detection to all Python language names from Pygments: ``py``, ``sage``, ``python3``, ``py3``, and ``numpy``.

* Remove ``language_version`` from ``.pre-commit-hooks.yaml``.
This change allows ``default_language_version`` in ``.pre-commit-config.yaml` to take precedence.

Expand Down
7 changes: 4 additions & 3 deletions src/blacken_docs/__init__.py
Expand Up @@ -14,8 +14,10 @@
from black.mode import TargetVersion


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<before>^(?P<indent> *)```\s*python( .*?)?\n)"
r"(?P<before>^(?P<indent> *)```\s*" + PYGMENTS_PY_LANGS_RE_FRAGMENT + r"( .*?)?\n)"
r"(?P<code>.*?)"
r"(?P<after>^(?P=indent)```\s*$)",
re.DOTALL | re.MULTILINE,
Expand All @@ -26,7 +28,6 @@
r"(?P<after>^(?P=indent)```.*$)",
re.DOTALL | re.MULTILINE,
)
RST_PY_LANGS = frozenset(("python", "py", "sage", "python3", "py3", "numpy"))
BLOCK_TYPES = "(code|code-block|sourcecode|ipython)"
DOCTEST_TYPES = "(testsetup|testcleanup|testcode)"
RST_RE = re.compile(
Expand Down Expand Up @@ -117,7 +118,7 @@ def _md_match(match: Match[str]) -> str:

def _rst_match(match: Match[str]) -> str:
lang = match["lang"]
if lang is not None and lang not in RST_PY_LANGS:
if lang is not None and lang not in PYGMENTS_PY_LANGS:
return match[0]
min_indent = min(INDENT_RE.findall(match["code"]))
trailing_ws_match = TRAILING_NL_RE.search(match["code"])
Expand Down
6 changes: 6 additions & 0 deletions tests/test_blacken_docs.py
Expand Up @@ -29,6 +29,12 @@ def test_format_src_markdown_leading_whitespace():
assert after == ("``` python\n" "f(1, 2, 3)\n" "```\n")


def test_format_src_markdown_short_name():
before = "``` py\n" "f(1,2,3)\n" "```\n"
after, _ = blacken_docs.format_str(before, BLACK_MODE)
assert after == ("``` py\n" "f(1, 2, 3)\n" "```\n")


def test_format_src_markdown_options():
before = "```python title='example.py'\n" + "f(1,2,3)\n" + "```\n"
after, _ = blacken_docs.format_str(before, BLACK_MODE)
Expand Down