html_entity.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """
  2. HTML Entities for reStructured Text
  3. ===================================
  4. Allows user to use HTML entities (©, •, etc.) in RST documents.
  5. Usage:
  6. :html_entity:`copy`
  7. :html_entity:`149`
  8. :html_entity:`#149`
  9. """
  10. from __future__ import unicode_literals
  11. from docutils import nodes, utils
  12. from docutils.parsers.rst import roles
  13. from pelican.readers import PelicanHTMLTranslator
  14. import six
  15. class html_entity(nodes.Inline, nodes.Node):
  16. # Subclassing Node directly since TextElement automatically appends the escaped element
  17. def __init__(self, rawsource, text):
  18. self.rawsource = rawsource
  19. self.text = text
  20. self.children = []
  21. self.attributes = {}
  22. def astext(self):
  23. return self.text
  24. def entity_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
  25. text = utils.unescape(text)
  26. entity_code = text
  27. try:
  28. entity_code = "#{}".format(six.u(int(entity_code)))
  29. except ValueError:
  30. pass
  31. entity_code = "&{};".format(entity_code)
  32. return [html_entity(text, entity_code)], []
  33. def register():
  34. roles.register_local_role('html_entity', entity_role)
  35. PelicanHTMLTranslator.visit_html_entity = lambda self, node: self.body.append(node.astext())
  36. PelicanHTMLTranslator.depart_html_entity = lambda self, node: None