Browse Source

Replace Markdown-generated <img> elements with <a> links

merge-requests/64/head
wirelyre 6 years ago
committed by Deimos
parent
commit
7d2e41f20f
  1. 9
      tildes/tests/test_markdown.py
  2. 19
      tildes/tildes/lib/markdown.py

9
tildes/tests/test_markdown.py

@ -356,3 +356,12 @@ def test_group_ref_inside_code_ignored():
processed = convert_markdown_to_safe_html(markdown)
assert "<a" not in processed
def test_image_syntax_ignored():
"""Ensure inline image syntax is treated as a link."""
markdown = "An exclamation mark preceding a ![link](url)."
processed = convert_markdown_to_safe_html(markdown)
assert "!<a" in processed
assert "img" not in processed

19
tildes/tildes/lib/markdown.py

@ -105,6 +105,8 @@ BAD_ORDERED_LIST_REGEX = re.compile(
r"\.\s" # Followed by a period and a space
)
STRIP_IMAGE_ELEMENTS_REGEX = re.compile(r'<img src="([^"<>]*?)" alt="([^"<>]*?)" />')
@histogram_timer("markdown_processing")
def convert_markdown_to_safe_html(markdown: str) -> str:
@ -177,6 +179,9 @@ def postprocess_markdown_html(html: str) -> str:
# apply syntax highlighting to code blocks
html = apply_syntax_highlighting(html)
# replace <img> elements that were generated by `![ ]( )` Markdown syntax
html = strip_image_elements(html)
return html
@ -223,6 +228,20 @@ def apply_syntax_highlighting(html: str) -> str:
return html
def strip_image_elements(html: str) -> str:
"""Replace all <img> elements generated from Markdown with <a>.
The Markdown syntax `![alt text](/url)` creates an image tag. Except for the leading
`!`, the syntax is identical to that of links. We can pretend we never parsed it as
a Markdown image by replacing all image tags with links.
<img src="/url" alt="alt text" />
==>
!<a href="/url">alt text</a>
"""
return STRIP_IMAGE_ELEMENTS_REGEX.sub(r'!<a href="\1">\2</a>', html)
class LinkifyFilter(Filter):
"""html5lib Filter to convert custom text patterns to links.

Loading…
Cancel
Save