arithmatex.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. r"""
  2. Arithmatex.
  3. pymdownx.arithmatex
  4. Extension that preserves the following for MathJax use:
  5. ```
  6. $Equation$, \(Equation\)
  7. $$
  8. Display Equations
  9. $$
  10. \[
  11. Display Equations
  12. \]
  13. \begin{align}
  14. Display Equations
  15. \end{align}
  16. ```
  17. and `$Inline MathJax Equations$`
  18. Inline and display equations are converted to scripts tags. You can optionally generate previews.
  19. MIT license.
  20. Copyright (c) 2014 - 2017 Isaac Muse <isaacmuse@gmail.com>
  21. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  22. documentation files (the "Software"), to deal in the Software without restriction, including without limitation
  23. the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
  24. and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  25. The above copyright notice and this permission notice shall be included in all copies or substantial portions
  26. of the Software.
  27. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  28. TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  29. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  30. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  31. DEALINGS IN THE SOFTWARE.
  32. """
  33. from markdown import Extension
  34. from markdown.inlinepatterns import InlineProcessor
  35. from markdown.blockprocessors import BlockProcessor
  36. from markdown import util as md_util
  37. import xml.etree.ElementTree as etree
  38. from . import util
  39. import re
  40. RE_SMART_DOLLAR_INLINE = r'(?:(?<!\\)((?:\\{2})+)(?=\$)|(?<!\\)(\$)(?!\s)((?:\\.|[^\\$])+?)(?<!\s)(?:\$))'
  41. RE_DOLLAR_INLINE = r'(?:(?<!\\)((?:\\{2})+)(?=\$)|(?<!\\)(\$)((?:\\.|[^\\$])+?)(?:\$))'
  42. RE_BRACKET_INLINE = r'(?:(?<!\\)((?:\\{2})+?)(?=\\\()|(?<!\\)(\\\()((?:\\[^)]|[^\\])+?)(?:\\\)))'
  43. RE_DOLLAR_BLOCK = r'(?P<dollar>[$]{2})(?P<math>((?:\\.|[^\\])+?))(?P=dollar)'
  44. RE_TEX_BLOCK = r'(?P<math2>\\begin\{(?P<env>[a-z]+\*?)\}(?:\\.|[^\\])+?\\end\{(?P=env)\})'
  45. RE_BRACKET_BLOCK = r'\\\[(?P<math3>(?:\\[^\]]|[^\\])+?)\\\]'
  46. def _escape(txt):
  47. """Basic html escaping."""
  48. txt = txt.replace('&', '&amp;')
  49. txt = txt.replace('<', '&lt;')
  50. txt = txt.replace('>', '&gt;')
  51. txt = txt.replace('"', '&quot;')
  52. return txt
  53. def _inline_mathjax_format(math, preview=False):
  54. """Inline math formatter."""
  55. if preview:
  56. el = etree.Element('span')
  57. pre = etree.SubElement(el, 'span', {'class': 'MathJax_Preview'})
  58. pre.text = md_util.AtomicString(math)
  59. script = etree.SubElement(el, 'script', {'type': 'math/tex'})
  60. script.text = md_util.AtomicString(math)
  61. else:
  62. el = etree.Element('script', {'type': 'math/tex'})
  63. el.text = md_util.AtomicString(math)
  64. return el
  65. def _fence_mathjax_format(math, preview=False):
  66. """Block math formatter."""
  67. text = ''
  68. if preview:
  69. text += (
  70. '<div>\n' +
  71. '<div class="MathJax_Preview">\n' +
  72. _escape(math) +
  73. '\n</div>\n'
  74. )
  75. text += (
  76. '<script type="math/tex; mode=display">\n' +
  77. math +
  78. '\n</script>\n'
  79. )
  80. if preview:
  81. text += '</div>'
  82. return text
  83. # Formatters usable with InlineHilite
  84. def inline_mathjax_preview_format(math, language='math', class_name='arithmatex', md=None):
  85. """Inline math formatter with preview."""
  86. return _inline_mathjax_format(math, True)
  87. def inline_mathjax_format(math, language='math', class_name='arithmatex', md=None):
  88. """Inline math formatter."""
  89. return _inline_mathjax_format(math, False)
  90. def inline_generic_format(math, language='math', class_name='arithmatex', md=None, wrap='\\(%s\\)'):
  91. """Inline generic formatter."""
  92. el = etree.Element('span', {'class': class_name})
  93. el.text = md_util.AtomicString(wrap % math)
  94. return el
  95. # Formatters usable with SuperFences
  96. def fence_mathjax_preview_format(math, language='math', class_name='arithmatex', options=None, md=None, **kwargs):
  97. """Block MathJax formatter with preview."""
  98. return _fence_mathjax_format(math, True)
  99. def fence_mathjax_format(math, language='math', class_name='arithmatex', options=None, md=None, **kwargs):
  100. """Block MathJax formatter."""
  101. return _fence_mathjax_format(math, False)
  102. def fence_generic_format(
  103. math, language='math', class_name='arithmatex', options=None, md=None, wrap='\\[\n%s\n\\]', **kwargs
  104. ):
  105. """Generic block formatter."""
  106. return '<div class="%s">%s</div>' % (class_name, (wrap % math))
  107. class InlineArithmatexPattern(InlineProcessor):
  108. """Arithmatex inline pattern handler."""
  109. ESCAPED_BSLASH = '%s%s%s' % (md_util.STX, ord('\\'), md_util.ETX)
  110. def __init__(self, pattern, config):
  111. """Initialize."""
  112. # Generic setup
  113. self.generic = config.get('generic', False)
  114. wrap = config.get('tex_inline_wrap', ["\\(", "\\)"])
  115. self.wrap = wrap[0] + '%s' + wrap[1]
  116. # Default setup
  117. self.preview = config.get('preview', True)
  118. InlineProcessor.__init__(self, pattern)
  119. def handleMatch(self, m, data):
  120. """Handle notations and switch them to something that will be more detectable in HTML."""
  121. # Handle escapes
  122. escapes = m.group(1)
  123. if not escapes:
  124. escapes = m.group(4)
  125. if escapes:
  126. return escapes.replace('\\\\', self.ESCAPED_BSLASH), m.start(0), m.end(0)
  127. # Handle Tex
  128. math = m.group(3)
  129. if not math:
  130. math = m.group(6)
  131. if self.generic:
  132. return inline_generic_format(math, wrap=self.wrap), m.start(0), m.end(0)
  133. else:
  134. return _inline_mathjax_format(math, self.preview), m.start(0), m.end(0)
  135. class BlockArithmatexProcessor(BlockProcessor):
  136. """MathJax block processor to find $$MathJax$$ content."""
  137. def __init__(self, pattern, config, md):
  138. """Initialize."""
  139. # Generic setup
  140. self.generic = config.get('generic', False)
  141. wrap = config.get('tex_block_wrap', ['\\[', '\\]'])
  142. self.wrap = wrap[0] + '%s' + wrap[1]
  143. # Default setup
  144. self.preview = config.get('preview', False)
  145. self.match = None
  146. self.pattern = re.compile(pattern)
  147. BlockProcessor.__init__(self, md.parser)
  148. def test(self, parent, block):
  149. """Return 'True' for future Python Markdown block compatibility."""
  150. self.match = self.pattern.match(block) if self.pattern is not None else None
  151. return self.match is not None
  152. def mathjax_output(self, parent, math):
  153. """Default MathJax output."""
  154. if self.preview:
  155. grandparent = parent
  156. parent = etree.SubElement(grandparent, 'div')
  157. preview = etree.SubElement(parent, 'div', {'class': 'MathJax_Preview'})
  158. preview.text = md_util.AtomicString(math)
  159. el = etree.SubElement(parent, 'script', {'type': 'math/tex; mode=display'})
  160. el.text = md_util.AtomicString(math)
  161. def generic_output(self, parent, math):
  162. """Generic output."""
  163. el = etree.SubElement(parent, 'div', {'class': 'arithmatex'})
  164. el.text = md_util.AtomicString(self.wrap % math)
  165. def run(self, parent, blocks):
  166. """Find and handle block content."""
  167. blocks.pop(0)
  168. math = self.match.group('math')
  169. if not math:
  170. math = self.match.group('math2')
  171. if not math:
  172. math = self.match.group('math3')
  173. if self.generic:
  174. self.generic_output(parent, math)
  175. else:
  176. self.mathjax_output(parent, math)
  177. return True
  178. class ArithmatexExtension(Extension):
  179. """Adds delete extension to Markdown class."""
  180. def __init__(self, *args, **kwargs):
  181. """Initialize."""
  182. self.config = {
  183. 'tex_inline_wrap': [
  184. ["\\(", "\\)"],
  185. "Wrap inline content with the provided text ['open', 'close'] - Default: ['', '']"
  186. ],
  187. 'tex_block_wrap': [
  188. ["\\[", "\\]"],
  189. "Wrap blick content with the provided text ['open', 'close'] - Default: ['', '']"
  190. ],
  191. "smart_dollar": [True, "Use Arithmatex's smart dollars - Default True"],
  192. "block_syntax": [
  193. ['dollar', 'square', 'begin'],
  194. 'Enable block syntax: "dollar" ($$...$$), "square" (\\[...\\]), and '
  195. '"begin" (\\begin{env}...\\end{env}). - Default: ["dollar", "square", "begin"]'
  196. ],
  197. "inline_syntax": [
  198. ['dollar', 'round'],
  199. 'Enable block syntax: "dollar" ($$...$$), "bracket" (\\(...\\)) '
  200. ' - Default: ["dollar", "round"]'
  201. ],
  202. 'generic': [False, "Output in a generic format for non MathJax libraries - Default: False"],
  203. 'preview': [
  204. True,
  205. "Insert a preview for scripts. - Default: False"
  206. ]
  207. }
  208. super(ArithmatexExtension, self).__init__(*args, **kwargs)
  209. def extendMarkdown(self, md):
  210. """Extend the inline and block processor objects."""
  211. md.registerExtension(self)
  212. util.escape_chars(md, ['$'])
  213. config = self.getConfigs()
  214. # Inline patterns
  215. allowed_inline = set(config.get('inline_syntax', ['dollar', 'round']))
  216. smart_dollar = config.get('smart_dollar', True)
  217. inline_patterns = []
  218. if 'dollar' in allowed_inline:
  219. inline_patterns.append(RE_SMART_DOLLAR_INLINE if smart_dollar else RE_DOLLAR_INLINE)
  220. if 'round' in allowed_inline:
  221. inline_patterns.append(RE_BRACKET_INLINE)
  222. if inline_patterns:
  223. inline = InlineArithmatexPattern('(?:%s)' % '|'.join(inline_patterns), config)
  224. md.inlinePatterns.register(inline, 'arithmatex-inline', 189.9)
  225. # Block patterns
  226. allowed_block = set(config.get('block_syntax', ['dollar', 'square', 'begin']))
  227. block_pattern = []
  228. if 'dollar' in allowed_block:
  229. block_pattern.append(RE_DOLLAR_BLOCK)
  230. if 'square' in allowed_block:
  231. block_pattern.append(RE_BRACKET_BLOCK)
  232. if 'begin' in allowed_block:
  233. block_pattern.append(RE_TEX_BLOCK)
  234. if block_pattern:
  235. block = BlockArithmatexProcessor(r'(?s)^(?:%s)[ ]*$' % '|'.join(block_pattern), config, md)
  236. md.parser.blockprocessors.register(block, "arithmatex-block", 79.9)
  237. def makeExtension(*args, **kwargs):
  238. """Return extension."""
  239. return ArithmatexExtension(*args, **kwargs)