# SCRIPT: BH-HTML-10
# Builds the dark HTML edition of the paper from the same LaTeX source as the PDF.
# Numbers for equations, theorems, sections and citations are taken from the LaTeX .aux file and the
# bibliography order, so the HTML matches the PDF.
import re, sys, subprocess, base64, os
src, aux, out = sys.argv[1], sys.argv[2], sys.argv[3]
tex = open(src).read()
labels = {}
for m in re.finditer(r'\\newlabel\{([^}]*)\}\{\{([^}]*)\}', open(aux).read()):
labels[m.group(1)] = m.group(2)
bib = re.findall(r'\\bibitem\{([^}]*)\}', tex)
num = {k: i+1 for i, k in enumerate(bib)}
tex = re.sub(r'\\cite\{([^}]*)\}', lambda m: '[' + ', '.join(str(num[k.strip()]) for k in m.group(1).split(',')) + ']', tex)
tex = re.sub(r'\\eqref\{([^}]*)\}', lambda m: '(' + labels[m.group(1)] + ')', tex)
tex = re.sub(r'(?:Section|Appendix|Theorem|Proposition|Lemma|Figure)~\\ref\{([^}]*)\}',
lambda m: m.group(0).split('~')[0] + ' ' + labels[m.group(1)], tex)
tex = re.sub(r'\\ref\{([^}]*)\}', lambda m: labels[m.group(1)], tex)
# tag numbered display equations
def tag_env(m):
body = m.group(2); lab = re.search(r'\\label\{(eq:[^}]*)\}', body)
if lab: body = body.replace(lab.group(0), '').rstrip() + r'\qquad\qquad(%s)' % labels[lab.group(1)]
return m.group(1) + body + m.group(3)
tex = re.sub(r'(\\begin\{equation\})(.*?)(\\end\{equation\})', tag_env, tex, flags=re.S)
tex = tex.replace(r'\grade{', r'\textsc{').replace(r'\textcolor{mut}{\textup{\textsc{[#1]}}}', '#1')
tex = re.sub(r'\\textsc\{([^}]*)\}', lambda m: r'\textsc{[' + m.group(1) + ']}' if not m.group(1).startswith('[') else m.group(0), tex)
# bibliography -> numbered list
tex = re.sub(r'\\begin\{thebibliography\}\{99\}\\small', r'\\section*{References}\n\\begin{enumerate}', tex)
tex = tex.replace(r'\end{thebibliography}', r'\end{enumerate}')
tex = re.sub(r'\\bibitem\{[^}]*\}', r'\\item', tex)
tex = tex.replace(r'\noindent\textcolor{mut}{', r'\noindent{')
tex = tex.replace(r'\begin{abstract}', r'\begin{quote}\textbf{Abstract.} ').replace(r'\end{abstract}', r'\end{quote}')
tmp = out + '.pre.tex'; open(tmp, 'w').write(tex)
body = subprocess.run(['pandoc', tmp, '--mathjax', '--number-sections', '--wrap=none', '-t', 'html5'], capture_output=True, text=True, cwd=os.path.dirname(src))
sys.stderr.write(body.stderr[-2000:]); body=body.stdout
os.remove(tmp)
# appendix numbering: pandoc numbers appendix sections 11, 12 -> A, B
body = re.sub(r'', lambda m: '', body)
body = re.sub(r'