# This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2015

'''
Math extension for Python-Markdown
==================================

Adds support for displaying math formulas using [MathJax](http://www.mathjax.org/).

Author: 2015, Dmitry Shachnev <mitya57@gmail.com>.
'''

from __future__ import absolute_import

import markdown

class MathExtension(markdown.extensions.Extension):
    def __init__(self, *args, **kwargs):
        self.config = {
            'enable_dollar_delimiter': [False, 'Enable single-dollar delimiter'],
        }
        super(MathExtension, self).__init__(*args, **kwargs)

    def extendMarkdown(self, md, md_globals):
        def handle_match_inline(m):
            node = markdown.util.etree.Element('script')
            node.set('type', 'math/tex')
            node.text = markdown.util.AtomicString(m.group(3))
            return node

        def handle_match(m):
            node = markdown.util.etree.Element('script')
            node.set('type', 'math/tex; mode=display')
            node.text = markdown.util.AtomicString(m.group(3))
            if '\\begin' in m.group(2):
                node.text = markdown.util.AtomicString(m.group(2) +
                m.group(3) + m.group(4))
            return node

        configs = self.getConfigs()
        inlinemathpatterns = (
            markdown.inlinepatterns.Pattern(r'(?<!\\|\$)(\$)([^\$]+)(\$)'),  #  $...$
            markdown.inlinepatterns.Pattern(r'(?<!\\)(\\\()(.+?)(\\\))')     # \(...\)
        )
        mathpatterns = (
            markdown.inlinepatterns.Pattern(r'(?<!\\)(\$\$)([^\$]+)(\$\$)'), # $$...$$
            markdown.inlinepatterns.Pattern(r'(?<!\\)(\\\[)(.+?)(\\\])'),    # \[...\]
            markdown.inlinepatterns.Pattern(r'(?<!\\)(\\begin{[a-z]+\*?})(.+)(\\end{[a-z]+\*?})')
        )
        if not configs['enable_dollar_delimiter']:
            inlinemathpatterns = inlinemathpatterns[1:]
        for i, pattern in enumerate(inlinemathpatterns):
            pattern.handleMatch = handle_match_inline
            md.inlinePatterns.add('math-inline-%d' % i, pattern, '<escape')
        for i, pattern in enumerate(mathpatterns):
            pattern.handleMatch = handle_match
            md.inlinePatterns.add('math-%d' % i, pattern, '<escape')

def makeExtension(*args, **kwargs):
    return MathExtension(*args, **kwargs)

@@ -1046,16 +1046,60 @@
 splay')%0A
+            if '%5C%5Cbegin' in m.group(2):%0A    
         
@@ -1153,50 +1153,54 @@
 oup(
-3))%0A            if '%5C%5Cbegin' in m.group(2)
+2) + m.group(4) + m.group(5))%0A            else
 :%0A  
@@ -1264,51 +1264,9 @@
 oup(
-2) +%0A                m.group(3) + m.group(4
+3
 ))%0A 
@@ -1804,30 +1804,34 @@
 gin%7B
+(
 %5Ba-z%5D+
+?
 %5C*?
+)
 %7D)(.+
+?
 )(%5C%5Cend%7B
 %5Ba-z
@@ -1830,17 +1830,10 @@
 end%7B
-%5Ba-z%5D+%5C*?
+%5C3
 %7D)')

Make \end{XXX} match the correct environment name