CAT-SOOP is a flexible, programmable learning management system based on the Python programming language. https://catsoop.mit.edu
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

69 lines
2.4 KiB

  1. # This file is part of CAT-SOOP
  2. # Copyright (c) 2011-2020 by The CAT-SOOP Developers <catsoop-dev@mit.edu>
  3. #
  4. # This program is free software: you can redistribute it and/or modify it under
  5. # the terms of the GNU Affero General Public License as published by the Free
  6. # Software Foundation, either version 3 of the License, or (at your option) any
  7. # later version.
  8. #
  9. # This program is distributed in the hope that it will be useful, but WITHOUT
  10. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  11. # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
  12. # details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. """CAT-SOOP Math Mode Extension for PyMarkdown"""
  17. from markdown.extensions import Extension
  18. from markdown.inlinepatterns import HtmlInlineProcessor, SimpleTextInlineProcessor
  19. _nodoc = {
  20. "Extension",
  21. "HtmlInlineProcessor",
  22. "SimpleTextInlineProcessor",
  23. "absolute_import",
  24. "unicode_literals",
  25. }
  26. _MATH_RE = r"(^|[^\\])(\$)((?:\\\$|[^$])*)\2"
  27. _DMATH_RE = r"(^|[^\\])(\$\$)(.*?)\2"
  28. _ESCAPED_DOLLAR_RE = r"\\(\$)"
  29. class RawHtmlInlineProcessor(HtmlInlineProcessor):
  30. """A subclass of `catsoop.thirdparty.markdown.inlinepattern.HtmlInlineProcessor`
  31. used to store raw inline html and return a placeholder."""
  32. def __init__(self, endtag, *args, **kwargs):
  33. self._hz_tag = endtag
  34. HtmlInlineProcessor.__init__(self, *args, **kwargs)
  35. def handleMatch(self, m, data):
  36. pre = m.group(1)
  37. body = self.unescape(m.group(3))
  38. rawhtml = "%(pre)s<%(tag)s>%(body)s</%(tag)s>" % {
  39. "tag": self._hz_tag,
  40. "body": body,
  41. "pre": pre,
  42. }
  43. place_holder = self.md.htmlStash.store(rawhtml)
  44. return place_holder, m.start(0), m.end(0)
  45. class MathExtension(Extension):
  46. """The CAT-SOOP math extension to Markdown."""
  47. def extendMarkdown(self, md):
  48. """ Modify inline patterns."""
  49. e = md.inlinePatterns.get_index_for_name("entity")
  50. md.inlinePatterns.register(
  51. RawHtmlInlineProcessor("displaymath", _DMATH_RE, md), "catsoop_dmath", e + 3
  52. )
  53. md.inlinePatterns.register(
  54. RawHtmlInlineProcessor("math", _MATH_RE, md), "catsoop_math", e + 2
  55. )
  56. md.inlinePatterns.register(
  57. SimpleTextInlineProcessor(_ESCAPED_DOLLAR_RE), "catsoop_emath", e + 1
  58. )