fix(telegram): a prose $$ never pairs across a code span with a later formula

Round-4 review: since the $ escape runs per prose stretch between code regions
(78a87c7c), a prose "Use $$ to get the shell PID." paired with a later display
formula's $$ across a code span, so the amounts in between ("Cost is $5 vs $10")
were left bare and rendered as garbled math, and the real formula's $$ was left
unpaired (6 of 20k corpus replies). A $$ pair now stays in one prose stretch: its
body holds no backtick, blank line, or bare $ before a digit (an amount).
This commit is contained in:
Teknium
2026-11-10 05:16:02 -08:00
parent a9ec0d8c5f
commit 8e31ef1e39
2 changed files with 10 additions and 1 deletions

View File

@@ -454,8 +454,11 @@ def _escape_bare_bracket(m, seg: str) -> str:
# and the currency $ it escapes: a lone $ before an
# amount, or after a currency prefix (R$ 1.000, US$ 1,200). Telegram's rich Markdown pairs any two
# bare $ as inline LaTeX, so "$395k vs $483k" otherwise renders as one garbled math span.
# A $$ pair stays inside one stretch of prose: its body never holds a backtick (a code span
# split the prose there, so a prose "Use $$ for the PID" would pair across it with the next
# formula), a blank line, or a bare $ before a digit (an amount, never display math).
_RICH_DOLLAR_RE = re.compile(
r'(?P<keep>\\\$|\$\$[\s\S]*?\$\$'
r'(?P<keep>\\\$|\$\$(?:[^$\n`]|(?<=\\)\$|(?<!\\)\$(?![\d$])|\n(?![ \t>]*(?:\n|$)))*?\$\$'
r'|(?<![\w$])\$(?![\d\s$])(?:\\.|[^\\\n$])+?(?<!\s)\$(?![\d$])'
r'|(?<![\w$\\])\$\d[\w.,]*(?:[-+*/^=<>]|\\[a-zA-Z]++)(?:[\w.,(){}^_+*/=<>-]|\\[a-zA-Z]+)*+(?<![-+*/^=<>])\$(?![\w$])'
r'|(?<![\w$\\])\$\d[\w.,]*(?<![.,])\$(?![\w$])'

View File

@@ -51,6 +51,12 @@ def test_a_lone_star_inside_bold_stays_a_visible_star(adapter, markdown, expecte
("Use ``` to open a fence. Cost is $5", "Use ``` to open a fence. Cost is \\$5"),
("Use ``` to open a fence. Cost is $5\n```\nx\n```", "Use ``` to open a fence. Cost is \\$5\n```\nx\n```"),
("Here is the code: ```bash\necho $5\n```\nthen $6", "Here is the code: ```bash\necho $5\n```\nthen \\$6"),
# A prose $$ (the shell PID) never pairs across a code span with a later formula's $$.
(
"Use $$ for the PID.\n\nA `x` span. Use $$ again. Cost is $5 vs $10.\n\n$$\nE = mc^2\n$$",
"Use $$ for the PID.\n\nA `x` span. Use $$ again. Cost is \\$5 vs \\$10.\n\n$$\nE = mc^2\n$$",
),
("Use $$ for the PID. A `x` span. Cost is $5. Use $$ again.", "Use $$ for the PID. A `x` span. Cost is \\$5. Use $$ again."),
],
)
def test_rich_dollar_escape_leaves_every_code_region_verbatim(markdown, expected):