# 6. Emphasis delimiters (* or _) if ch in ("*", "_"): j = i while j < n and s[j] == ch: j += 1 tokens.append(("delim", s[i:j])) i = j continue tokens.append(("text", ch)) i += 1 # Resolve matched emphasis delimiter runs (* and _) per CommonMark §6.2 flanking rules def _prev_char(idx: int) -> str: for k in range(idx - 1, -1, -1): if tokens[k][1]: return tokens[k][1][-1] return " " def _next_char(idx: int) -> str: for k in range(idx + 1, len(tokens)): if tokens[k][1]: return tokens[k][1][0] return " " def _is_ws_ch(c: str) -> bool: return c.isspace() def _is_punct_ch(c: str) -> bool: return c in _CM_ASCII_PUNCT delims: List[Dict[str, Any]] = [] for idx, (tk, tv) in enumerate(tokens): if tk != "delim": continue dch = tv[0] pc_c = _prev_char(idx) nc_c = _next_char(idx) left_flank = (not _is_ws_ch(nc_c)) and (not _is_punct_ch(nc_c) or _is_ws_ch(pc_c) or _is_punct_ch(pc_c)) right_flank = (not _is_ws_ch(pc_c)) and (not _is_punct_ch(pc_c) or _is_ws_ch(nc_c) or _is_punct_ch(nc_c)) can_open = left_flank if dch == "*" else (left_flank and (not right_flank or _is_punct_ch(pc_c))) can_close = right_flank if dch == "*" else (right_flank and (not left_flank or _is_punct_ch(nc_c))) delims.append({ "idx": idx, "ch": dch, "rem": len(tv), "orig": len(tv), "can_open": can_open, "can_close": can_close, }) # Match closers against nearest valid openers ci = 0 while ci < len(delims): closer = delims[ci] if closer["rem"] <= 0 or not closer["can_close"]: ci += 1 continue matched_opener = None for oi in range(ci - 1, -1, -1): opener = delims[oi] if opener["rem"] <= 0 or not opener["can_open"] or opener["ch"] != closer["ch"]: continue if (opener["can_close"] or closer["can_open"]) and (opener["orig"] + closer["orig"]) % 3 == 0: if opener["orig"] % 3 != 0 or closer["orig"] % 3 != 0: continue matched_opener = oi break if matched_opener is not None: opener = delims[matched_opener] use = 2 if (opener["rem"] >= 2 and closer["rem"] >= 2) else 1 opener["rem"] -= use closer["rem"] -= use # Clear any intermediate unmatched delimiters between opener and closer for mi in range(matched_opener + 1, ci): delims[mi]["can_open"] = False delims[mi]["can_close"] = False if closer["rem"] == 0: ci += 1 else: ci += 1 delim_rem = {d["idx"]: d["rem"] for d in delims} out_parts: List[str] = [] for idx, (tk, tv) in enumerate(tokens): if tk == "delim": rem = delim_rem.get(idx, len(tv)) if rem > 0: out_parts.append(tv[:rem]) else: out_parts.append(tv) return "".join(out_parts), has_link def _cm_render_inline_visible_text(raw: str, link_refs: set[str] | None = None) -> str: """Render visible plain text of a CommonMark 0.31.2 inline heading string.""" txt, _ = _cm_render_inline_with_meta(raw, link_refs) return txt def _parse_commonmark_headings(text: str) -> List[Dict[str, Any]]: """Stdlib CommonMark 0.31.2 block + inline heading parser extracting ATX and multiline Setext headings. Tracks exact 4-column absolute tab stops across nested blockquotes and list items (§2.2/§5.1/§5.2), strictly checks open fenced/HTML leaf blocks before opening new containers, uses ASCII-only blank lines, parses full §4.7 link-reference definitions (nested parens, multi-line titles, non-blank labels), and renders visible inline heading text (code spans, backslash escapes before semicolon-required HTML5 entities, links/images, and emphasis). """ norm = text.replace("\r\n", "\n").replace("\r", "\n") raw_lines = norm.split("\n") line_offsets: List[int] = [] pos = 0 for ln in raw_lines: line_offsets.append(pos) pos += len(ln) + 1 headings: List[Dict[str, Any]] = [] doc_link_refs: set[str] = set() in_fence = False fence_char = "" fence_len = 0 fence_depth = 0 in_html_block_type = 0 html_block_depth = 0 para_lines: List[tuple[int, str, int]] = [] atx_re = re.compile(r"^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*$") fence_open_re = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$") setext_re = re.compile(r"^ {0,3}(=+|-+)[ \t]*$") thematic_re = re.compile(r"^[ ]{0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$") ul_re = re.compile(r"^( {0,3})([-+*])(?:([ \t]+)(.*)|([ \t]*))$") ol_re = re.compile(r"^( {0,3})([0-9]{1,9}[.)])(?:([ \t]+)(.*)|([ \t]*))$", re.ASCII) # CommonMark 0.31.2 §4.6 HTML block start/end rules (Types 1-7) html_t1_start_re = re.compile(r"^ {0,3}<(?:pre|script|style|textarea)(?:[ \t>]|$)", re.IGNORECASE) html_t1_end_re = re.compile(r"", re.IGNORECASE) html_t2_start_re = re.compile(r"^ {0,3}