From 85a66ba052cef1cfc164aa286840788e82c8aab1 Mon Sep 17 00:00:00 2001 From: Yuzhong Zhang Date: Sun, 30 Aug 2026 02:01:20 +0000 Subject: [PATCH] fix: escape leading tilde fences after wrap Wrapping can move ~~~ to column 0, which CommonMark treats as a fenced code opener. Escape a leading run of three or more tildes in paragraph() like the other line-start guards. Fixes #590 --- src/mdformat/renderer/_context.py | 5 +++++ tests/data/wrap_width_50.md | 30 ++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/mdformat/renderer/_context.py b/src/mdformat/renderer/_context.py index 238dd07d..c38315f5 100644 --- a/src/mdformat/renderer/_context.py +++ b/src/mdformat/renderer/_context.py @@ -459,6 +459,11 @@ def paragraph(node: RenderTreeNode, context: RenderContext) -> str: # noqa: C90 elif all(c == "=" for c in stripped): lines[i] = lines[i].replace("=", "\\=", 1) + # Make sure a paragraph line does not start with three or more + # tildes (otherwise it will be interpreted as a fenced code block). + if re.match(r"~{3,}", lines[i]): + lines[i] = f"\\{lines[i]}" + # Check if the line could be interpreted as an HTML block. # If yes, prefix it with 4 spaces to prevent this. for html_seq_tuple in HTML_SEQUENCES: diff --git a/tests/data/wrap_width_50.md b/tests/data/wrap_width_50.md index eceede9f..be9fa55c 100644 --- a/tests/data/wrap_width_50.md +++ b/tests/data/wrap_width_50.md @@ -188,3 +188,33 @@ Starts with encoded space . * * \* . + + +Wrap three tildes to line start (issue #590) +. +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ~~~ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB +. +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +\~~~ +BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB +. + + +Wrap two tildes to line start +. +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ~~ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB +. +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +~~ +BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB +. + + +Wrap four tildes to line start +. +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ~~~~ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB +. +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +\~~~~ +BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB +.