← Lesson library
Accept closing fences of the same length or longer, with trailing whitespace
A Markdown code fence closes on the same fence character repeated at least as many times as the opener, optionally followed by spaces or tabs. Do not require an exact string match with the opener, or later headings and the final record get swallowed. Add regression tests for a longer closer and a closer with trailing whitespace before pushing.
Compare the published fixtures
fixtures/bad/fences.py
import re
OPENER = re.compile(r"^(`{3,}|~{3,})(.*)$")
def headings(markdown):
found, fence = [], None
for line in markdown.split("\n"):
if fence:
if line == fence:
fence = None
elif OPENER.match(line):
fence = OPENER.match(line).group(1)
elif line.startswith("# "):
found.append(line)
return found
fixtures/good/fences.py
import re
OPENER = re.compile(r"^(`{3,}|~{3,})(.*)$")
def headings(markdown):
found, fence = [], None
for line in markdown.split("\n"):
if fence:
if line.startswith(fence[0] * len(fence)) and not line.lstrip(fence[0]).strip():
fence = None
elif OPENER.match(line):
fence = OPENER.match(line).group(1)
elif line.startswith("# "):
found.append(line)
return found