Files

63 lines
2.2 KiB
Python

import re
import typing
FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})", re.M)
HEADING = re.compile(r"^(#+)\s+(.*?)\s*$")
def fenced_lines(text: str) -> list[tuple[str, bool]]:
"""Each line of text with whether a code fence holds it, the fence's own lines included. A fence closes only on a line of its own marker, as long as the opener or longer."""
found = []
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 = ""
found.append((line, bool(opener or fence)))
return found
def sections(text: str) -> dict[str, list[str]]:
blocks: list[tuple[str | None, list[str]]] = []
for line, fenced in fenced_lines(text):
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
def section(text: str, title: str) -> list[str] | None:
"""The lines under the first heading whose text fullmatches the pattern title, up to the next heading of its level or above, blank lines kept; None where none does."""
found: list[str] | None = None
level = 0
for line, fenced in fenced_lines(text):
heading = None if fenced else HEADING.match(line)
if found is None:
if heading and re.fullmatch(title, heading.group(2)):
found, level = [], len(heading.group(1))
elif heading and len(heading.group(1)) <= level:
break
else:
found.append(line)
return found
# Blockquoted, so a passage holding blank lines still ends visibly where the text after it starts.
def quoted(passage: str) -> str:
return "\n".join(f"> {line}" for line in passage.splitlines())
def listed(names: typing.Sequence[str], conjunction: str) -> str:
"""The names as `a, b and c`, with conjunction, such as `and` or `or`, before the last."""
return names[0] if len(names) == 1 else f"{', '.join(names[:-1])} {conjunction} {names[-1]}"