Repository: adamchainz/blacken-docs (language: python)

Issue:
Blacken-docs removes lines at beginning and end of codeblocks, thereby destroying the rst
### Python Version

3.10

### Package Version

1.13

### Description

![image](https://user-images.githubusercontent.com/8102638/216025503-1278f3f2-3a8c-4a8e-b7b5-69f55ff9c131.png)



Discussion / hints:
Probably when the first line is a comment.
No, it happens when the empty line between the code-block and your actual code contains the same amount of spaces as the rest of the code.
In theory, this is allowed by rst. Therefore I think Blacken-docs should handle this.

Fix patch:
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 75e961c..3360bd2 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -8,6 +8,10 @@ Changelog
 
 * Expand Markdown detection to all Python language names from Pygments: ``py``, ``sage``, ``python3``, ``py3``, and ``numpy``.
 
+* Preserve leading blank lines with whitespace in reStructuredText code blocks.
+
+  Thanks to Julianus Pfeuffer for the report in `Issue #217 <https://github.com/adamchainz/blacken-docs/issues/217>`__.
+
 * Remove ``language_version`` from ``.pre-commit-hooks.yaml``.
   This change allows ``default_language_version`` in ``.pre-commit-config.yaml` to take precedence.
 
diff --git a/src/blacken_docs/__init__.py b/src/blacken_docs/__init__.py
index aa593d3..903cf68 100644
--- a/src/blacken_docs/__init__.py
+++ b/src/blacken_docs/__init__.py
@@ -37,7 +37,7 @@
     rf"{DOCTEST_TYPES}::.*"
     rf")\n"
     rf"((?P=indent) +:.*\n)*"
-    rf"\n*"
+    rf"( *\n)*"
     rf")"
     rf"(?P<code>(^((?P=indent) +.*)?\n)+)",
     re.MULTILINE,


Test patch:
diff --git a/tests/test_blacken_docs.py b/tests/test_blacken_docs.py
index a55a617..46e4332 100644
--- a/tests/test_blacken_docs.py
+++ b/tests/test_blacken_docs.py
@@ -381,6 +381,24 @@ def test_format_src_rst_indented():
     )
 
 
+def test_format_src_rst_code_block_indent():
+    before = "\n".join(
+        [
+            ".. code-block:: python",
+            "   ",
+            "   f(1,2,3)\n",
+        ]
+    )
+    after, _ = blacken_docs.format_str(before, BLACK_MODE)
+    assert after == "\n".join(
+        [
+            ".. code-block:: python",
+            "   ",
+            "   f(1, 2, 3)\n",
+        ]
+    )
+
+
 def test_format_src_rst_with_highlight_directives():
     before = (
         ".. code-block:: python\n"