\n" + "\n".join(inner) + "\n") else: out.append("
\n") elif _is_list_start(line): html, i = _parse_list(lines, i, offset, link_rewrite, slugs) out.append(html) elif _table_at(lines, i) is not None: html, i = _take_table(lines, i, link_rewrite) out.append(html) else: buf = [line] i += 1 while i < n and not _starts_block(lines, i): buf.append(lines[i]) i += 1 out.append("
" + _inline("\n".join(buf).strip(), link_rewrite) + "
") return out def _starts_block(lines, i): line = lines[i] if not line.strip(): return True if _fence_open(line) is not None: return True if _parse_heading(line) is not None: return True if _is_hr(line): return True if _parse_quote(line) is not None: return True if _is_list_start(line): return True if _table_at(lines, i) is not None: return True return False def _parse_heading(line): """Return ``(level, raw text)`` for an ATX heading, else None.""" body = line.lstrip(" ") if len(line) - len(body) > 3 or not body.startswith("#"): return None match = _HEADING_RE.match(body) if match is None: return None hashes, rest = match.group(1), match.group(2) if body[len(hashes):len(hashes) + 1] not in ("", " ", "\t"): return None rest = _CLOSING_HASHES_RE.sub("", rest).strip() return (len(hashes), rest) def _fence_open(line): """Return the info string for a fence opener, else None.""" body = line.lstrip(" ") if len(line) - len(body) > 3 or not body.startswith("```"): return None if body[3:4] == "`": return None return body[3:].strip() def _fence_close(line): stripped = line.strip() return (stripped.startswith("```") and all(ch in " \t" for ch in stripped[3:])) def _take_fence(lines, i): info = _fence_open(lines[i]) lang = info.split()[0] if info.split() else "" buf = [] i += 1 while i < len(lines) and not _fence_close(lines[i]): buf.append(lines[i]) i += 1 if i < len(lines): i += 1 if lang and _LANG_RE.match(lang): open_tag = f'' else: open_tag = "") else: parts.append(_inline_raw(chunk, link_rewrite)) return "".join(parts) def _align(cell): text = cell.strip() if text.startswith(":") and text.endswith(":") and len(text) > 2: return "center" if text.endswith(":"): return "right" return "left" def _table_at(lines, i): """Return the alignment row's cells if a table starts here.""" if "|" not in lines[i] or i + 1 >= len(lines): return None cells = _split_cells(lines[i + 1]) if not cells: return None raws = [] for cell in cells: raws.append("".join(chunk for _, chunk in cell)) if any(not _ALIGN_RE.match(raw.strip()) for raw in raws): return None return raws def _take_table(lines, i, link_rewrite): header = _split_cells(lines[i]) aligns = [_align("".join(chunk for _, chunk in cell)) for cell in _split_cells(lines[i + 1])] width = max(len(header), len(aligns)) while len(header) < width: header.append([(False, "")]) while len(aligns) < width: aligns.append("left") def row(cells, tag): out = [] scope = ' scope="col"' if tag == "th" else "" for pos in range(width): cell = cells[pos] if pos < len(cells) else [(False, "")] cls = ' class="num"' if aligns[pos] == "right" else "" out.append(f"<{tag}{scope}{cls}>" + _render_cell(cell, link_rewrite) + f"{tag}>") return "", i def _is_hr(line): stripped = line.strip() if len(stripped) < 3 or stripped[0] not in "*-_": return False char = stripped[0] return (stripped.count(char) >= 3 and all(ch in (char, " ", "\t") for ch in stripped)) def _parse_quote(line): """Return the line's quote content, else None.""" body = line.lstrip(" ") if len(line) - len(body) > 3 or not body.startswith(">"): return None rest = body[1:] if rest.startswith((" ", "\t")): rest = rest[1:] return rest def _is_list_start(line): match = _LIST_RE.match(line) return match is not None and len(match.group(1)) <= 3 def _parse_list(lines, i, offset, link_rewrite, slugs): first = _LIST_RE.match(lines[i]) base = len(first.group(1)) ordered = first.group(2)[0].isdigit() start = int(first.group(2)[:-1]) if ordered else 1 items = [] loose = False n = len(lines) while i < n: match = _LIST_RE.match(lines[i]) if (match is None or len(match.group(1)) != base or (match.group(2)[0].isdigit() != ordered)): break content_indent = base + len(match.group(2)) + 1 item = [match.group(3)] i += 1 while i < n: line = lines[i] if not line.strip(): end = i while end < n and not lines[end].strip(): end += 1 if end >= n: i = end break peek = _LIST_RE.match(lines[end]) peek_indent = len(lines[end]) - len(lines[end].lstrip(" ")) same_item = peek is not None and peek.group(2)[0].isdigit() == ordered and peek_indent == base if same_item or peek_indent >= content_indent: loose = True item.append("") i = end else: break continue inner = _LIST_RE.match(line) indent = len(line) - len(line.lstrip(" ")) if (inner is not None and indent == base and inner.group(2)[0].isdigit() == ordered): break if indent >= content_indent: item.append(line[content_indent:]) i += 1 else: break while item and not item[-1].strip(): item.pop() items.append(item) rendered = [] for item in items: sub = _blocks(item, offset, link_rewrite, slugs) if (not loose and sub and sub[0].startswith("" return open_tag + _html.escape("\n".join(buf)) + "") and sub[0].endswith("
")): sub = [sub[0][len(""):-len("
")]] + sub[1:] rendered.append("" + "\n".join(sub) + " " if sub else "") if ordered and start != 1: open_tag, close_tag = f'', "
" elif ordered: open_tag, close_tag = "", "
" else: open_tag, close_tag = "", "
" return open_tag + "\n" + "\n".join(rendered) + "\n" + close_tag, i def _split_cells(line): """Split a table row into cell segment lists. Each cell is a list of ``(is_code, text)`` segments. Pipes inside code spans or escaped as ``\\|`` never split the cell. """ text = line.strip() if text.startswith("|"): text = text[1:] if text.endswith("|") and not text.endswith("\\|"): text = text[:-1] cells = [] current = [] for is_code, chunk in _split_code(text): if is_code: current.append((True, chunk)) else: pieces = re.split(r"(?" + _html.escape(chunk) + "" + "".join(out) + " " head = row(header, "th") body_rows = [] i += 2 while i < len(lines) and lines[i].strip() and "|" in lines[i]: body_rows.append(row(_split_cells(lines[i]), "td")) i += 1 html = "
" + _html.escape(code) + "")
else:
parts.append(_inline_raw(chunk, link_rewrite))
return "".join(parts)
def _split_code(text):
"""Split text into ``(is_code, chunk)`` parts at backtick spans."""
parts = []
buf = []
i = 0
n = len(text)
while i < n:
if text[i] != "`":
buf.append(text[i])
i += 1
continue
end = i
while end < n and text[end] == "`":
end += 1
run = end - i
close = _find_close(text, end, run)
if close < 0:
buf.append(text[i:end])
i = end
else:
if buf:
parts.append((False, "".join(buf)))
buf = []
parts.append((True, text[end:close]))
i = close + run
if buf:
parts.append((False, "".join(buf)))
return parts
def _find_close(text, start, run):
tick = "`" * run
pos = text.find(tick, start)
while pos >= 0:
prev_is_tick = pos > 0 and text[pos - 1] == "`"
next_is_tick = pos + run < len(text) and text[pos + run] == "`"
if not prev_is_tick and not next_is_tick:
return pos
pos = text.find(tick, pos + 1)
return -1
def _inline_raw(text, link_rewrite):
out = []
i = 0
n = len(text)
while i < n:
char = text[i]
if char == "\\" and i + 1 < n and text[i + 1] in _PUNCT:
out.append(_html.escape(text[i + 1]))
i += 2
elif char == "[":
html, i = _parse_link(text, i, link_rewrite)
out.append(html)
elif char == "<":
html, i = _parse_angle(text, i, link_rewrite)
out.append(html)
elif ((text.startswith("http://", i) or text.startswith("https://", i))
and (i == 0 or text[i - 1] in " \t\n('\"")):
html, i = _parse_bare(text, i, link_rewrite)
out.append(html)
elif char in "*_":
html, i = _parse_emph(text, i, link_rewrite)
out.append(html)
elif char == "&":
out.append("&")
i += 1
elif char == ">":
out.append(">")
i += 1
else:
out.append(_html.escape(char))
i += 1
return "".join(out)
def _parse_link(text, i, link_rewrite):
"""Parse ``[label](destination)`` at ``text[i] == '['``."""
close = text.find("]", i + 1)
if close < 0 or close + 1 >= len(text) or text[close + 1] != "(":
return "[", i + 1
pos = close + 2
while pos < len(text) and text[pos] in " \t":
pos += 1
if pos < len(text) and text[pos] == "<":
end = text.find(">", pos + 1)
if end < 0:
return "[", i + 1
dest, pos = text[pos + 1:end], end + 1
else:
start = pos
depth = 0
while pos < len(text):
char = text[pos]
if char == "(":
depth += 1
elif char == ")":
if depth == 0:
break
depth -= 1
elif char in " \t\n" and depth == 0:
break
pos += 1
dest = text[start:pos]
end = pos
while end < len(text) and text[end] in " \t":
end += 1
if end < len(text) and text[end] in "\"'(":
quote = ")" if text[end] == "(" else text[end]
title_end = text.find(quote, end + 1)
if title_end < 0:
return "[", i + 1
end = title_end + 1
if end >= len(text) or text[end] != ")":
return "[", i + 1
pos = end
if pos >= len(text) or text[pos] != ")":
return "[", i + 1
href = dest.strip()
if not href:
return "[", i + 1
if link_rewrite is not None:
href = link_rewrite(href)
inner = _inline(text[i + 1:close], link_rewrite)
if href is None:
return inner, pos + 1
return (f'{inner}',
pos + 1)
def _parse_angle(text, i, link_rewrite):
"""Parse ``