File size: 32,767 Bytes
4ef1e8b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 | // Render the paper TeX in the browser. Math is left for MathJax.
(function (root) {
'use strict';
var ESC = { '&': '&', '<': '<', '>': '>', '"': '"' };
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 += '&';
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);
|