fufa/chatgpt
0
1# This program is written by: https://github.com/polarwinkel/mdtex2html2 3from latex2mathml.converter import convert as tex2mathml4import re5 6incomplete = '<font style="color:orange;" class="tooltip">⚠<span class="tooltiptext">formula incomplete</span></font>'7convError = '<font style="color:red" class="tooltip">⚠<span class="tooltiptext">LaTeX-convert-error</span></font>'8 9def convert(mdtex, extensions=[], splitParagraphs=True):10 ''' converts recursively the Markdown-LaTeX-mixture to HTML with MathML '''11 found = False12 # handle all paragraphs separately (prevents aftereffects)13 if splitParagraphs:14 parts = re.split("\n\n", mdtex)15 result = ''16 for part in parts:17 result += convert(part, extensions, splitParagraphs=False)18 return result19 # find first $$-formula:20 parts = re.split('\${2}', mdtex, 2)21 if len(parts)>1:22 found = True23 result = convert(parts[0], extensions, splitParagraphs=False)+'\n'24 try:25 result += '<div class="blockformula">'+tex2mathml(parts[1])+'</div>\n'26 except:27 result += '<div class="blockformula">'+convError+'</div>'28 if len(parts)==3:29 result += convert(parts[2], extensions, splitParagraphs=False)30 else:31 result += '<div class="blockformula">'+incomplete+'</div>'32 # else find first $-formulas:33 else:34 parts = re.split('\${1}', mdtex, 2)35 if len(parts)>1 and not found:36 found = True37 try:38 mathml = tex2mathml(parts[1])39 except:40 mathml = convError41 if parts[0].endswith('\n\n') or parts[0]=='': # make sure textblock starts before formula!42 parts[0]=parts[0]+'​'43 if len(parts)==3:44 result = convert(parts[0]+mathml+parts[2], extensions, splitParagraphs=False)45 else:46 result = convert(parts[0]+mathml+incomplete, extensions, splitParagraphs=False)47 # else find first \[..\]-equation:48 else:49 parts = re.split(r'\\\[', mdtex, 1)50 if len(parts)>1 and not found:51 found = True52 result = convert(parts[0], extensions, splitParagraphs=False)+'\n'53 parts = re.split(r'\\\]', parts[1], 1)54 try:55 result += '<div class="blockformula">'+tex2mathml(parts[0])+'</div>\n'56 except:57 result += '<div class="blockformula">'+convError+'</div>'58 if len(parts)==2:59 result += convert(parts[1], extensions, splitParagraphs=False)60 else:61 result += '<div class="blockformula">'+incomplete+'</div>'62 # else find first \(..\)-equation:63 else:64 parts = re.split(r'\\\(', mdtex, 1)65 if len(parts)>1 and not found:66 found = True67 subp = re.split(r'\\\)', parts[1], 1)68 try:69 mathml = tex2mathml(subp[0])70 except:71 mathml = convError72 if parts[0].endswith('\n\n') or parts[0]=='': # make sure textblock starts before formula!73 parts[0]=parts[0]+'​'74 if len(subp)==2:75 result = convert(parts[0]+mathml+subp[1], extensions, splitParagraphs=False)76 else:77 result = convert(parts[0]+mathml+incomplete, extensions, splitParagraphs=False)78 if not found:79 result = mdtex80 return result81 