Ricci4-Axiomatic / tex2html.js
encryptidai's picture
Publish Ricci4 axiomatic paper
4ef1e8b verified
Raw History Blame Contribute Delete
32.8 kB
// Render the paper TeX in the browser. Math is left for MathJax.
(function (root) {
'use strict';
var ESC = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' };
function esc(s) {
return String(s).replace(/[&<>"]/g, function (c) { return ESC[c]; });
}
// Filled from the document preamble. Do not keep a stock macro set:
// a shorter name must not rewrite a longer command from another paper.
var MACROS = {};
var MACRO_RE = null;
var ENVS = {};
function rebuildMacroRe() {
var names = Object.keys(MACROS).sort(function (a, b) { return b.length - a.length; });
MACRO_RE = names.length
? new RegExp('\\\\(' + names.join('|') + ')(?![A-Za-z])', 'g')
: null;
}
function expandMacros(s) {
if (!MACRO_RE) return s;
return s.replace(MACRO_RE, function (m, name) { return MACROS[name]; });
}
function expandInputs(src, files) {
files = files || {};
var guard = 0;
while (guard++ < 20) {
var m = /\\input\s*\{([^}]+)\}/.exec(src);
if (!m) return src;
var key = m[1].trim();
var body = files[key];
if (body == null && key.slice(-4) !== '.tex') body = files[key + '.tex'];
if (body == null) body = files[key.replace(/\.tex$/, '')];
if (body == null) throw new Error('missing input: ' + key);
src = src.slice(0, m.index) + '\n' + body + '\n' + src.slice(m.index + m[0].length);
}
throw new Error('too many \\\\input expansions');
}
function parseNewcommands(src) {
MACROS = {};
var re = /\\newcommand\s*\{\\([A-Za-z]+)\}/g;
var m;
while ((m = re.exec(src))) {
var p = m.index + m[0].length;
if (src[p] === '[') continue;
var body = readBrace(src, p);
MACROS[m[1]] = body.text;
re.lastIndex = body.end;
}
rebuildMacroRe();
}
function parseNewtheorems(preamble) {
ENVS = {};
var style = 'plain';
var i = 0;
while (i < preamble.length) {
var rest = preamble.slice(i);
var st = /\\theoremstyle\s*\{([^}]*)\}/.exec(rest);
var nt = /\\newtheorem\s*\{([A-Za-z]+)\}/.exec(rest);
var nextStyle = st ? st.index : -1;
var nextThm = nt ? nt.index : -1;
if (nextStyle < 0 && nextThm < 0) break;
if (nextThm < 0 || (nextStyle >= 0 && nextStyle < nextThm)) {
style = st[1].trim();
i += nextStyle + st[0].length;
continue;
}
var p = i + nextThm + nt[0].length;
var shared = null;
if (preamble[p] === '[') {
var sh = readBracket(preamble, p);
shared = sh.text.trim();
p = sh.end;
}
var title = readBrace(preamble, p);
p = title.end;
var within = null;
if (preamble[p] === '[') {
var w = readBracket(preamble, p);
within = w.text.trim();
p = w.end;
}
ENVS[nt[1]] = { title: title.text, shared: shared, within: shared ? null : within, style: style };
i = p;
}
}
function stripComments(s) {
var out = '';
for (var i = 0; i < s.length; i++) {
if (s[i] === '\\') {
out += s[i];
if (i + 1 < s.length) out += s[++i];
continue;
}
if (s[i] === '%') {
while (i < s.length && s[i] !== '\n') i++;
out += '\n';
continue;
}
out += s[i];
}
return out;
}
function readBrace(s, i) {
if (s[i] !== '{') throw new Error('expected { at ' + i + ': ' + JSON.stringify(s.slice(i, i + 60)));
var depth = 0;
for (var j = i; j < s.length; j++) {
if (s[j] === '\\') { j++; continue; }
if (s[j] === '{') depth++;
else if (s[j] === '}') {
depth--;
if (depth === 0) return { text: s.slice(i + 1, j), end: j + 1 };
}
}
throw new Error('unclosed { at ' + i);
}
function readBracket(s, i) {
if (s[i] !== '[') return null;
var depth = 0, brace = 0;
for (var j = i; j < s.length; j++) {
if (s[j] === '\\') { j++; continue; }
if (s[j] === '{') brace++;
else if (s[j] === '}') brace--;
else if (brace === 0 && s[j] === '[') depth++;
else if (brace === 0 && s[j] === ']') {
depth--;
if (depth === 0) return { text: s.slice(i + 1, j), end: j + 1 };
}
}
throw new Error('unclosed [ at ' + i);
}
function grab(s, name) {
var token = '\\' + name + '{';
var i = s.indexOf(token);
if (i < 0) return '';
return readBrace(s, i + token.length - 1).text;
}
function extractAll(src) {
var math = [];
var out = '';
var i = 0;
function push(info) {
var n = math.length;
math.push(info);
return '\uE000' + n + '\uE001';
}
while (i < src.length) {
if (src.startsWith('\\begin{equation', i)) {
var star = src.startsWith('\\begin{equation*}', i);
var open = star ? '\\begin{equation*}' : '\\begin{equation}';
var close = star ? '\\end{equation*}' : '\\end{equation}';
var start = i + open.length;
var end = src.indexOf(close, start);
if (end < 0) throw new Error('unclosed equation');
var body = src.slice(start, end);
var id = null;
body = body.replace(/\\label\{([^}]*)\}/, function (_, lab) { id = lab; return ''; });
out += push({ display: true, tex: expandMacros(body.trim()), id: id, numbered: !star });
i = end + close.length;
continue;
}
if (src.startsWith('\\[', i)) {
var endD = src.indexOf('\\]', i + 2);
if (endD < 0) throw new Error('unclosed \\[');
out += push({ display: true, tex: expandMacros(src.slice(i + 2, endD).trim()), id: null, numbered: false });
i = endD + 2;
continue;
}
if (src[i] === '\\') {
out += src[i];
if (i + 1 < src.length) out += src[++i];
i++;
continue;
}
if (src[i] === '$') {
var j = i + 1;
while (j < src.length) {
if (src[j] === '\\') { j += 2; continue; }
if (src[j] === '$') break;
j++;
}
if (j >= src.length) throw new Error('unclosed $');
out += push({ display: false, tex: expandMacros(src.slice(i + 1, j)), id: null, numbered: false });
i = j + 1;
continue;
}
out += src[i];
i++;
}
return { text: out, math: math };
}
function findEnd(s, i, name) {
var depth = 1;
var open = '\\begin{' + name + '}';
var close = '\\end{' + name + '}';
var j = i;
while (j < s.length) {
if (s.startsWith(open, j)) { depth++; j += open.length; continue; }
if (s.startsWith(close, j)) {
depth--;
if (depth === 0) return { body: s.slice(i, j), end: j + close.length };
j += close.length;
continue;
}
if (s[j] === '\\') { j += 2; continue; }
j++;
}
throw new Error('missing \\end{' + name + '}');
}
function readBegin(s, i) {
var m = /^\\begin\{([^}]+)\}/.exec(s.slice(i));
if (!m) throw new Error('bad begin at ' + i);
var j = i + m[0].length;
var opt = null;
if (s[j] === '[') {
var b = readBracket(s, j);
opt = b.text;
j = b.end;
}
return { name: m[1], opt: opt, next: j };
}
function takeLabel(s) {
var m = /^\s*\\label\{([^}]*)\}/.exec(s);
if (!m) return { id: null, rest: s };
return { id: m[1], rest: s.slice(m[0].length) };
}
function splitItems(s) {
var items = [];
var buf = '';
var env = 0;
var brace = 0;
var started = false;
function push() {
if (!started) return;
var raw = buf;
var label = null;
var t = raw.replace(/^\s+/, '');
if (t[0] === '[') {
var b = readBracket(t, 0);
label = b.text;
t = t.slice(b.end);
}
items.push({ label: label, text: t });
buf = '';
}
for (var i = 0; i < s.length; i++) {
if (s[i] === '\\' && env === 0 && brace === 0 && s.startsWith('\\item', i) && !/[a-zA-Z]/.test(s[i + 5] || '')) {
push();
started = true;
i += 4;
continue;
}
if (s.startsWith('\\begin{', i)) env++;
else if (s.startsWith('\\end{', i)) env--;
if (s[i] === '\\') {
buf += s[i];
if (i + 1 < s.length) buf += s[++i];
continue;
}
if (s[i] === '{') brace++;
else if (s[i] === '}') brace--;
buf += s[i];
}
push();
return items;
}
function splitRows(s) {
var rows = [];
var cur = '';
var brace = 0;
for (var i = 0; i < s.length; i++) {
if (s[i] === '\\' && s[i + 1] === '\\' && brace === 0) {
rows.push(cur);
cur = '';
i++;
continue;
}
if (s[i] === '\\') {
cur += s[i];
if (i + 1 < s.length) cur += s[++i];
continue;
}
if (s[i] === '{') brace++;
else if (s[i] === '}') brace--;
cur += s[i];
}
if (cur.trim()) rows.push(cur);
return rows;
}
function splitCells(s) {
var cells = [];
var cur = '';
var brace = 0;
for (var i = 0; i < s.length; i++) {
if (s[i] === '&' && brace === 0) {
cells.push(cur);
cur = '';
continue;
}
if (s[i] === '\\') {
cur += s[i];
if (i + 1 < s.length) cur += s[++i];
continue;
}
if (s[i] === '{') brace++;
else if (s[i] === '}') brace--;
cur += s[i];
}
cells.push(cur);
return cells;
}
function parseTabular(body) {
var rows = [];
splitRows(body).forEach(function (raw) {
var rule = false;
var t = raw.trim();
if (!t) return;
if (t === '\\hline') {
if (rows.length) rows[rows.length - 1].ruleAfter = true;
else rows.push({ ruleBefore: true, cells: [], ruleAfter: false });
return;
}
if (t.startsWith('\\hline')) {
rule = true;
t = t.replace(/^\\hline\s*/, '');
}
if (!t) {
if (rows.length && rule) rows[rows.length - 1].ruleAfter = true;
return;
}
var cells = splitCells(t).map(function (c) {
var m = /^\\multicolumn\{(\d+)\}\{[^}]*\}\{([\s\S]*)\}$/.exec(c.trim());
if (m) return { span: +m[1], text: m[2] };
return { span: 1, text: c.trim() };
});
rows.push({ ruleBefore: rule, ruleAfter: false, cells: cells });
});
return rows;
}
function listKind(name, opt) {
if (name === 'itemize') return 'bullet';
if (name === 'description') return 'desc';
var spec = '';
if (opt) {
var m = /label\s*=\s*([^,\]]+)/.exec(opt);
if (m) spec = m[1].trim();
}
return spec || 'decimal';
}
function roman(n) {
var map = [[100, 'c'], [90, 'xc'], [50, 'l'], [40, 'xl'], [10, 'x'], [9, 'ix'], [5, 'v'], [4, 'iv'], [1, 'i']];
var s = '';
map.forEach(function (pair) {
while (n >= pair[0]) { s += pair[1]; n -= pair[0]; }
});
return s;
}
function formatMarker(spec, n) {
if (spec === 'decimal') return n + '.';
if (spec === 'bullet' || spec === 'desc') return '';
return spec
.replace(/\\alph\*/g, String.fromCharCode(96 + n))
.replace(/\\Alph\*/g, String.fromCharCode(64 + n))
.replace(/\\roman\*/g, roman(n))
.replace(/\\Roman\*/g, roman(n).toUpperCase())
.replace(/\\arabic\*/g, String(n));
}
function parseContent(s, depth) {
var blocks = [];
var buf = '';
var i = 0;
var pendingSize = '';
function flush() {
if (buf.trim()) blocks.push({ type: 'p', text: buf.trim() });
buf = '';
}
while (i < s.length) {
var start = i;
if (s[i] === '\n') {
var j = i + 1;
while (s[j] === ' ' || s[j] === '\t') j++;
if (s[j] === '\n') {
flush();
i = j + 1;
continue;
}
}
if (s.startsWith('\\begin{', i)) {
flush();
var b = readBegin(s, i);
var found = findEnd(s, b.next, b.name);
blocks.push(makeEnv(b.name, b.opt, found.body, depth, pendingSize));
pendingSize = '';
i = found.end;
if (i === start) throw new Error('env did not advance');
continue;
}
var sec = /^\\(subsubsection|subsection|section|paragraph|maketitle|tableofcontents|clearpage)\b\*?/.exec(s.slice(i));
if (sec) {
flush();
var name = sec[1];
var k = i + sec[0].length;
if (name === 'maketitle') blocks.push({ type: 'maketitle' });
else if (name === 'tableofcontents') blocks.push({ type: 'toc' });
else if (name === 'clearpage') { /* skip */ }
else if (name === 'paragraph') {
var title = readBrace(s, k);
buf = '\uE010' + title.text + '\uE011 ';
k = title.end;
} else {
var titleS = readBrace(s, k);
k = titleS.end;
var id = null;
var lab = /^\s*\\label\{([^}]*)\}/.exec(s.slice(k));
if (lab) { id = lab[1]; k = k + lab[0].length; }
var level = name === 'section' ? 1 : name === 'subsection' ? 2 : 3;
blocks.push({ type: 'section', level: level, title: titleS.text, id: id });
}
i = k;
if (i === start) throw new Error('command did not advance: ' + name);
continue;
}
if (s.startsWith('\\small', i) && !/[a-zA-Z]/.test(s[i + 6] || '')) { pendingSize = 'small'; i += 6; continue; }
if (s.startsWith('\\footnotesize', i)) { pendingSize = 'footnotesize'; i += 13; continue; }
buf += s[i];
i++;
}
flush();
return blocks;
}
function makeEnv(name, opt, body, depth, size) {
if (ENVS[name]) {
var labelled = takeLabel(body);
return { type: 'thm', kind: name, opt: opt, id: labelled.id, body: parseContent(labelled.rest, depth) };
}
if (name === 'proof') return { type: 'proof', body: parseContent(body, depth) };
if (name === 'abstract') return { type: 'abstract', body: parseContent(body, depth) };
if (name === 'center') return { type: 'center', body: parseContent(body, depth), size: size || '' };
if (name === 'enumerate' || name === 'itemize' || name === 'description') {
return {
type: 'list',
kind: listKind(name, opt),
depth: depth + 1,
items: splitItems(body).map(function (it) {
return { label: it.label, body: parseContent(it.text, depth + 1) };
})
};
}
if (name === 'tabular') {
var spec = '';
var rest = body;
if (rest.trimStart().startsWith('{')) {
var lead = rest.length - rest.trimStart().length;
var specArg = readBrace(rest.trimStart(), 0);
spec = specArg.text;
rest = rest.trimStart().slice(specArg.end);
if (lead) { /* spec already sliced from trimmed string */ }
}
return { type: 'table', rows: parseTabular(rest), size: size || '', spec: spec };
}
if (name === 'figure') return parseFigure(body);
if (name === 'thebibliography') return { type: 'bib', items: parseBib(body) };
throw new Error('unknown environment: ' + name);
}
function parseFigure(body) {
var imgs = [];
var re = /\\includegraphics(?:\[[^\]]*\])?\{([^}]*)\}/g;
var m;
while ((m = re.exec(body))) imgs.push(m[1]);
var cap = '';
var c = /\\caption\{/.exec(body);
if (c) cap = readBrace(body, c.index + '\\caption'.length).text;
var id = null;
var lab = /\\label\{([^}]*)\}/.exec(body);
if (lab) id = lab[1];
return { type: 'figure', imgs: imgs, caption: cap, id: id };
}
function parseBib(body) {
var parts = body.split(/\\bibitem\{/);
var items = [];
parts.slice(1).forEach(function (part) {
var end = part.indexOf('}');
items.push({ key: part.slice(0, end), text: part.slice(end + 1).trim() });
});
return items;
}
function assignMath(s, state) {
if (!s) return;
var re = /\uE000(\d+)\uE001/g;
var m;
while ((m = re.exec(s))) {
var info = state.math[+m[1]];
if (info && info.display && info.numbered && info.num == null) {
info.num = ++state.eq;
if (info.id) state.labels[info.id] = String(info.num);
}
}
}
function walk(nodes, state) {
nodes.forEach(function (n) {
if (n.type === 'section') {
if (n.level === 1) {
state.sec++;
state.sub = 0;
Object.keys(ENVS).forEach(function (kind) {
var def = ENVS[kind];
if (!def.shared && def.within === 'section') state.counters[kind] = 0;
});
n.num = String(state.sec);
} else if (n.level === 2) { state.sub++; n.num = state.sec + '.' + state.sub; }
else n.num = '';
n.anchor = n.id || ('sec-' + (n.num || n.title));
if (n.id) state.labels[n.id] = n.num || n.title;
assignMath(n.title, state);
} else if (n.type === 'p') assignMath(n.text, state);
else if (n.type === 'thm') {
var def = ENVS[n.kind] || { title: n.kind, shared: null, within: 'section', style: 'plain' };
var key = def.shared || n.kind;
var parent = def.shared ? ENVS[def.shared] : def;
var within = parent && parent.within;
state.counters[key] = (state.counters[key] || 0) + 1;
n.num = within === 'section' ? state.sec + '.' + state.counters[key] : String(state.counters[key]);
n.title = def.title;
n.style = def.style || 'plain';
if (n.id) state.labels[n.id] = n.num;
assignMath(n.opt || '', state);
walk(n.body, state);
} else if (n.type === 'proof' || n.type === 'abstract' || n.type === 'center') walk(n.body, state);
else if (n.type === 'list') n.items.forEach(function (it) {
assignMath(it.label || '', state);
walk(it.body, state);
});
else if (n.type === 'table') n.rows.forEach(function (row) {
(row.cells || []).forEach(function (cell) { assignMath(cell.text, state); });
});
else if (n.type === 'figure') {
state.fig++;
n.num = String(state.fig);
if (n.id) state.labels[n.id] = n.num;
assignMath(n.caption, state);
} else if (n.type === 'bib') n.items.forEach(function (it, idx) {
it.num = idx + 1;
state.cites[it.key] = it.num;
assignMath(it.text, state);
});
});
}
function mathSpan(info) {
if (!info) return '';
var open = info.display ? '\\[' : '\\(';
var close = info.display ? '\\]' : '\\)';
return open + esc(info.tex) + close;
}
function inline(s, state) {
var out = '';
var i = 0;
while (i < s.length) {
if (s.charCodeAt(i) === 0xE000) {
var j = s.indexOf('\uE001', i);
out += mathSpan(state.math[+s.slice(i + 1, j)]);
i = j + 1;
continue;
}
if (s.charCodeAt(i) === 0xE010) {
var j2 = s.indexOf('\uE011', i);
out += '<strong class="runin">' + inline(s.slice(i + 1, j2), state) + '</strong> ';
i = j2 + 1;
continue;
}
if (s.startsWith('``', i)) { out += '\u201c'; i += 2; continue; }
if (s.startsWith("''", i)) { out += '\u201d'; i += 2; continue; }
if (s.startsWith('---', i)) { out += '\u2014'; i += 3; continue; }
if (s.startsWith('--', i)) { out += '\u2013'; i += 2; continue; }
if (s[i] === '~') { out += '\u00a0'; i++; continue; }
if (s[i] === '\\') {
var acc = s[i + 1];
if (acc && "'`^\"~".indexOf(acc) >= 0) {
var k = i + 2;
var ch = '';
if (s[k] === '{') {
var g = readBrace(s, k);
ch = g.text;
k = g.end;
} else {
ch = s[k] || '';
k++;
}
var mark = { "'": '\u0301', '`': '\u0300', '^': '\u0302', '"': '\u0308', '~': '\u0303' }[acc];
out += esc(ch).replace(/^(.)/, function (_, c) { return c + mark; });
i = k;
continue;
}
if (s.startsWith('\\c{', i)) {
var ced = readBrace(s, i + 2);
out += esc(ced.text) + '\u0327';
i = ced.end;
continue;
}
var word = /^\\([a-zA-Z]+)\s*/.exec(s.slice(i));
if (!word) {
var n = s[i + 1];
if (n === '\\') out += '<br>';
else if (n === ' ' || n === ',' || n === '/') out += n === ',' ? '\u2009' : (n === ' ' ? ' ' : '');
else if (n === '&') out += '&amp;';
else if (n === '%') out += '%';
else if (n === '#') out += '#';
else if (n === '_') out += '_';
else if (n === '$') out += '$';
else if (n === '{' || n === '}') out += n;
else out += esc(n || '');
i += 2;
continue;
}
var cmd = word[1];
var p = i + word[0].length;
if (cmd === 'emph' || cmd === 'textit' || cmd === 'textsc') {
var a1 = readBrace(s, p);
out += '<em>' + inline(a1.text, state) + '</em>';
i = a1.end;
continue;
}
if (cmd === 'textbf' || cmd === 'textup') {
var a2 = readBrace(s, p);
out += '<strong>' + inline(a2.text, state) + '</strong>';
i = a2.end;
continue;
}
if (cmd === 'texttt') {
var a3 = readBrace(s, p);
out += '<code>' + inline(a3.text, state) + '</code>';
i = a3.end;
continue;
}
if (cmd === 'ref') {
var r = readBrace(s, p);
var num = state.labels[r.text];
out += '<a class="ref" href="#' + esc(r.text) + '">' + esc(num || r.text) + '</a>';
i = r.end;
continue;
}
if (cmd === 'eqref') {
var e = readBrace(s, p);
var en = state.labels[e.text];
out += '(<a class="ref" href="#' + esc(e.text) + '">' + esc(en || e.text) + '</a>)';
i = e.end;
continue;
}
if (cmd === 'cite') {
var note = '';
if (s[p] === '[') {
var br = readBracket(s, p);
note = br.text;
p = br.end;
}
var c = readBrace(s, p);
var keys = c.text.split(/\s*,\s*/);
var bits = keys.map(function (key) {
var cn = state.cites[key];
return '<a class="ref" href="#bib-' + esc(key) + '">' + esc(cn || key) + '</a>';
});
out += '[' + bits.join(', ') + (note ? ', ' + inline(note, state) : '') + ']';
i = c.end;
continue;
}
if (cmd === 'S') { out += '\u00a7'; i = p; continue; }
if (cmd === 'label') {
var lb = readBrace(s, p);
out += '<span id="' + esc(lb.text) + '"></span>';
i = lb.end;
continue;
}
if (cmd === 'qedhere') { out += '<span class="qed">\u220e</span>'; i = p; continue; }
if (cmd === 'noindent' || cmd === 'leavevmode' || cmd === 'centering' || cmd === 'small' ||
cmd === 'footnotesize' || cmd === 'normalsize' || cmd === 'clearpage' || cmd === 'hfill' ||
cmd === 'qquad' || cmd === 'quad' || cmd === 'hspace' || cmd === 'vspace') {
if (cmd === 'hspace' || cmd === 'vspace') {
if (s[p] === '{') p = readBrace(s, p).end;
}
if (cmd === 'quad') out += '\u2003';
if (cmd === 'qquad') out += '\u2003\u2003';
i = p;
continue;
}
if (MACROS[cmd]) {
out += '\\(' + esc(MACROS[cmd]) + '\\)';
i = p;
continue;
}
if (s[p] === '{') {
var unk = readBrace(s, p);
state.unknown[cmd] = (state.unknown[cmd] || 0) + 1;
out += inline(unk.text, state);
i = unk.end;
continue;
}
state.unknown[cmd] = (state.unknown[cmd] || 0) + 1;
i = p;
continue;
}
if (s[i] === '{') {
var grp = readBrace(s, i);
var inner = grp.text;
var font = /^(?:\\(em|it|bf|rm|sc|tt|bfseries|itshape|rmfamily|sffamily))\s*/.exec(inner);
if (font) {
var rest = inner.slice(font[0].length);
var tag = (font[1] === 'bf' || font[1] === 'bfseries') ? 'strong' : 'em';
if (font[1] === 'rm' || font[1] === 'rmfamily' || font[1] === 'upshape') out += inline(rest, state);
else out += '<' + tag + '>' + inline(rest, state) + '</' + tag + '>';
} else out += inline(inner, state);
i = grp.end;
continue;
}
out += esc(s[i]);
i++;
}
return out;
}
function renderBlocks(nodes, state, mergeFirst) {
var html = '';
nodes.forEach(function (n, idx) {
html += renderNode(n, state, mergeFirst && idx === 0);
});
return html;
}
function renderParas(text, state) {
var re = /\uE000(\d+)\uE001/g;
var html = '';
var last = 0;
var buf = '';
var m;
function flush() {
var t = buf.replace(/\s*\n\s*/g, ' ').trim();
if (t) html += '<p>' + inline(t, state) + '</p>';
buf = '';
}
while ((m = re.exec(text))) {
var info = state.math[+m[1]];
if (info && info.display) {
buf += text.slice(last, m.index);
flush();
html += renderEq(info, state);
} else {
buf += text.slice(last, m.index) + m[0];
}
last = m.index + m[0].length;
}
buf += text.slice(last);
flush();
return html;
}
function renderEq(info) {
var id = info.id ? ' id="' + esc(info.id) + '"' : '';
var no = info.numbered ? '<span class="eq-no">(' + info.num + ')</span>' : '';
return '<div class="eq"' + id + '>' + no + '<div class="eq-body">\\[' + esc(info.tex) + '\\]</div></div>';
}
function renderNode(n, state, mergeHead) {
if (n.type === 'maketitle') {
return '<header class="paper-title"><h1>' + inline(state.title, state) + '</h1>' +
'<p class="by">' + inline(state.author, state) + '</p>' +
'<p class="date">' + inline(state.date, state) + '</p></header>';
}
if (n.type === 'toc') return renderToc(state.tocNodes, state);
if (n.type === 'section') {
var tag = n.level === 1 ? 'h2' : n.level === 2 ? 'h3' : 'h4';
var num = n.num ? '<span class="sec-no">' + esc(n.num) + '</span> ' : '';
return '<' + tag + ' id="' + esc(n.anchor) + '">' + num + inline(n.title, state) + '</' + tag + '>';
}
if (n.type === 'p') return renderParas(n.text, state);
if (n.type === 'abstract') {
return '<div class="abstract"><h2>Abstract</h2>' + renderBlocks(n.body, state) + '</div>';
}
if (n.type === 'thm') {
var head = '<span class="thm-head"><strong>' + esc(n.title || n.kind) + ' ' + esc(n.num) + '</strong>';
if (n.opt) head += ' <span class="note">(' + inline(n.opt, state) + ')</span>';
head += '.</span> ';
return '<div class="thm ' + esc(n.style || 'plain') + '"' + (n.id ? ' id="' + esc(n.id) + '"' : '') + '>' +
mergeBody(head, n.body, state) + '</div>';
}
if (n.type === 'proof') {
var bodyHtml = mergeBody('<span class="proof-head"><em>Proof.</em></span> ', n.body, state);
if (bodyHtml.indexOf('class="qed"') < 0) bodyHtml = bodyHtml.replace(/<\/p>\s*$/, ' <span class="qed">\u220e</span></p>');
if (bodyHtml.indexOf('class="qed"') < 0) bodyHtml += '<p class="qed-row"><span class="qed">\u220e</span></p>';
return '<div class="proof">' + bodyHtml + '</div>';
}
if (n.type === 'center') {
return '<div class="center ' + esc(n.size) + '">' + renderBlocks(n.body, state) + '</div>';
}
if (n.type === 'list') return renderList(n, state);
if (n.type === 'table') return renderTable(n, state);
if (n.type === 'figure') {
var imgs = n.imgs.map(function (src) {
return '<img src="' + esc(src) + '" alt="" onerror="this.remove()">';
}).join('');
var id = n.id ? ' id="' + esc(n.id) + '"' : '';
return '<figure' + id + '><div class="figs">' + imgs + '</div><figcaption><strong>Figure ' +
esc(n.num) + '.</strong> ' + inline(n.caption, state) + '</figcaption></figure>';
}
if (n.type === 'bib') {
var rows = n.items.map(function (it) {
return '<dt id="bib-' + esc(it.key) + '">[' + it.num + ']</dt><dd>' + inline(it.text.replace(/\s*\n\s*/g, ' '), state) + '</dd>';
}).join('');
return '<section class="bib" id="references"><h2>References</h2><dl>' + rows + '</dl></section>';
}
return '';
}
function mergeBody(head, blocks, state) {
if (!blocks.length) return '<p>' + head + '</p>';
if (blocks[0].type !== 'p') return '<p>' + head + '</p>' + renderBlocks(blocks, state);
var first = blocks[0].text;
var re = /\uE000(\d+)\uE001/;
var m = re.exec(first);
var html;
if (m && m.index === 0 && state.math[+m[1]] && state.math[+m[1]].display) {
html = '<p>' + head + '</p>' + renderParas(first, state);
} else {
var collapsed = first.replace(/\s*\n\s*/g, ' ').trim();
var displayAt = collapsed.search(/\uE000(\d+)\uE001/);
html = renderParas(collapsed, state).replace('<p>', '<p>' + head);
}
return html + renderBlocks(blocks.slice(1), state);
}
function renderList(n, state) {
if (n.kind === 'desc') {
return '<dl class="desc">' + n.items.map(function (it) {
return '<dt>' + inline(it.label || '', state) + '</dt><dd>' + renderBlocks(it.body, state) + '</dd>';
}).join('') + '</dl>';
}
if (n.kind === 'bullet') {
return '<ul>' + n.items.map(function (it) {
return '<li><div class="li-body">' + renderBlocks(it.body, state) + '</div></li>';
}).join('') + '</ul>';
}
return '<ol class="enum">' + n.items.map(function (it, idx) {
var marker = it.label ? inline(it.label, state) : esc(formatMarker(n.kind, idx + 1));
return '<li><span class="marker">' + marker + '</span><div class="li-body">' + renderBlocks(it.body, state) + '</div></li>';
}).join('') + '</ol>';
}
function renderTable(n, state) {
var body = n.rows.map(function (row) {
if (!row.cells || !row.cells.length) return '';
var cls = (row.ruleBefore ? ' rule-before' : '') + (row.ruleAfter ? ' rule-after' : '');
var cells = row.cells.map(function (cell) {
var span = cell.span > 1 ? ' colspan="' + cell.span + '"' : '';
return '<td' + span + '>' + inline(cell.text, state) + '</td>';
}).join('');
return '<tr class="' + cls.trim() + '">' + cells + '</tr>';
}).join('');
return '<div class="table-wrap ' + esc(n.size) + '"><table>' + body + '</table></div>';
}
function renderToc(nodes, state) {
var html = '<nav class="toc"><p class="toc-label">Contents</p><ol>';
var open = false;
var started = false;
nodes.forEach(function (n) {
if (n.type !== 'section' || n.level > 2) return;
if (n.level === 1) {
if (open) html += '</ol></li>';
else if (started) html += '</li>';
html += '<li><a href="#' + esc(n.anchor) + '"><span class="sec-no">' + esc(n.num) + '</span> ' + inline(n.title, state) + '</a>';
open = false;
started = true;
} else {
if (!open) { html += '<ol>'; open = true; }
html += '<li><a href="#' + esc(n.anchor) + '"><span class="sec-no">' + esc(n.num) + '</span> ' + inline(n.title, state) + '</a></li>';
}
});
if (open) html += '</ol></li>';
else html += '</li>';
return html + '</ol></nav>';
}
function convert(tex, options) {
options = options || {};
var src = stripComments(expandInputs(tex, options.files || {}));
parseNewcommands(src);
var preamble = src.split('\\begin{document}')[0];
parseNewtheorems(preamble);
var extracted = extractAll(src);
var text = extracted.text;
var doc = text.split('\\begin{document}');
if (doc.length < 2) throw new Error('missing \\begin{document}');
var body = doc[1].split('\\end{document}')[0];
var state = {
math: extracted.math,
labels: {},
cites: {},
unknown: {},
title: grab(text, 'title'),
author: grab(text, 'author'),
date: grab(text, 'date'),
sec: 0, sub: 0, eq: 0, fig: 0,
counters: {},
tocNodes: null
};
var nodes = parseContent(body, 0);
state.tocNodes = nodes;
walk(nodes, state);
return {
html: renderBlocks(nodes, state),
unknown: state.unknown,
labels: state.labels,
counts: {
display: extracted.math.filter(function (m) { return m.display; }).length,
inline: extracted.math.filter(function (m) { return !m.display; }).length
}
};
}
root.tex2html = convert;
if (typeof module !== 'undefined') module.exports = convert;
})(typeof window !== 'undefined' ? window : globalThis);