Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion substack/mdexport.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 8 additions & 1 deletion substack/mdrender.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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
Expand Down
9 changes: 9 additions & 0 deletions tests/substack/test_from_markdown_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)")
Expand Down
20 changes: 20 additions & 0 deletions tests/substack/test_markdown_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading