# No valid title; destination must end at EOL (or EOF) p_eol = _skip_spaces_tabs(after_dest_pos) if p_eol == n: pos = n labels.add(_cm_normalize_link_label(raw_label)) lines_consumed = text.count("\n") + 1 break if text[p_eol] == "\n": pos = p_eol + 1 labels.add(_cm_normalize_link_label(raw_label)) lines_consumed = text[:pos].count("\n") continue # Neither valid title nor EOL after destination -> not a valid link ref def pos = save_pos break return labels, lines_consumed _CM_ENTITY_RE = re.compile(r"&(?:#[0-9]{1,7}|#[xX][0-9A-Fa-f]{1,6}|[A-Za-z][A-Za-z0-9]{1,31});", re.ASCII) _CM_ASCII_PUNCT = frozenset(r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""") def _cm_decode_entity(match: re.Match[str]) -> str: raw = match.group(0) if raw.startswith("&#"): try: cp = int(raw[3:-1], 16) if raw[2] in ("x", "X") else int(raw[2:-1], 10) if cp == 0 or cp > 0x10FFFF or (0xD800 <= cp <= 0xDFFF): return "\uFFFD" return chr(cp) except Exception: return raw decoded = html.unescape(raw) return decoded def _cm_render_inline_with_meta(raw: str, link_refs: set[str] | None = None) -> tuple[str, bool]: """Render visible plain text of a CommonMark 0.31.2 inline string and report whether any link/autolink formed. Enforces CommonMark §6.5 (links may not contain other links or autolinks at any level of nesting, e.g. Example 518 `[foo [bar](/uri)](/uri)` -> `[foo bar](/uri)`, while images may contain links and links may contain images). """ refs = link_refs or set() s = raw n = len(s) # Tokenize into protected literal spans vs plain text so emphasis resolution runs cleanly on plain tokens tokens: List[tuple[str, str]] = [] # ("lit" | "text" | "delim", val) has_link = False i = 0 def _find_matching_bracket(start_idx: int) -> int | None: depth = 0 j = start_idx while j < n: ch = s[j] if ch == "\\" and j + 1 < n and s[j + 1] in _CM_ASCII_PUNCT: j += 2 continue if ch == "`": bt = j while bt < n and s[bt] == "`": bt += 1 run = bt - j k = bt found_bt = False while k < n: if s[k] == "`": k2 = k while k2 < n and s[k2] == "`": k2 += 1 if k2 - k == run: j = k2 found_bt = True break k = k2 else: k += 1 if found_bt: continue j = bt continue if ch == "[": depth += 1 elif ch == "]": if depth == 0: return j depth -= 1 j += 1 return None def _try_consume_inline_dest(p: int) -> int | None: if p >= n or s[p] != "(": return None p += 1 while p < n and s[p] in (" ", "\t", "\n"): p += 1 if p < n and s[p] == ")": return p + 1 if p < n and s[p] == "<": p += 1 while p < n and s[p] != ">": if s[p] == "\n": return None if s[p] == "\\" and p + 1 < n: p += 2 continue p += 1 if p >= n: return None p += 1 else: pdepth = 0 while p < n: ch = s[p] if ch in (" ", "\t", "\n"): break if ch == "\\" and p + 1 < n and s[p + 1] in _CM_ASCII_PUNCT: p += 2 continue if ch == "(": pdepth += 1 elif ch == ")": if pdepth == 0: break pdepth -= 1 p += 1 if pdepth != 0: return None while p < n and s[p] in (" ", "\t", "\n"): p += 1 if p < n and s[p] in ('"', "'", "("): delim = ")" if s[p] == "(" else s[p] p += 1 while p < n and s[p] != delim: if s[p] == "\\" and p + 1 < n: p += 2 continue p += 1 if p >= n: return None p += 1 while p < n and s[p] in (" ", "\t", "\n"): p += 1 if p < n and s[p] == ")": return p + 1 return None while i < n: ch = s[i] # 1. Code span if ch == "`": j = i while j < n and s[j] == "`": j += 1 run = j - i k = j matched_end = None while k < n: if s[k] == "`": k2 = k while k2 < n and s[k2] == "`": k2 += 1 if k2 - k == run: matched_end = k break k = k2 else: k += 1 if matched_end is not None: code_body = s[j:matched_end].replace("\n", " ") if len(code_body) >= 2 and code_body[0] == " " and code_body[-1] == " " and any(c != " " for c in code_body): code_body = code_body[1:-1] tokens.append(("lit", code_body)) i = matched_end + run continue tokens.append(("lit", s[i:j])) i = j continue # 2. Backslash escape (CommonMark §2.4: BEFORE HTML entities!) if ch == "\\" and i + 1 < n and s[i + 1] in _CM_ASCII_PUNCT: tokens.append(("lit", s[i + 1])) i += 2 continue # 3. Semicolon-required HTML character reference (CommonMark §2.5) if ch == "&": me = _CM_ENTITY_RE.match(s, i) if me: tokens.append(("lit", _cm_decode_entity(me))) i = me.end() continue tokens.append(("text", "&")) i += 1 continue # 4. Autolink or raw inline HTML tag / comment if ch == "<": m_auto = re.match(r"<([A-Za-z][A-Za-z0-9+.-]{1,31}:[^\s<>]*|[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*)>", s[i:]) if m_auto: tokens.append(("lit", m_auto.group(1))) has_link = True i += m_auto.end() continue m_html = re.match( r"(?:|<[A-Za-z][A-Za-z0-9-]*(?:[ \t\n]+[A-Za-z_:][A-Za-z0-9_.:-]*(?:[ \t\n]*=[ \t\n]*(?:[^ \t\n\"'=<>`]+|'[^']*'|\"[^\"]*\"))?)*[ \t\n]*/?>|)", s[i:], re.S, ) if m_html: # Strip raw inline HTML tags from visible text i += m_html.end() continue tokens.append(("text", "<")) i += 1 continue # 5. Links & Images: [label](dest), [label][ref], [label][], [label] (shortcut ref) if ch == "[" or (ch == "!" and i + 1 < n and s[i + 1] == "["): is_img = (ch == "!") open_b = i + 1 if is_img else i close_b = _find_matching_bracket(open_b + 1) if close_b is not None: inner_lbl = s[open_b + 1 : close_b] next_p = close_b + 1 end_pos: int | None = None # Inline link/image end_inline = _try_consume_inline_dest(next_p) if end_inline is not None: end_pos = end_inline # Full or collapsed reference link [text][ref] / [text][] elif next_p < n and s[next_p] == "[": close_r = _find_matching_bracket(next_p + 1) if close_r is not None: ref_raw = s[next_p + 1 : close_r] ref_key = _cm_normalize_link_label(ref_raw if ref_raw else inner_lbl) if ref_key in refs: end_pos = close_r + 1 # Shortcut reference link [text] elif _cm_normalize_link_label(inner_lbl) in refs: end_pos = close_b + 1 if end_pos is not None: inner_txt, inner_has_link = _cm_render_inline_with_meta(inner_lbl, refs) # CommonMark §6.5: links may not contain other links/autolinks; images may. if is_img or not inner_has_link: tokens.append(("lit", inner_txt)) has_link = (has_link or inner_has_link) if is_img else True i = end_pos continue tokens.append(("text", ch)) i += 1 continue