shorthandimgs.py 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. #-*- coding: utf-8 -*-
  2. import re
  3. import markdown
  4. from markdown.inlinepatterns import LinkPattern
  5. from misago.utils.strings import html_escape
  6. from misago.utils.urls import is_inner, clean_inner
  7. from markdown.util import etree
  8. IMAGES_RE = r'\!(\s?)\((<.*?>|([^\)]*))\)'
  9. class ShorthandImagesExtension(markdown.Extension):
  10. def extendMarkdown(self, md):
  11. md.registerExtension(self)
  12. md.inlinePatterns.add('mi_shorthand_imgs',
  13. ShorthandImagePattern(IMAGES_RE, md),
  14. '_end')
  15. class ShorthandImagePattern(LinkPattern):
  16. def handleMatch(self, m):
  17. img_src = m.groups()[2].strip()
  18. if is_inner(img_src):
  19. img_src = self.sanitize_url(clean_inner(img_src))
  20. if img_src:
  21. a = etree.Element("a")
  22. a.set('href', img_src)
  23. a.set('rel', 'nofollow')
  24. a.set('target', '_blank')
  25. img = etree.SubElement(a, "img")
  26. img.set('src', img_src)
  27. img.set('alt', img_src)
  28. return a