legacy_attrs.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """
  2. Python Markdown
  3. A Python implementation of John Gruber's Markdown.
  4. Documentation: https://python-markdown.github.io/
  5. GitHub: https://github.com/Python-Markdown/markdown/
  6. PyPI: https://pypi.org/project/Markdown/
  7. Started by Manfred Stienstra (http://www.dwerg.net/).
  8. Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
  9. Currently maintained by Waylan Limberg (https://github.com/waylan),
  10. Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
  11. Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
  12. Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
  13. Copyright 2004 Manfred Stienstra (the original version)
  14. License: BSD (see LICENSE.md for details).
  15. Legacy Attributes Extension
  16. ===========================
  17. An extension to Python Markdown which implements legacy attributes.
  18. Prior to Python-Markdown version 3.0, the Markdown class had an `enable_attributes`
  19. keyword which was on by default and provided for attributes to be defined for elements
  20. using the format `{@key=value}`. This extension is provided as a replacement for
  21. backward compatability. New documents should be authored using attr_lists. However,
  22. numerious documents exist which have been using the old attribute format for many
  23. years. This extension can be used to continue to render those documents correctly.
  24. """
  25. import re
  26. from markdown.treeprocessors import Treeprocessor, isString
  27. from markdown.extensions import Extension
  28. ATTR_RE = re.compile(r'\{@([^\}]*)=([^\}]*)}') # {@id=123}
  29. class LegacyAttrs(Treeprocessor):
  30. def run(self, doc):
  31. """Find and set values of attributes ({@key=value}). """
  32. for el in doc.iter():
  33. alt = el.get('alt', None)
  34. if alt is not None:
  35. el.set('alt', self.handleAttributes(el, alt))
  36. if el.text and isString(el.text):
  37. el.text = self.handleAttributes(el, el.text)
  38. if el.tail and isString(el.tail):
  39. el.tail = self.handleAttributes(el, el.tail)
  40. def handleAttributes(self, el, txt):
  41. """ Set attributes and return text without definitions. """
  42. def attributeCallback(match):
  43. el.set(match.group(1), match.group(2).replace('\n', ' '))
  44. return ATTR_RE.sub(attributeCallback, txt)
  45. class LegacyAttrExtension(Extension):
  46. def extendMarkdown(self, md):
  47. md.treeprocessors.register(LegacyAttrs(md), 'legacyattrs', 15)
  48. def makeExtension(**kwargs): # pragma: no cover
  49. return LegacyAttrExtension(**kwargs)