Split body on `## ` headings, but only when they appear OUTSIDE fenced code blocks. A fence is opened/closed by a line starting with ``` (any number of backticks ≥ 3). Headings inside a fence stay attached to the surrounding section.
(body: str)
| 215 | |
| 216 | |
| 217 | def _split_body_fence_aware(body: str) -> list[str]: |
| 218 | """Split body on `## ` headings, but only when they appear OUTSIDE fenced code blocks. |
| 219 | |
| 220 | A fence is opened/closed by a line starting with ``` (any number of backticks ≥ 3). |
| 221 | Headings inside a fence stay attached to the surrounding section. |
| 222 | """ |
| 223 | sections: list[str] = [] |
| 224 | current: list[str] = [] |
| 225 | in_fence = False |
| 226 | fence_marker = "" # tracks the exact backtick run that opened the fence |
| 227 | |
| 228 | for line in body.splitlines(keepends=True): |
| 229 | stripped = line.lstrip() |
| 230 | if stripped.startswith("```"): |
| 231 | # Count leading backticks; same count must close. |
| 232 | marker = stripped[: len(stripped) - len(stripped.lstrip("`"))] |
| 233 | if not in_fence: |
| 234 | in_fence = True |
| 235 | fence_marker = marker |
| 236 | elif marker == fence_marker: |
| 237 | in_fence = False |
| 238 | fence_marker = "" |
| 239 | if not in_fence and line.startswith("## ") and current: |
| 240 | sections.append("".join(current)) |
| 241 | current = [line] |
| 242 | else: |
| 243 | current.append(line) |
| 244 | if current: |
| 245 | sections.append("".join(current)) |
| 246 | return sections |
| 247 | |
| 248 | |
| 249 | def _utf8_safe_cut(encoded: bytes, cap: int) -> tuple[bytes, bytes]: |
no outgoing calls