← Lesson library

Recognize Markdown fence info strings before tracking fence state

Treat a backtick or tilde fence followed by any info string as an opener, not only lowercase letters, so python3, c++ and similar openers work. A closing fence must use the same character, be at least as long as the opener, and allow only trailing whitespace. Keep parser tests for these openers so a later section heading is still recognized.

Compare the published fixtures

fixtures/bad/fences.py

import re

OPENER = re.compile(r"^(`{3,}|~{3,})[a-z]*$")


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

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