fix: mask code and math spans in one pass before the CJK emphasis repair

Masking fenced code, math and inline code in three passes let the math pattern match $ signs inside inline code, and the inline code pass then wrapped that placeholder in a new one, so a placeholder leaked into the stored answer. Match all three in one left-to-right pass and skip the repair when the text already has a NUL.
This commit is contained in:
berce
2026-10-28 14:17:35 +03:00
parent e99d632de5
commit 02f819038c
2 changed files with 21 additions and 3 deletions

View File

@@ -112,6 +112,10 @@ _INLINE_CODE_SPAN_RE = re.compile(r"`[^`\n]*`")
_MATH_SPAN_RE = re.compile(
r"\\\[[\s\S]*?\\\]|\\\([\s\S]*?\\\)|\$\$[\s\S]*?\$\$|\$(?!\s)(?:\\.|[^$\n])*?(?<!\s)\$"
)
# One left-to-right pass, so a span is never masked inside another (a `$` in code is not math).
_PROTECTED_SPAN_RE = re.compile(
"|".join(p.pattern for p in (_FENCED_CODE_BLOCK_RE, _INLINE_CODE_SPAN_RE, _MATH_SPAN_RE))
)
def _is_escaped(text: str, index: int) -> bool:
@@ -234,15 +238,16 @@ def _repair_chinese_emphasis_for_persistence(content: str, language: str) -> str
"""
if not content or not str(language or "").lower().startswith("zh"):
return content
# NUL delimits the placeholders below; text that already has one is left as is.
if "\x00" in content:
return content
protected: list[str] = []
def mask(match: re.Match[str]) -> str:
protected.append(match.group(0))
return f"\x00CJK_PROTECTED_{len(protected) - 1}\x00"
masked = _FENCED_CODE_BLOCK_RE.sub(mask, content)
masked = _MATH_SPAN_RE.sub(mask, masked)
masked = _INLINE_CODE_SPAN_RE.sub(mask, masked)
masked = _PROTECTED_SPAN_RE.sub(mask, content)
repaired = "\n".join(_repair_chinese_emphasis_line(line) for line in masked.split("\n"))
return re.sub(
r"\x00CJK_PROTECTED_(\d+)\x00",

View File

@@ -98,6 +98,19 @@ class TestAssemblePersistedAnswer:
content = "`中文*,重点*`\n$中文*,重点*$\n中文***,重点***内容"
assert _repair_chinese_emphasis_for_persistence(content, "zh") == content
def test_dollar_signs_in_code_and_literal_placeholders_survive(self) -> None:
inputs = [
"PHP 对象:`$b = $a`;PHP 数组:`$b = $a`。",
"```php\n$b = $a;\n```\n价格 $5,`$c = $d` 与 $x^2$",
"原文 \x00CJK_PROTECTED_0\x00 与 `代码`",
]
for content in inputs:
assert _repair_chinese_emphasis_for_persistence(content, "zh") == content
assert (
_repair_chinese_emphasis_for_persistence("`$b = $a`,中文*,重点*内容`$c`", "zh")
== "`$b = $a`,中文 *,重点* 内容`$c`"
)
def test_continuation_preserves_exact_visible_boundary(self) -> None:
segments = [
("round-part-1", "Part one. "),