import re import mistune from django.conf import settings from judge.utils.mathoid import MathoidMathParser mistune._pre_tags.append('latex') class MathInlineGrammar(mistune.InlineGrammar): block_math = re.compile(r'^\$\$(.*?)\$\$|^\\\[(.*?)\\\]', re.DOTALL) math = re.compile(r'^~(.*?)~|^\\\((.*?)\\\)', re.DOTALL) text = re.compile(r'^[\s\S]+?(?=[\\%s' % (tag, extra, text, tag) else: html = m.group(0) return self.renderer.inline_html(html) class MathRenderer(mistune.Renderer): def __init__(self, *args, **kwargs): if kwargs.pop('math', False) and settings.MATHOID_URL != False: self.mathoid = MathoidMathParser(kwargs.pop('math_engine', None) or 'svg') else: self.mathoid = None super(MathRenderer, self).__init__(*args, **kwargs) def block_math(self, math): if self.mathoid is None or not math: return r'\[%s\]' % mistune.escape(str(math)) return self.mathoid.display_math(math) def math(self, math): if self.mathoid is None or not math: return r'\(%s\)' % mistune.escape(str(math)) return self.mathoid.inline_math(math)