28 lines
824 B
Python
28 lines
824 B
Python
import re
|
|
|
|
FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})", re.M)
|
|
|
|
|
|
def sections(text: str) -> dict[str, list[str]]:
|
|
blocks: list[tuple[str | None, list[str]]] = []
|
|
opener = ""
|
|
for line in text.splitlines():
|
|
if fence := FENCE.match(line):
|
|
marker = fence.group(1)
|
|
if not opener:
|
|
opener = marker
|
|
elif marker[0] == opener[0] and len(marker) >= len(opener) and not line[fence.end():].strip():
|
|
opener = ""
|
|
fenced = bool(opener or fence)
|
|
if not fenced and line.startswith("## "):
|
|
blocks.append((line.strip()[3:], []))
|
|
elif not fenced and line.startswith("# "):
|
|
blocks.append((None, []))
|
|
elif blocks and line.strip():
|
|
blocks[-1][1].append(line)
|
|
found: dict[str, list[str]] = {}
|
|
for name, body in blocks:
|
|
if name is not None:
|
|
found.setdefault(name, []).append("\n".join(body))
|
|
return found
|