restructured_text.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import os
  2. from functools import lru_cache
  3. from docutils.core import publish_parts
  4. from .markdown import Markdown, remove_indentation
  5. class ReStructuredText(Markdown):
  6. def __init__(self, content: str = '') -> None:
  7. """ReStructuredText
  8. Renders ReStructuredText onto the page.
  9. :param content: the ReStructuredText content to be displayed
  10. """
  11. super().__init__(content=content)
  12. def _handle_content_change(self, content: str) -> None:
  13. html = prepare_content(content)
  14. if self._props.get('innerHTML') != html:
  15. self._props['innerHTML'] = html
  16. self.update()
  17. @lru_cache(maxsize=int(os.environ.get('RST_CONTENT_CACHE_SIZE', '1000')))
  18. def prepare_content(content: str) -> str:
  19. """Render ReStructuredText content to HTML."""
  20. html = publish_parts(
  21. remove_indentation(content),
  22. writer_name='html4',
  23. settings_overrides={'syntax_highlight': 'short'},
  24. )
  25. return html["html_body"].replace('<div class="document"', '<div class="codehilite"')