import re from cross.tokens import LinkToken, TextToken, Token MFM_PATTERN = re.compile(r"\$\[([^\[\]]+)\]") def strip_mfm(tokens: list[Token]) -> tuple[list[Token], bool]: modified = False original: str | None for tk in tokens: if isinstance(tk, TextToken): original = tk.text cleaned = __strip_mfm(original) if cleaned != original: modified = True tk.text = cleaned or "" elif isinstance(tk, LinkToken): original = tk.label cleaned = __strip_mfm(original) if cleaned != original: modified = True tk.label = cleaned return tokens, modified def __strip_mfm(text: str | None) -> str | None: if text is None: return None def match_contents(match: re.Match[str]): content = match.group(1).strip() parts = content.split(" ", 1) return parts[1] if len(parts) > 1 else "" while MFM_PATTERN.search(text): text = MFM_PATTERN.sub(match_contents, text) return text