Skip to content

Resolve backslash escapes in image alt text - #95

Open
MattFisher wants to merge 1 commit into
ma2za:mainfrom
MattFisher:fix/image-alt-plain-text
Open

MattFisher wants to merge 1 commit into
ma2za:mainfrom
MattFisher:fix/image-alt-plain-text

Conversation

@MattFisher

Copy link
Copy Markdown
Contributor

Backslash escapes in image alt text reach Substack with the backslash still in place, and alt text containing a backslash or square bracket does not survive export and re-import. This PR fixes both.

The problem

markdown-it stores an image's alt text as raw Markdown source, and _captioned_image() uses it as-is. So:

![find . -iname "\*taxes\*"](image.png)

is stored with the alt text find . -iname "\*taxes\*" instead of find . -iname "*taxes*". The escapes are needed in the source, because other Markdown tools read unescaped *…* in alt text as emphasis and drop the asterisks.

The same thing breaks the export round trip. mdexport already escapes \ and ] in alt text, but reading that Markdown back keeps the escapes:

Alt text in the draft Exported as Read back as
back\slash and ] bracket back\\slash and \] bracket back\\slash and \] bracket
an [unbalanced bracket an [unbalanced bracket not recognised as an image

The change

  • mdrender: resolve backslash escapes (a backslash before ASCII punctuation) when building the image node.
  • mdexport: escape [ as well as \ and ], so an unbalanced bracket can no longer stop the line being read as an image.

Alt text without backslashes is unaffected. Unescaped markup such as *word* is still kept literally, as it is today.

Testing

  • New test in test_from_markdown_features.py for escapes on import, including that \q (not an escape) is left alone.
  • New round-trip test in test_markdown_export.py for alt text containing backslashes, ], an unbalanced [, and literal \*.
  • pytest -q -m "not live" --strict-markers: 296 passed.
  • Checked against a real draft: alt text written with \* in Markdown was stored without backslashes.

Note

#94 touches the lines next to this one in mdrender.py, so whichever of the two is merged second will need a small rebase. I'm happy to do that.

🤖 Generated with Claude Code

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 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant