Skip to content

Commit

Permalink
Added regex for Sphinx default language blocks.
Browse files Browse the repository at this point in the history
  • Loading branch information
carltongibson committed Dec 1, 2022
1 parent 79ef671 commit f269206
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
22 changes: 22 additions & 0 deletions blacken_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@
rf'(?P<code>(^((?P=indent) +.*)?\n)+)',
re.MULTILINE,
)
RST_SPHINX_DEFAULT_LANG_RE = re.compile(
r'(?P<before>'
r'^(?P<indent> *)(?!\.\. )'
r'.*::\n'
r'((?P=indent) +:.*\n)*'
r'\n*'
r')'
r'(?P<code>(^((?P=indent) +.*)?\n)+)',
re.MULTILINE,
)
RST_PYCON_RE = re.compile(
r'(?P<before>'
r'(?P<indent> *)\.\. ((code|code-block):: pycon|doctest::.*)\n'
Expand Down Expand Up @@ -115,6 +125,17 @@ def _rst_match(match: Match[str]) -> str:
code = textwrap.indent(code, min_indent)
return f'{match["before"]}{code.rstrip()}{trailing_ws}'

def _rst_sphinx_default_lang_match(match: Match[str]) -> str:
min_indent = min(INDENT_RE.findall(match['code']))
trailing_ws_match = TRAILING_NL_RE.search(match['code'])
assert trailing_ws_match
trailing_ws = trailing_ws_match.group()
code = textwrap.dedent(match['code'])
with _collect_error(match):
code = black.format_str(code, mode=black_mode)
code = textwrap.indent(code, min_indent)
return f'{match["before"]}{code.rstrip()}{trailing_ws}'

def _pycon_match(match: Match[str]) -> str:
code = ''
fragment = None
Expand Down Expand Up @@ -187,6 +208,7 @@ def _latex_pycon_match(match: Match[str]) -> str:
src = MD_PYCON_RE.sub(_md_pycon_match, src)
src = RST_RE.sub(_rst_match, src)
src = RST_PYCON_RE.sub(_rst_pycon_match, src)
src = RST_SPHINX_DEFAULT_LANG_RE.sub(_rst_sphinx_default_lang_match, src)
src = LATEX_RE.sub(_latex_match, src)
src = LATEX_PYCON_RE.sub(_latex_pycon_match, src)
src = PYTHONTEX_RE.sub(_latex_match, src)
Expand Down
18 changes: 18 additions & 0 deletions tests/blacken_docs_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,24 @@ def test_format_src_rst():
)


def test_format_src_rst_sphinx_default_language():
before = (
'hello::\n'
'\n'
' f(1,2,3)\n'
'\n'
'world\n'
)
after, _ = blacken_docs.format_str(before, BLACK_MODE)
assert after == (
'hello::\n'
'\n'
' f(1, 2, 3)\n'
'\n'
'world\n'
)


def test_format_src_rst_sphinx_doctest():
before = (
'.. testsetup:: group1\n'
Expand Down

0 comments on commit f269206

Please sign in to comment.