Skip to content

Escape ampersands in image alt text and link titles - #780

Open
SwastikTripathi wants to merge 2 commits into
trentm:masterfrom
SwastikTripathi:fix/xml-escape-attr-ampersand
Open

SwastikTripathi wants to merge 2 commits into
trentm:masterfrom
SwastikTripathi:fix/xml-escape-attr-ampersand

Conversation

@SwastikTripathi

Copy link
Copy Markdown
Contributor

_xml_escape_attr computes the & escape and then throws it away:

escaped = _AMPERSAND_RE.sub('&', attr)

escaped = (attr
    .replace('"', '"')
    ...

The second assignment starts again from attr, so a bare & is never escaped. Its two callers show it:

>>> markdown2.markdown('![Tom & Jerry](x.png)')
'<p><img src="x.png" alt="Tom & Jerry" /></p>\n'
>>> markdown2.markdown('[a](http://x "AT&T")', safe_mode="escape")
'<p><a href="http://x" title="AT&T">a</a></p>\n'

Without safe_mode, titles only come out right (AT&amp;T) because the general ampersand pass escapes them later. Alt text is hashed before that pass, so it keeps the raw & in every mode, and in safe_mode titles are hashed too.

The fix chains the replacements onto the ampersand-escaped string. _AMPERSAND_RE already skips existing entities, so &copy; stays as it is.

Tests: new attr_ampersand_escape and attr_ampersand_escape_safe_mode tm-cases (alt text, an image title and a link title with & and &copy;). Both fail before the fix and pass after. python test.py otherwise has the same 14 failures as on master.

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