Skip to content

Commit

Permalink
Merge pull request #128 from adamchainz/issue_126_fix_nested_code_blocks
Browse files Browse the repository at this point in the history
Fix nested code block syntax
  • Loading branch information
asottile committed Nov 19, 2021
2 parents 8016cd8 + 9fa6d86 commit 732d0c0
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
7 changes: 5 additions & 2 deletions blacken_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@
r'(?P<after>^(?P=indent)```.*$)',
re.DOTALL | re.MULTILINE,
)
PY_LANGS = '(python|py|sage|python3|py3|numpy)'
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(
rf'(?P<before>'
rf'^(?P<indent> *)\.\. ('
rf'jupyter-execute::|'
rf'{BLOCK_TYPES}:: {PY_LANGS}|'
rf'{BLOCK_TYPES}:: (?P<lang>\w+)|'
rf'{DOCTEST_TYPES}::.*'
rf')\n'
rf'((?P=indent) +:.*\n)*'
Expand Down Expand Up @@ -103,6 +103,9 @@ def _md_match(match: Match[str]) -> str:
return f'{match["before"]}{code}{match["after"]}'

def _rst_match(match: Match[str]) -> str:
lang = match['lang']
if lang is not None and lang not in RST_PY_LANGS:
return match[0]
min_indent = min(INDENT_RE.findall(match['code']))
trailing_ws_match = TRAILING_NL_RE.search(match['code'])
assert trailing_ws_match
Expand Down
15 changes: 15 additions & 0 deletions tests/blacken_docs_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,21 @@ def test_format_src_rst_with_highlight_directives():
)


def test_format_src_rst_python_inside_non_python_code_block():
before = (
'blacken-docs does changes like:\n'
'\n'
'.. code-block:: diff\n'
'\n'
' .. code-block:: python\n'
'\n'
" - 'Hello World'\n"
' + "Hello World"\n'
)
after, _ = blacken_docs.format_str(before, BLACK_MODE)
assert after == before


def test_integration_ok(tmpdir, capsys):
f = tmpdir.join('f.md')
f.write(
Expand Down

0 comments on commit 732d0c0

Please sign in to comment.