From d0b54b3b49588f88d52fd2869d9e43a7189f8bac Mon Sep 17 00:00:00 2001 From: Matt Fisher Date: Tue, 17 Nov 2026 09:19:57 +1100 Subject: [PATCH] Resolve backslash escapes in image alt text markdown-it keeps an image's alt text as raw Markdown source, so an escaped character such as "\*" reached Substack with its backslash. That also broke the export round trip: the exporter escapes "\\" and "]" in alt text, and reading the Markdown back kept those escapes. Resolve backslash escapes when building the image node, and have the exporter escape "[" as well so an unbalanced bracket in alt text no longer stops the line being read back as an image. Co-Authored-By: Claude --- CHANGELOG.md | 3 +++ substack/mdexport.py | 4 +++- substack/mdrender.py | 9 ++++++++- tests/substack/test_from_markdown_features.py | 9 +++++++++ tests/substack/test_markdown_export.py | 20 +++++++++++++++++++ 5 files changed, 43 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f9d4a60..1d235a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,9 @@ - Nested color and highlight spans override inherited styles of the same type without creating duplicate ProseMirror marks or changing sibling styles. Repeated style properties use the last nonempty declaration. +- Image alt text now resolves Markdown backslash escapes, so `![a \*b\*](...)` + produces the alt text `a *b*` instead of keeping the backslashes. Exported + alt text containing a backslash or square bracket now reads back unchanged. ### Development diff --git a/substack/mdexport.py b/substack/mdexport.py index 612f037..9996e41 100644 --- a/substack/mdexport.py +++ b/substack/mdexport.py @@ -251,7 +251,9 @@ def _render_image(node, unsupported): ): return _marker(node, unsupported) - alt = str(attrs.get("alt") or "").replace("\\", "\\\\").replace("]", "\\]") + # Escape what would end or unbalance the image's alt text; the renderer + # resolves these escapes again when the Markdown is read back. + alt = re.sub(r"([\\\[\]])", r"\\\1", str(attrs.get("alt") or "")) image_markdown = f"![{alt}]({_escape_destination(attrs['src'])}" if len(content) > 2: return _marker(node, unsupported) diff --git a/substack/mdrender.py b/substack/mdrender.py index 355889f..a4988b7 100644 --- a/substack/mdrender.py +++ b/substack/mdrender.py @@ -250,6 +250,10 @@ def _only_image(inline: SyntaxTreeNode) -> Optional[SyntaxTreeNode]: return None +# A backslash before ASCII punctuation is a Markdown escape for that character. +_BACKSLASH_ESCAPE = re.compile(r"\\([!-/:-@\[-`{-~])") + + def _captioned_image(img: SyntaxTreeNode, api) -> Dict: src = img.attrs.get("src", "") if api is not None and ( @@ -275,7 +279,10 @@ def _captioned_image(img: SyntaxTreeNode, api) -> Dict: raise ValueError(f"Failed to upload local image: {path}") from exc src = url # markdown-it stores the image alt text as the node's content, not in attrs. - alt = img.content or img.attrs.get("alt") or None + # That content is the raw Markdown source, so resolve backslash escapes: + # "\*" in the source means a literal "*" in the alt text. + alt = _BACKSLASH_ESCAPE.sub(r"\1", img.content or "") + alt = alt or img.attrs.get("alt") or None # Standard markdown image title `![alt](src "caption")` maps to Substack's caption node. title = img.attrs.get("title") or None caption = [nodes.text(title)] if title else None diff --git a/tests/substack/test_from_markdown_features.py b/tests/substack/test_from_markdown_features.py index 1ebd93c..b280429 100644 --- a/tests/substack/test_from_markdown_features.py +++ b/tests/substack/test_from_markdown_features.py @@ -160,6 +160,15 @@ def test_blockquote(self): assert block["type"] == "blockquote" assert block["content"][0]["type"] == "paragraph" + def test_image_alt_resolves_backslash_escapes(self): + post = make_post() + post.from_markdown( + r'![find . -iname "\*taxes\*" \[a\_b\] C:\\dir \q](https://example.com/img.png)' + ) + attrs = body(post)[0]["content"][0]["attrs"] + # Escaped punctuation loses its backslash; "\q" is not an escape. + assert attrs["alt"] == r'find . -iname "*taxes*" [a_b] C:\dir \q' + def test_image(self): post = make_post() post.from_markdown("![alt](https://example.com/img.png)") diff --git a/tests/substack/test_markdown_export.py b/tests/substack/test_markdown_export.py index 6bc88fd..d1babf8 100644 --- a/tests/substack/test_markdown_export.py +++ b/tests/substack/test_markdown_export.py @@ -330,3 +330,23 @@ def test_api_export_rejects_malformed_draft_body(monkeypatch, draft_body): with pytest.raises(ValueError, match="Malformed draft body"): api.export_draft_to_markdown(42) + + +@pytest.mark.parametrize( + "alt", + [ + r"back\slash and ] bracket", + "an [unbalanced bracket", + r"literal \* and \\ and \]", + 'find . -iname "*taxes*"', + ], +) +def test_image_alt_text_survives_export_and_reimport(alt): + document = { + "type": "doc", + "content": [captioned_image("https://example.com/image.png", alt=alt)], + } + markdown, unsupported = document_to_markdown(document) + assert unsupported == [] + reimported = markdown_to_doc(markdown) + assert reimported[0]["content"][0]["attrs"]["alt"] == alt