fix(telegram): render tilde and longer code fences as code

The Markdown-to-HTML converter only protected ``` blocks, and closed a
block at the first ``` it met. A ~~~ block was formatted as prose ("#
setup" turned bold, __init__ into <b>init</b>), and a ```` block showing a
``` example rendered as an empty <pre> followed by leaked, re-formatted
text.

Protect fenced blocks line by line first: open on ``` or ~~~, close on a
run of the same character at least as long. One-line ```code``` and
unclosed fences keep the previous regex handling. The streaming preview
strips fences through the same helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HuiandClaude Opus 5.5 authored and Xubin Ren committed 2026-10-18 18:33:24 +08:00
1 parent df6158ec18
commit 7f64efbb95
2 files changed
+73 -4

No files matched your search

+39 -4
View File
@@ -205,6 +205,41 @@ def _strip_md(s: str) -> str:
return s.strip()
_FENCE_OPEN_RE = re.compile(r'^[ \t]*(`{3,}|~{3,})(.*)$')
_INLINE_FENCE_RE = re.compile(r'```(?:[^\n]*\n)?([\s\S]*?)```')
def _replace_fenced_code(text: str, replace: Callable[[str], str]) -> str:
"""Replace fenced code blocks with ``replace(code)``.
A block opens on a ``` or ~~~ line and closes on a line holding only a run
of the same character that is at least as long, so tilde fences work and a
```` fence can show a ``` example. What remains (one-line ```code``` and
unclosed fences) keeps the previous regex handling.
"""
lines = text.split('\n')
out: list[str] = []
i = 0
while i < len(lines):
match = _FENCE_OPEN_RE.match(lines[i])
if match and not (match.group(1)[0] == '`' and '`' in match.group(2)):
fence = match.group(1)
for j in range(i + 1, len(lines)):
closing = lines[j].strip()
if len(closing) >= len(fence) and closing == fence[0] * len(closing):
out.append(replace(''.join(line + '\n' for line in lines[i + 1:j])))
i = j + 1
break
else:
out.append(lines[i])
i += 1
continue
out.append(lines[i])
i += 1
text = '\n'.join(out)
return _INLINE_FENCE_RE.sub(lambda m: replace(m.group(1)), text)
def _strip_md_block(text: str) -> str:
"""Strip block-level and inline markdown for readable plain-text preview.
@@ -212,7 +247,7 @@ def _strip_md_block(text: str) -> str:
markdown syntax while the response is still being generated.
"""
# Code blocks -> just the code
text = re.sub(r'```(?:[^\n]*\n)?([\s\S]*?)```', r'\1', text)
text = _replace_fenced_code(text, lambda code: code)
# Headers -> plain text
text = re.sub(r'^#{1,6}\s+(.+)$', r'\1', text, flags=re.MULTILINE)
# Blockquotes
@@ -274,11 +309,11 @@ def _markdown_to_telegram_html(text: str) -> str:
# 1. Extract and protect code blocks (preserve content from other processing)
code_blocks: list[str] = []
def save_code_block(m: re.Match[str]) -> str:
code_blocks.append(m.group(1))
def save_code_block(code: str) -> str:
code_blocks.append(code)
return f"\x00CB{len(code_blocks) - 1}\x00"
text = re.sub(r'```(?:[^\n]*\n)?([\s\S]*?)```', save_code_block, text)
text = _replace_fenced_code(text, save_code_block)
# 1.5. Convert markdown tables to box-drawing (reuse code_block placeholders)
lines = text.split('\n')
@@ -2965,6 +2965,34 @@ def test_markdown_to_html_headers_become_bold() -> None:
assert _markdown_to_telegram_html("### Deep") == "<b>Deep</b>"
def test_markdown_to_html_tilde_fence_is_code() -> None:
from nanobot.channels.telegram.runtime import _markdown_to_telegram_html
text = "Run:\n~~~python\n# setup\ndef __init__(self): pass\n~~~\nDone"
assert _markdown_to_telegram_html(text) == (
"Run:\n<pre><code># setup\ndef __init__(self): pass\n</code></pre>\nDone"
)
def test_markdown_to_html_longer_fence_keeps_nested_example() -> None:
from nanobot.channels.telegram.runtime import _markdown_to_telegram_html
text = "Example:\n````markdown\n```python\nx = a * b\n```\n**raw**\n````\nAfter **bold**"
assert _markdown_to_telegram_html(text) == (
"Example:\n<pre><code>```python\nx = a * b\n```\n**raw**\n</code></pre>\n"
"After <b>bold</b>"
)
def test_markdown_to_html_single_line_and_backtick_fences_unchanged() -> None:
from nanobot.channels.telegram.runtime import _markdown_to_telegram_html
assert _markdown_to_telegram_html("```py\n# c\nx = __y__\n```") == (
"<pre><code># c\nx = __y__\n</code></pre>"
)
assert _markdown_to_telegram_html("Use ```ls -la``` now") == "Use <pre><code>ls -la</code></pre> now"
def test_markdown_to_html_numbered_lists_preserved() -> None:
from nanobot.channels.telegram.runtime import _markdown_to_telegram_html
@@ -3067,6 +3095,12 @@ def test_strip_md_block_converts_bullets_and_numbers() -> None:
assert "2. item c" in result
def test_strip_md_block_strips_tilde_fences() -> None:
from nanobot.channels.telegram.runtime import _strip_md_block
assert _strip_md_block("~~~bash\nls\n~~~\nDone") == "ls\n\nDone"
def test_strip_md_block_strips_links() -> None:
from nanobot.channels.telegram.runtime import _strip_md_block