Publish the multi-radix heap preprint
Browse filesFiles changed (8)
- .gitattributes+1
- README.md+16-4
- index.html+135-17
- multi_radix_heap.pdfAdded+3
- multi_radix_heap.texAdded+289
- refs.bblAdded+79
- style.cssDeleted-28
- tex2html.jsAdded+1123
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textmulti_radix_heap.pdf filter=lfs diff=lfs merge=lfs -text
12345678910---title: Multi Radix Heapemoji: 🏢colorFrom: pinkcolorTo: graysdk: staticpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122---title: Multi-Radix Heapemoji: 🔢colorFrom: indigocolorTo: graysdk: staticpinned: falseshort_description: Mixed-radix monotone priority queue for Dijkstra---# Multi-Radix Heap**The Multi-Radix Heap: A Mixed-Radix Monotone Priority Queue for Dijkstra's Algorithm**Gregory Disney-Leugers (Encryptid Systems) · November 2026- [Paper (PDF)](multi_radix_heap.pdf)- [LaTeX source](multi_radix_heap.tex)- Companion preprint: [Eikonal Memory Laws](https://huggingface.co/spaces/EncryptidSystems/Eikonal-Memory-Laws)- Companion preprint: [Multi-Radix Geometry](https://huggingface.co/spaces/EncryptidSystems/Multi-Radix-Geometry)The page renders the LaTeX in the browser. The PDF is a download.
12345678910111213141516171819<!doctype html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width" /><title>My static Space</title><link rel="stylesheet" href="style.css" /></head><body><div class="card"><h1>Welcome to your static Space!</h1><p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p><p>Also don't forget to check the<a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.</p></div></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>The Multi-Radix Heap</title><meta name="description" content="The Multi-Radix Heap: A Mixed-Radix Monotone Priority Queue for Dijkstra's Algorithm. Gregory Disney-Leugers, Encryptid Systems, November 2026."><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Source+Serif+4:ital,opsz,wght@0,8..60,400;0,8..60,600;1,8..60,400&family=Inter:wght@400;500;600&display=swap" rel="stylesheet"><script>window.MathJax = {tex: { inlineMath: [['\\(', '\\)']], displayMath: [['\\[', '\\]']] },chtml: { matchFontHeight: false },startup: { typeset: false }};</script><script defer src="https://cdn.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-chtml.js"></script><script src="tex2html.js"></script><style>:root {--bg: #fbfaf7; --surface: #ffffff; --text: #1d1c1a; --muted: #5f5b55;--rule: #e4e0d8; --accent: #3a4f9a; --accent-soft: #eef0f8; --thm: #f5f3ee;}@media (prefers-color-scheme: dark) {:root { --bg: #151514; --surface: #1d1d1b; --text: #ecebe7; --muted: #a39f97;--rule: #34322e; --accent: #9fb0ec; --accent-soft: #23283a; --thm: #1f1f1d; }}* { box-sizing: border-box; }html, body { margin: 0; background: var(--bg); color: var(--text); }body { font: 18px/1.65 "Source Serif 4", Georgia, serif; }.bar, .btn, footer, .status, .sec-no, .marker, .eq-no, .thm-head, .proof-head, figcaption, dt, .algo-comment {font-family: Inter, system-ui, sans-serif;}.bar { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; max-width: 860px; margin: 0 auto; padding: 22px 20px 0; }.btn { display: inline-flex; align-items: center; padding: 8px 14px; border-radius: 8px; font-size: 14px; font-weight: 500; text-decoration: none; border: 1px solid var(--rule); color: var(--text); background: var(--surface); }.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--bg); }main { max-width: 860px; margin: 0 auto; padding: 12px 20px 72px; }.paper-title h1 { font-size: clamp(28px, 5vw, 40px); line-height: 1.15; font-weight: 600; margin: 18px 0 8px; }.by, .date { margin: 0; color: var(--muted); font-size: 16px; }.abstract { background: var(--accent-soft); border-radius: 10px; padding: 4px 22px 8px; margin: 28px 0; }.abstract h2 { font-size: 13px; letter-spacing: .08em; text-transform: uppercase; color: var(--muted); font-weight: 600; }h2 { font-size: 1.45rem; line-height: 1.25; margin: 2.2em 0 .6em; }h3 { font-size: 1.15rem; margin: 1.6em 0 .4em; }p { margin: 0 0 .9em; }a { color: var(--accent); }.sec-no { color: var(--muted); font-weight: 600; font-size: .85em; }.thm { background: var(--thm); border-radius: 8px; padding: 10px 16px 4px; margin: 1em 0; }.thm.plain { font-style: italic; }.thm.plain .thm-head, .thm .note { font-style: normal; }.thm-head { font-style: normal; }.thm.plain em { font-style: normal; }.proof { margin: .4em 0 1.2em; }.qed { float: right; font-style: normal; }ol.enum, ul { margin: .3em 0 .6em; padding: 0; list-style: none; }ol.enum > li, ul > li { display: flex; gap: .55em; margin: .15em 0; }.marker { min-width: 1.8em; font-style: normal; }.li-body { flex: 1; min-width: 0; }.li-body > p { margin: 0 0 .35em; }.eq { display: flex; align-items: center; gap: 12px; margin: .8em 0; overflow-x: auto; }.eq-body { flex: 1; }.eq-no { color: var(--muted); font-size: .9rem; }.center { text-align: center; margin: 1em 0; }.center .table-wrap { display: inline-block; text-align: left; max-width: 100%; }.table-wrap { overflow-x: auto; margin: 1em 0; }table { border-collapse: collapse; width: 100%; font-size: .78rem; line-height: 1.35; }.small table, .table-wrap.small table { font-size: .82rem; }td { padding: 3px 8px; vertical-align: top; }tr.rule-before td { border-top: 1px solid var(--text); }tr.rule-after td { border-bottom: 1px solid var(--text); }figure.algo { margin: 1.4em 0; padding: 12px 16px 8px; border: 1px solid var(--rule); border-radius: 10px; background: var(--surface); }figure.algo figcaption { margin: 0 0 .6em; color: var(--text); }ol.algo-lines { margin: 0; padding-left: 2.2em; font-size: .92rem; }ol.algo-lines li { margin: .2em 0; padding-left: .2em; }ol.algo-lines li.d1 { margin-left: 1.15em; }ol.algo-lines li.d2 { margin-left: 2.3em; }ol.algo-lines li.d3 { margin-left: 3.45em; }.algo-comment { color: var(--muted); font-size: .85em; }.algo-comment::before { content: "\\25B8\\00a0"; }.bib dl { display: grid; grid-template-columns: 3em 1fr; gap: .35em .6em; }.bib dt { color: var(--muted); }.bib dd { margin: 0; }footer { max-width: 860px; margin: 0 auto; padding: 0 20px 48px; color: var(--muted); font-size: 13.5px; }pre.cite { font: 13px/1.5 ui-monospace, SFMono-Regular, Consolas, monospace; background: var(--accent-soft); padding: 16px; border-radius: 8px; overflow-x: auto; }code { font: 0.86em/1.4 ui-monospace, SFMono-Regular, Consolas, monospace; }mjx-container { overflow-x: auto; overflow-y: hidden; max-width: 100%; }</style></head><body><div class="bar"><a class="btn primary" href="multi_radix_heap.pdf" download>PDF</a><a class="btn" href="multi_radix_heap.tex" download>TeX</a><a class="btn" href="https://huggingface.co/spaces/EncryptidSystems/Eikonal-Memory-Laws">Eikonal Memory Laws</a><a class="btn" href="https://huggingface.co/spaces/EncryptidSystems/Multi-Radix-Geometry">Multi-Radix Geometry</a></div><main id="paper"><p class="status">Rendering the paper…</p></main><footer><pre class="cite">@misc{disneyleugers2026mrh,title = {The Multi-Radix Heap: A Mixed-Radix Monotone Priority Queue for Dijkstra's Algorithm},author = {Disney-Leugers, Gregory},year = {2026},month = nov,note = {Encryptid Systems preprint},howpublished = {\url{https://huggingface.co/spaces/EncryptidSystems/Multi-Radix-Heap}}}</pre><p>© 2026 Gregory Disney-Leugers, Encryptid Systems. Rendered in the browser from the LaTeX source.</p></footer><script>(function () {var paper = document.getElementById('paper');function fail(msg) {paper.innerHTML = '<p class="status">' + msg + ' <a href="multi_radix_heap.pdf">Download the PDF</a>.</p>';}function load(url) {return fetch(url).then(function (r) {if (!r.ok) throw new Error(url + ' ' + r.status);return r.text();});}Promise.all([load('multi_radix_heap.tex'), load('refs.bbl')]).then(function (parts) {var main = parts[0].replace(/\\bibliography\{refs\}/, '\n' + parts[1] + '\n');var out = window.tex2html(main, { files: {} });paper.innerHTML = out.html;var ready = function () {return MathJax.startup.promise.then(function () {return MathJax.typesetPromise([paper]);});};if (window.MathJax && MathJax.startup && MathJax.startup.promise) return ready();return new Promise(function (res) { window.addEventListener('load', res); }).then(ready);}).catch(function (e) { console.error(e); fail('The paper could not be rendered.'); });})();</script></body></html>
123version https://git-lfs.github.com/spec/v1oid sha256:c303bee570cb9984b28c4697a68bb731a9b6eff7cfe945a7d76435b37070a3easize 289856123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289\documentclass[11pt]{article}\usepackage[margin=1in]{geometry}\usepackage{amsmath,amssymb,amsthm}\usepackage{booktabs,xcolor}\usepackage{algorithm}\usepackage[noend]{algpseudocode}\usepackage[numbers,sort&compress]{natbib}\usepackage[colorlinks=true,linkcolor=blue!50!black,citecolor=blue!50!black,urlcolor=blue!50!black]{hyperref}\usepackage{enumitem}\setlist{nosep,leftmargin=*}
\newtheorem{theorem}{Theorem}\newtheorem{lemma}{Lemma}\newtheorem{proposition}{Proposition}\newtheorem{corollary}{Corollary}\theoremstyle{definition}\newtheorem{definition}{Definition}\theoremstyle{remark}\newtheorem{remark}{Remark}
\newcommand{\rmax}{r_{\max}}\newcommand{\lev}{\ell}\newcommand{\Loc}{\textsc{Locate}}
\title{The Multi-Radix Heap:\\ A Mixed-Radix Monotone Priority Queue for Dijkstra's Algorithm}\author{Gregory Disney-Leugers\\ \small Encryptid Systems}\date{November 2026}
\begin{document}\maketitle
\begin{abstract}We define the multi-radix heap $\mathrm{MRH}(r;C)$, a monotone integer priority queue parameterised by an arbitrary tuple of radices $r=(r_0,\dots,r_{k-1})$ with $\prod_jr_j\ge C+1$. Keys are addressed by their mixed-radix digits with place values $\pi_0=1$, $\pi_{j+1}=\pi_jr_j$. A key is stored at the most significant digit in which it differs from the current frontier, and keys in the next block of size $\pi_k$ share a single overflow bucket. We prove that every item's level only decreases, and that each extract-min redistributes at most one bucket. It follows that any sequence of $n$ inserts, $m$ decrease-keys and at most $n$ extract-mins, with keys in a sliding window of width $C+1$, runs in $O(m+n(k+\rmax))$ time, where $\rmax=\max_jr_j$, using $O(n+\sum_jr_j)$ space. A refined bound weights each radix by the number of extract-mins that scan its level. Dijkstra's algorithm on a graph with $n$ vertices, $m$ arcs and integer lengths at most $C$ inherits the same bound. Binary radices give the $O(m+n\log C)$ bound of the one-level radix heap, uniform radices $\Delta=\Theta(\log C/\log\log C)$ give the $O(m+n\log C/\log\log C)$ bound of the two-level radix heap, and a single level of $C+1$ buckets is Dial's algorithm. A stored operation-count ablation of a reference implementation over eight radix tuples at $C=4095$ is reported. All eight runs reproduced binary-heap distances. The ablation shows that reordering the same radices changes the number of bucket scans by a factor of 7.2.\end{abstract}
\section{Introduction}A priority queue is \emph{monotone} if successive extract-min operations return nondecreasing keys~\cite{thorup96,costa}. Dijkstra's algorithm~\cite{dijkstra} on a graph with non-negative arc lengths uses its queue monotonically: every key inserted or decreased after a vertex $u$ is settled is at least $d(u)$. When lengths are integers bounded by $C$, every such key also lies in the window $[d(u),d(u)+C]$, and bucket structures whose cost depends on $C$ rather than on comparison depth become available.
Dial~\cite{dial} used $C+1$ unit-width buckets. Denardo and Fox~\cite{denardofox} introduced multi-level buckets with a uniform branching factor per level. Johnson~\cite{johnson} and Ahuja, Mehlhorn, Orlin and Tarjan~\cite{amot} developed radix heaps, whose one-level form uses $O(\log C)$ buckets of exponentially growing width and whose two-level form replaces powers of two by powers of a parameter $\Delta$. Cherkassky, Goldberg and Silverstein~\cite{cgs} combined multi-level buckets with heaps, and Goldberg and Silverstein~\cite{goldbergsilverstein} studied implementations. Practical libraries such as TLX~\cite{tlx} expose radix heaps with a single power-of-two radix.
All of these structures fix one branching factor, or one sequence of bucket widths. We define a queue whose bucket hierarchy is induced by an \emph{arbitrary} radix tuple $(r_0,\dots,r_{k-1})$, possibly with unequal entries. We are not aware of a prior definition of a priority queue parameterised in this way. The structure is close in spirit to Denardo--Fox multi-level buckets. It differs in three respects: it allows level-dependent radices, it places keys relative to the frontier by their most significant differing digit, and it handles the sliding window with one overflow bucket rather than a wrap-around top level.
\paragraph{Contributions.}\begin{enumerate}\item A precise definition of $\mathrm{MRH}(r;C)$ and its invariants (Section~\ref{sec:def}). It needs only $\prod_jr_j\ge C+1$.\item Correctness (Theorem~\ref{thm:correct}) and the amortised bound $O(m+n(k+\rmax))$, with a refined form $O(m+nk+\sum_jr_jE_j)$ in which $E_j$ counts the extract-mins that scan level $j$ (Theorem~\ref{thm:cost}).\item Dijkstra's algorithm on the multi-radix heap (Section~\ref{sec:dijkstra}): correctness, the running time $O(m+n(k+\rmax))$, and the radix-heap and Dial bounds as special cases.\item An operation-count ablation over eight radix tuples (Section~\ref{sec:exp}), and a description of two implementations (Section~\ref{sec:impl}).\end{enumerate}
\section{Definition}\label{sec:def}\subsection{Mixed-radix addressing}\begin{definition}[radix tuple]Let $C\ge0$ be an integer. A \emph{radix tuple for $C$} is $r=(r_0,\dots,r_{k-1})$ with integers $r_j\ge2$ and\begin{equation}\label{eq:cover}\pi_k\ge C+1,\qquad\text{where}\quad \pi_0=1,\quad \pi_{j+1}=\pi_jr_j .\end{equation}We also admit the degenerate tuple $k=1$, $r_0=C+1$, which covers $C=0$. Write $\rmax=\max_jr_j$.\end{definition}For an integer $x\ge0$ define the digits and the block\begin{equation}\delta_j(x)=\Big\lfloor\frac{x}{\pi_j}\Big\rfloor\bmod r_j\quad(0\le j<k),\qquad \beta(x)=\Big\lfloor\frac{x}{\pi_k}\Big\rfloor,\end{equation}so that $x=\beta(x)\pi_k+\sum_{j<k}\delta_j(x)\pi_j$ with $0\le\delta_j(x)<r_j$. This is the mixed-radix numeral system with place values $\pi_j$.
\begin{definition}[level and address]Fix a frontier $\mu\ge0$. For a key $\kappa\ge\mu$, its \emph{level} is\[\lev_\mu(\kappa)=\begin{cases}k & \text{if }\beta(\kappa)\ne\beta(\mu),\\ \max\{j<k:\delta_j(\kappa)\ne\delta_j(\mu)\} & \text{if }\beta(\kappa)=\beta(\mu)\text{ and such }j\text{ exists},\\ 0&\text{if }\kappa=\mu.\end{cases}\]Its \emph{address} is $a_\mu(\kappa)=(\lev,\delta_\lev(\kappa))$ when $\lev=\lev_\mu(\kappa)<k$, and $a_\mu(\kappa)=(k,0)$ when $\lev_\mu(\kappa)=k$.\end{definition}
\begin{definition}[multi-radix heap]$\mathrm{MRH}(r;C)$ stores items with integer keys and maintains a frontier $\mu$ (initially $0$, or any base key); buckets $B_j[t]$ for $0\le j<k$, $0\le t<r_j$, and one overflow bucket $B_k[0]$, each a doubly linked list; a count of items per level; and, for each item, a handle to its bucket. A configuration is \emph{valid} when\begin{itemize}\item[(I1)] every key satisfies $\mu\le K(x)\le\mu+C$, and\item[(I2)] every item $x$ lies in bucket $B_{a}$ with $a=a_\mu(K(x))$.\end{itemize}Operations are called under the \emph{window condition} (W): every key inserted, or set by decrease-key, lies in $[\mu,\mu+C]$ for the current $\mu$.\end{definition}Since $\mu$ never decreases (Theorem~\ref{thm:correct}), (W) implies the upper half of (I1) at all later times.
\subsection{Order lemmas}\begin{lemma}[window]\label{lem:window}If $\mu\le\kappa\le\mu+C$ then $\beta(\kappa)\in\{\beta(\mu),\beta(\mu)+1\}$.\end{lemma}\begin{proof}$0\le\kappa-\mu\le C<\pi_k$ by \eqref{eq:cover}.\end{proof}
\begin{lemma}[order]\label{lem:order}Let $\mu\le\kappa,\kappa'\le\mu+C$.\begin{enumerate}\item[(a)] If $\lev_\mu(\kappa)=j<k$ and $\kappa\ne\mu$, then $\delta_j(\kappa)>\delta_j(\mu)$.\item[(b)] If $\lev_\mu(\kappa)<\lev_\mu(\kappa')$, then $\kappa<\kappa'$.\item[(c)] If $\lev_\mu(\kappa)=\lev_\mu(\kappa')=j<k$ and $\delta_j(\kappa)<\delta_j(\kappa')$, then $\kappa<\kappa'$.\item[(d)] All keys with the same address at level $0$ are equal.\end{enumerate}\end{lemma}\begin{proof}Two numbers in the same block whose digits agree above position $j$ differ by $(\delta_j-\delta_j')\pi_j+\tau$ with $|\tau|<\pi_j$, where $\tau$ is the difference of their parts below $j$. So their order is the order of their $j$-th digits whenever those differ.(a) $\kappa$ and $\mu$ share the block and the digits above $j$, and $\kappa>\mu$, so $\delta_j(\kappa)>\delta_j(\mu)$.(b) Let $j'=\lev_\mu(\kappa')$. If $j'=k$, then $\beta(\kappa')=\beta(\mu)+1$ by Lemma~\ref{lem:window} while $\beta(\kappa)=\beta(\mu)$, so $\kappa<\kappa'$. If $j'<k$, both keys share the block and the digits above $j'$ with $\mu$, and $\delta_{j'}(\kappa)=\delta_{j'}(\mu)<\delta_{j'}(\kappa')$ by (a).(c) The keys share the block and the digits above $j$.(d) Such keys share the block and every digit.\end{proof}
\begin{lemma}[monotone level]\label{lem:mono}If $\mu\le\kappa'\le\kappa\le\mu+C$, then $\lev_\mu(\kappa')\le\lev_\mu(\kappa)$.\end{lemma}\begin{proof}Otherwise Lemma~\ref{lem:order}(b) gives $\kappa<\kappa'$.\end{proof}By Lemma~\ref{lem:order}(a), in a valid configuration the buckets $B_j[t]$ with $t\le\delta_j(\mu)$ are empty, except $B_0[\delta_0(\mu)]$, which holds exactly the items with key $\mu$.
\subsection{Operations}All digit computations are word operations; when every $\pi_j$ is a power of two they are shifts and masks.
\paragraph{Locate.} $\Loc(\kappa,h)$ returns $a_\mu(\kappa)$, given the promise $\lev_\mu(\kappa)\le h$. If $h=k$ and $\beta(\kappa)\ne\beta(\mu)$, it returns $(k,0)$. Otherwise it compares $\delta_j(\kappa)$ with $\delta_j(\mu)$ for $j=\min(h,k-1),\dots,1$ and returns at the first difference; if there is none it returns $(0,\delta_0(\kappa))$. Its cost is $O(1+h-\lev_\mu(\kappa))$.
\paragraph{Insert and decrease-key.} $\textsc{Insert}(x,\kappa)$ splices $x$ into $B_{\Loc(\kappa,k)}$. $\textsc{DecreaseKey}(x,\kappa')$, with $\mu\le\kappa'<K(x)$, unlinks $x$ from its level $j$ and splices it into $B_{\Loc(\kappa',j)}$, which is valid by Lemma~\ref{lem:mono}.
\paragraph{Extract-min.} See Algorithm~\ref{alg:extract}. When the frontier bucket is empty, the least nonempty level $j^\ast$ and its least nonempty bucket $t^\ast$ hold the minimum. The frontier moves to that minimum, and only that bucket is redistributed.
\begin{algorithm}[t]\caption{\textsc{ExtractMin} on $\mathrm{MRH}(r;C)$}\label{alg:extract}\begin{algorithmic}[1]\If{$B_0[\delta_0(\mu)]$ is empty} \State $j^\ast\gets$ least level with a nonzero count \Comment{$O(k)$} \If{$j^\ast=k$} $t^\ast\gets0$ \Else\ $t^\ast\gets$ least $t>\delta_{j^\ast}(\mu)$ with $B_{j^\ast}[t]$ nonempty \Comment{at most $r_{j^\ast}$ probes} \EndIf \State $\mu\gets\min\{K(y):y\in B_{j^\ast}[t^\ast]\}$ \If{$j^\ast\ge1$} \For{each $y$ in $B_{j^\ast}[t^\ast]$} \State move $y$ to $B_{\Loc(K(y),\,\min(j^\ast-1,k-1))}$ \EndFor \EndIf\EndIf\State remove any item $x$ from $B_0[\delta_0(\mu)]$ and \Return $(x,K(x))$\end{algorithmic}\end{algorithm}
\section{Correctness and cost}\label{sec:analysis}\begin{lemma}[frontier advance]\label{lem:advance}In a valid configuration with $B_0[\delta_0(\mu)]$ empty, let $j^\ast,t^\ast$ be as in Algorithm~\ref{alg:extract} and let $\mu'$ be the least key in $B_{j^\ast}[t^\ast]$. Then\begin{enumerate}\item[(i)] $\mu'$ is the least key in the heap;\item[(ii)] every item $x\notin B_{j^\ast}[t^\ast]$ satisfies $a_{\mu'}(K(x))=a_\mu(K(x))$;\item[(iii)] if $j^\ast\ge1$, every $y\in B_{j^\ast}[t^\ast]$ satisfies $\lev_{\mu'}(K(y))<j^\ast$; if $j^\ast=0$, every such $y$ has $K(y)=\mu'$ and address $(0,\delta_0(\mu'))$.\end{enumerate}\end{lemma}\begin{proof}(i) By Lemma~\ref{lem:order}(b), keys at levels above $j^\ast$ exceed keys at level $j^\ast$. By (c), keys in later buckets of level $j^\ast$ exceed keys in $B_{j^\ast}[t^\ast]$. The level-$k$ bucket is the only bucket of its level.
(iii) If $j^\ast=k$, every key in $B_k[0]$ lies in block $\beta(\mu)+1$ (Lemma~\ref{lem:window}), as does $\mu'$, so their levels relative to $\mu'$ are below $k$. If $1\le j^\ast<k$, the keys of $B_{j^\ast}[t^\ast]$, including $\mu'$, share the block and all digits from $j^\ast$ upward, so they differ from $\mu'$ only below $j^\ast$. If $j^\ast=0$, Lemma~\ref{lem:order}(d) gives $K(y)=\mu'$.
(ii) If $j^\ast=k$ there is no such $x$, since every lower level is empty. Let $j^\ast<k$, and let $x$ have address $(j_x,t_x)$ relative to $\mu$, with $j_x\ge j^\ast$. Relative to $\mu$, the new frontier $\mu'$ has the same block and the same digits above $j^\ast$, and $\delta_{j^\ast}(\mu')=t^\ast$. If $j_x=k$, then $\beta(K(x))\ne\beta(\mu)=\beta(\mu')$. If $j^\ast<j_x<k$, then $K(x)$ agrees with $\mu$, hence with $\mu'$, on the block and above $j_x$, and $\delta_{j_x}(K(x))\ne\delta_{j_x}(\mu)=\delta_{j_x}(\mu')$. If $j_x=j^\ast$, then $t_x\ne t^\ast=\delta_{j^\ast}(\mu')$, with agreement above. In each case the level and the digit are unchanged.\end{proof}
\begin{theorem}[correctness]\label{thm:correct}Starting from an empty heap, under (W) every operation preserves (I1)--(I2), $\mu$ never decreases, and each extract-min returns an item of least key. Successive extracted keys are nondecreasing.\end{theorem}\begin{proof}Insert and decrease-key place the item at its address under (W) and Lemma~\ref{lem:mono}. In extract-min, if $B_0[\delta_0(\mu)]$ is nonempty its items have key $\mu$, which is minimal by (I1). Otherwise Lemma~\ref{lem:advance} shows that $\mu'$ is the minimum, so $\mu'\ge\mu$ and (I1) holds for $\mu'$. Items outside the redistributed bucket keep valid addresses. Redistributed items are placed by $\Loc$ with a valid promise. The item of key $\mu'$ lands in $B_0[\delta_0(\mu')]$, which is therefore nonempty when the last line runs.\end{proof}
\begin{theorem}[amortised cost]\label{thm:cost}Consider any sequence on an initially empty $\mathrm{MRH}(r;C)$ with $n$ inserts, $m$ decrease-keys and at most $n$ extract-mins, satisfying (W). Let $E_j$ be the number of extract-mins with $j^\ast=j$, so $\sum_jE_j\le n$. The total time is\begin{equation}\label{eq:cost}O\Big(m+nk+\sum_{j<k}r_jE_j\Big)\;\subseteq\;O\big(m+n(k+\rmax)\big),\end{equation}and the space is $O(n+\sum_jr_j)$.\end{theorem}\begin{proof}\emph{Levels only decrease.} Decrease-key does not raise a level (Lemma~\ref{lem:mono}). A frontier advance leaves every other item's address unchanged and moves the redistributed items to strictly lower levels (Lemma~\ref{lem:advance}). Hence an item descends at most $k$ levels in total, and each redistribution of an item strictly lowers its level, so there are at most $nk$ redistribution moves.
\emph{Placement.} An insert costs $O(k)$, which totals $O(nk)$. A decrease-key or a redistribution move from level $j$ to level $j'$ costs $O(1+j-j')$. Over an item's lifetime the terms $j-j'$ sum to at most $k$. So decrease-keys cost $O(m+nk)$ in total and redistributions $O(nk)$. Computing $\mu'$ costs $O(|B_{j^\ast}[t^\ast]|)$, which is charged to the moves when $j^\ast\ge1$; when $j^\ast=0$, Lemma~\ref{lem:order}(d) lets any item supply $\mu'$.
\emph{Scanning.} Each extract-min that finds $B_0[\delta_0(\mu)]$ empty spends $O(k)$ finding $j^\ast$ from the counts, probes at most $r_{j^\ast}$ buckets (one if $j^\ast=k$), and redistributes one bucket. Summing over extract-mins gives $O(nk+\sum_jr_jE_j)$. Space comes from $\sum_jr_j+1$ bucket heads, $k+1$ counts and $O(1)$ words per item.\end{proof}Redistributing only one bucket per extract-min matters for the bound. It replaces the per-level sum $\sum_jr_j$ of a naive analysis by the single largest radix.
\begin{proposition}[best tuple for a given depth]\label{prop:tuple}For fixed $k$, every radix tuple for $C$ has $\rmax\ge\lceil(C+1)^{1/k}\rceil$, and the uniform tuple $r_j=\lceil(C+1)^{1/k}\rceil$ attains it.\end{proposition}\begin{proof}$\rmax^k\ge\prod_jr_j\ge C+1$.\end{proof}Unequal radices therefore do not improve the worst-case bound \eqref{eq:cost} at a given depth. What they allow is two things. First, $\pi_k=C+1$ exactly, whenever $C+1$ factors into $k$ parts of size at least two. Second, radices can be matched to how often each level is scanned, through the weights $E_j$ in \eqref{eq:cost}.
\section{Dijkstra's algorithm}\label{sec:dijkstra}Let $G=(V,E)$ be a directed graph with $|V|=n$, $|E|=m$, a source $s$ and lengths $\ell:E\to\{0,1,\dots,C\}$.
\begin{algorithm}[t]\caption{Dijkstra's algorithm on $\mathrm{MRH}(r;C)$}\label{alg:dijkstra}\begin{algorithmic}[1]\State $d(s)\gets0$; $d(v)\gets\infty$ for $v\ne s$; $H\gets\mathrm{MRH}(r;C)$ with $\mu=0$; $H.\textsc{Insert}(s,0)$\While{$H$ is nonempty} \State $(u,d(u))\gets H.\textsc{ExtractMin}()$ \For{each arc $(u,v)\in E$ with $v$ unsettled} \State $\delta\gets d(u)+\ell(u,v)$ \If{$d(v)=\infty$} $d(v)\gets\delta$; $H.\textsc{Insert}(v,\delta)$ \ElsIf{$\delta<d(v)$} $d(v)\gets\delta$; $H.\textsc{DecreaseKey}(v,\delta)$ \EndIf \EndFor\EndWhile\State \Return $d$\end{algorithmic}\end{algorithm}
\begin{proposition}[monotone use]\label{prop:window}Every insert and decrease-key issued by Algorithm~\ref{alg:dijkstra} satisfies (W).\end{proposition}\begin{proof}The first insert has key $0=\mu$. Every other call is made while relaxing the arcs of the vertex $u$ just extracted, when $\mu=d(u)$, and has key $d(u)+\ell(u,v)\in[\mu,\mu+C]$.\end{proof}
\begin{theorem}[multi-radix Dijkstra]\label{thm:dijkstra}Algorithm~\ref{alg:dijkstra} returns $d(v)=\mathrm{dist}_G(s,v)$ for every $v$, in time $O(m+n(k+\rmax))$ and space $O(n+\sum_jr_j)$ beyond the graph.\end{theorem}\begin{proof}Dijkstra's algorithm is correct with any priority queue that implements insert, decrease-key and extract-min correctly on the keys it presents. By Proposition~\ref{prop:window} and Theorem~\ref{thm:correct}, $\mathrm{MRH}(r;C)$ does so. Each vertex is inserted and extracted at most once, and each arc causes at most one decrease-key, when its tail is extracted. Theorem~\ref{thm:cost} with $O(n+m)$ for traversal gives the bound.\end{proof}
\begin{corollary}[special cases]\label{cor:special}\begin{enumerate}\item[(i)] \emph{Binary radices}, $r=(2,\dots,2)$ with $k=\lceil\log_2(C+1)\rceil$: $O(m+n\log C)$, the bound of the one-level radix heap~\cite{amot}.\item[(ii)] \emph{Uniform radices} $\Delta$ with $k=\lceil\log_\Delta(C+1)\rceil$: $O(m+n(\log_\Delta C+\Delta))$. With $\Delta=\Theta(\log C/\log\log C)$, $\log\Delta=\Theta(\log\log C)$, so this is $O(m+n\log C/\log\log C)$, the bound of the two-level radix heap~\cite{amot}.\item[(iii)] \emph{One level}, $k=1$ and $r_0=C+1$: the structure is Dial's array of $C+1$ unit buckets~\cite{dial}, and the bound is $O(m+nC)$.\end{enumerate}\end{corollary}Faster asymptotic bounds for integer-weighted shortest paths are known on the word RAM~\cite{thorup96,thorup04}, and the two-level radix heap with Fibonacci heaps improves (ii)~\cite{amot}. The multi-radix heap is aimed at a simple, array-based structure with an explicit radix dial.
\section{Operation-count ablation}\label{sec:exp}We report a stored ablation produced by the reference implementation described in Section~\ref{sec:impl}. Its result file is \texttt{radix\_ablation.json} and its script is \texttt{test\_mrh.py}. The graph is a random directed graph with $n=5{,}000$ vertices and $m=30{,}000$ arcs: a spanning path plus uniformly random arcs, with lengths uniform in $\{0,\dots,4095\}$. Here $C=4095$, so every tuple has $\pi_k=4096$. For each of eight tuples, the script runs Dijkstra from vertex $0$ and asserts that the distances equal those of a binary-heap Dijkstra before writing the file. All eight runs passed. Three counters are recorded: \emph{locate} (digit comparisons during placement), \emph{scans} (bucket probes during extract-min) and \emph{moves} (redistributed items). These are operation counts, not times. This implementation locates every key from the top level downward, so its locate count is at most $k+1$ per placement rather than the descent-proportional cost used in Theorem~\ref{thm:cost}.
\begin{center}\small\begin{tabular}{lrrrrrrr}\topruleRadices & $k$ & $\sum_jr_j$ & $\rmax$ & locate & scans & moves & total\\\midrule$(2)^{12}$ & 12 & 24 & 2 & 237,631 & 5,944 & 27,714 & 271,289\\$(4)^{6}$ & 6 & 24 & 4 & 106,414 & 9,150 & 21,907 & 137,471\\$(8)^{4}$ & 4 & 32 & 8 & 65,347 & 15,396 & 17,797 & 98,540\\$(16)^{3}$ & 3 & 48 & 16 & 46,324 & 27,511 & 14,895 & 88,730\\$(64)^{2}$ & 2 & 128 & 64 & 28,845 & 99,825 & 11,089 & 139,759\\$(2,4,8,64)$ & 4 & 78 & 64 & 54,723 & 13,365 & 15,643 & 83,731\\$(64,8,4,2)$ & 4 & 78 & 64 & 65,283 & 96,095 & 15,524 & 176,902\\$(4096)$, Dial & 1 & 4,096 & 4,096 & 14,343 & 5,983,094 & 6,415 & 6,003,852\\\bottomrule\end{tabular}\end{center}
Among uniform tuples, locate and move counts fall and scan counts rise as $k$ decreases and $\rmax$ grows, which is the trade-off in \eqref{eq:cost}. The lowest total, 83,731, is for the mixed tuple $(2,4,8,64)$. The tuples $(2,4,8,64)$ and $(64,8,4,2)$ have the same radices in opposite order. Their scan counts differ by a factor of 7.2 (13,365 against 96,095), although their worst-case bounds are identical. The refined bound $\sum_jr_jE_j$ predicts a difference of this kind, since it weights each radix by how often its level is scanned. The script did not record the $E_j$, so this explanation is not tested here. The Dial row's 5,983,094 scans lie within the bound $n\,\rmax=20{,}480{,}000$.
\section{Implementations}\label{sec:impl}\paragraph{Reference implementation.} The Python implementation \texttt{mrh.py} used in Section~\ref{sec:exp} follows Section~\ref{sec:def}. It has digit-based placement relative to $\mu$, one overflow bucket, per-level counts, and one redistributed bucket per extract-min. It differs in two inessential ways. It locates from the top level, and it scans a level from bucket $0$ instead of from $\delta_{j^\ast}(\mu)+1$. Those buckets are empty by Lemma~\ref{lem:order}(a), so the scan cost changes by at most a constant factor. With top-down location, decrease-keys cost $O(k)$ each and redistribution moves $O(k)$ each, so its worst-case bound is $O(mk+nk^2+n\rmax)$.
\paragraph{The \texttt{gptrun} implementation.} The Go implementation in \texttt{gptrun}~\cite{gptrun} uses explicit level bounds $L_j$ and active indices in the style of Denardo--Fox buckets, with a top block $[L_{k-1},L_{k-1}+\pi_k)$. When an inserted key falls beyond the top block, it re-files every item relative to $\mu$ (``rebase''). This is correct under \eqref{eq:cover}, but Theorem~\ref{thm:cost} does not cover it.
\begin{remark}[rebasing can be quadratic]Let $\pi_k=C+1$ and $C\ge n$. Take a path $v_0\to v_1\to\dots\to v_t$ with unit lengths, and an arc of length $C$ from each $v_i$ to a fresh vertex $w_i$. Settling $v_i$ sets $\mu=i$ and inserts $w_i$ with key $i+C$. The previous rebase set $L_{k-1}=i-1$, so the key exceeds the top block and triggers a rebase, which re-files the $\Theta(i)$ vertices $w_0,\dots,w_{i-1}$ still in the queue. The total rebasing work is $\Theta(t^2)=\Theta(n^2)$. The overflow bucket of Section~\ref{sec:def} avoids this.\end{remark}
\section{Limitations}\begin{itemize}\item The analysis is amortised over a sequence that starts empty and satisfies the window condition (W). The heap is not a general-purpose priority queue.\item Digit extraction is assumed to take $O(1)$ time. For radices that are not powers of two this needs division by the place values.\item The ablation is one graph family at one $C$, and it reports operation counts from an implementation with top-down location, not wall-clock times. We make no claim about practical speed relative to other queues.\item Unequal radices do not improve the worst-case bound at fixed depth (Proposition~\ref{prop:tuple}). A rule for choosing radices from the level weights $E_j$ is left open.\end{itemize}
\section{Related structures}\begin{center}\small\begin{tabular}{p{0.24\linewidth}p{0.2\linewidth}p{0.47\linewidth}}\topruleStructure & Key model & Relation to MRH\\\midruleBinary / $d$-ary heap & comparisons & No buckets; $\Theta(\log_dn)$ per operation.\\Fibonacci heap~\cite{fredmantarjan} & comparisons & $O(1)$ amortised insert and decrease-key, $O(\log n)$ extract-min; no radix geometry.\\van Emde Boas tree~\cite{veb} & integers in $[0,U)$ & Recursive universe reduction, $O(\log\log U)$ per operation.\\Dial buckets~\cite{dial} & monotone integers & The one-level MRH with $r_0=C+1$.\\Denardo--Fox buckets~\cite{denardofox} & monotone integers & Uniform branching per level; MRH allows unequal radices and uses frontier-relative placement with an overflow bucket.\\Radix heaps~\cite{johnson,amot} & monotone integers & One sequence of widths (powers of $2$ or $\Delta$); their bounds are recovered by binary and uniform tuples (Corollary~\ref{cor:special}).\\Hot queues~\cite{cgs} & monotone integers & Multi-level buckets combined with a heap.\\Soft heap~\cite{chazelle} & comparisons & Deliberate key corruption; unrelated.\\\bottomrule\end{tabular}\end{center}
\bibliographystyle{unsrtnat}\bibliography{refs}\end{document}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879\begin{thebibliography}{10}
\bibitem{thorup96}Mikkel Thorup.\newblock On RAM priority queues.\newblock In \emph{Proceedings of the Seventh Annual ACM--SIAM Symposium on Discrete Algorithms}, pages 59--67, 1996.
\bibitem{costa}Jonas Costa, Lucas Castro, and Rosiane de Freitas.\newblock Exploring monotone priority queues for Dijkstra optimization.\newblock arXiv:2409.06061, 2024.
\bibitem{dijkstra}Edsger W. Dijkstra.\newblock A note on two problems in connexion with graphs.\newblock \emph{Numerische Mathematik}, 1:\penalty0 269--271, 1959.
\bibitem{dial}Robert B. Dial.\newblock Algorithm 360: Shortest-path forest with topological ordering.\newblock \emph{Communications of the ACM}, 12(11):\penalty0 632--633, 1969.
\bibitem{denardofox}Eric V. Denardo and Bennett L. Fox.\newblock Shortest-route methods: 1. reaching, pruning, and buckets.\newblock \emph{Operations Research}, 27(1):\penalty0 161--186, 1979.
\bibitem{johnson}Donald B. Johnson.\newblock Efficient algorithms for shortest paths in sparse networks.\newblock \emph{Journal of the ACM}, 24(1):\penalty0 1--13, 1977.
\bibitem{amot}Ravindra K. Ahuja, Kurt Mehlhorn, James B. Orlin, and Robert E. Tarjan.\newblock Faster algorithms for the shortest path problem.\newblock \emph{Journal of the ACM}, 37(2):\penalty0 213--223, 1990.
\bibitem{cgs}Boris V. Cherkassky, Andrew V. Goldberg, and Craig Silverstein.\newblock Buckets, heaps, lists, and monotone priority queues.\newblock \emph{SIAM Journal on Computing}, 28(4):\penalty0 1326--1346, 1999.
\bibitem{goldbergsilverstein}Andrew V. Goldberg and Craig Silverstein.\newblock Implementations of Dijkstra's algorithm based on multi-level buckets.\newblock In \emph{Network Optimization}, volume 450 of Lecture Notes in Economics and Mathematical Systems, pages 292--327. Springer, 1997.
\bibitem{tlx}TLX.\newblock tlx::RadixHeap class template reference.\newblock \url{https://tlx.github.io/classtlx_1_1RadixHeap.html}, 2026.\newblock Accessed 2026.
\bibitem{thorup04}Mikkel Thorup.\newblock Integer priority queues with decrease key in constant time and the single source shortest paths problem.\newblock \emph{Journal of Computer and System Sciences}, 69(3):\penalty0 330--353, 2004.
\bibitem{gptrun}Encryptid Systems.\newblock gptrun: package \texttt{internal/hes}, file \texttt{mrh.go}.\newblock \url{https://github.com/EncryptidSystems/gptrun/tree/main/internal/hes}, 2026.
\bibitem{fredmantarjan}Michael L. Fredman and Robert E. Tarjan.\newblock Fibonacci heaps and their uses in improved network optimization algorithms.\newblock \emph{Journal of the ACM}, 34(3):\penalty0 596--615, 1987.
\bibitem{veb}Peter van Emde Boas, R. Kaas, and E. Zijlstra.\newblock Design and implementation of an efficient priority queue.\newblock \emph{Mathematical Systems Theory}, 10(1):\penalty0 99--127, 1976.
\bibitem{chazelle}Bernard Chazelle.\newblock The soft heap: an approximate priority queue with optimal error rate.\newblock \emph{Journal of the ACM}, 47(6):\penalty0 1012--1027, 2000.
\end{thebibliography}12345678910111213141516171819202122232425262728body { padding: 2rem; font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;}
h1 { font-size: 16px; margin-top: 0;}
p { color: rgb(107, 114, 128); font-size: 15px; margin-bottom: 10px; margin-top: 5px;}
.card { max-width: 620px; margin: 0 auto; padding: 16px; border: 1px solid lightgray; border-radius: 16px;}
.card p:last-child { margin-bottom: 0;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123// 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) { var body = MACROS[name]; // A letter body glued to the previous control word (\in\Bo -> \inB). if (body.charAt(0) !== '\\') return '{' + body + '}'; return body; }); }
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 peelRules(t) { var before = false; var guard = 0; while (guard++ < 8) { var m = /^\s*\\(?:toprule|midrule|bottomrule|hline)\s*/.exec(t); if (!m) break; before = true; t = t.slice(m[0].length); } return { before: before, text: t }; }
function parseTabular(body) { var rows = []; splitRows(body).forEach(function (raw) { var t = raw.trim(); if (!t) return; var peeled = peelRules(t); if (!peeled.text) { if (rows.length && peeled.before) rows[rows.length - 1].ruleAfter = true; else if (peeled.before) rows.push({ ruleBefore: true, cells: [], ruleAfter: false }); return; } var rule = peeled.before; t = peeled.text; 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('\\appendix', i) && !/[a-zA-Z]/.test(s[i + 9] || '')) { flush(); blocks.push({ type: 'appendix' }); i += 9; continue; } if (s.startsWith('\\bibliographystyle', i)) { flush(); var bs = i + '\\bibliographystyle'.length; if (s[bs] === '{') bs = readBrace(s, bs).end; i = bs; 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; }
var ALGO_OPEN = { If: 'if ', For: 'for ', While: 'while ' }; var ALGO_CLOSE = { EndIf: 1, EndFor: 1, EndWhile: 1, EndProcedure: 1, EndFunction: 1 };
function readAlgoCmd(s, i) { var m = /^\\([A-Za-z]+)\s*/.exec(s.slice(i)); if (!m) return null; return { name: m[1], end: i + m[0].length }; }
function parseAlgo(body) { var lines = []; var indent = 0; var i = 0; function emit(kind, text, ind) { lines.push({ kind: kind, text: text.trim(), indent: ind, comment: '' }); } function restUntilCmd() { var j = i; while (j < body.length && body[j] !== '\\') j++; var text = body.slice(i, j); i = j; return text; } while (i < body.length) { while (i < body.length && /\s/.test(body[i])) i++; if (i >= body.length) break; if (body[i] !== '\\') { var extra = restUntilCmd().trim(); if (extra && lines.length) lines[lines.length - 1].text += ' ' + extra; continue; } var cmd = readAlgoCmd(body, i); if (!cmd) { i++; continue; } i = cmd.end; var arg = ''; if (body[i] === '{') { var b = readBrace(body, i); arg = b.text; i = b.end; } if (cmd.name === 'Comment') { if (lines.length) lines[lines.length - 1].comment = arg; continue; } if (ALGO_CLOSE[cmd.name]) { indent = Math.max(0, indent - 1); continue; } if (cmd.name === 'Else' || cmd.name === 'ElsIf') { emit(cmd.name, cmd.name === 'Else' ? 'else' : 'else if ' + arg, Math.max(0, indent - 1)); continue; } if (ALGO_OPEN[cmd.name]) { emit(cmd.name, ALGO_OPEN[cmd.name] + arg, indent); indent++; continue; } if (cmd.name === 'Return') { var ret = ('return ' + restUntilCmd()).trim(); if (lines.length && lines[lines.length - 1].kind === 'State') { lines[lines.length - 1].text = lines[lines.length - 1].text.replace(/\s+$/, '') + ' ' + ret; } else emit('Return', ret, indent); continue; } if (cmd.name === 'State') { emit('State', restUntilCmd(), indent); continue; } emit(cmd.name, (arg ? arg + ' ' : '') + restUntilCmd(), indent); } return lines; }
function parseAlgorithm(body) { var cap = ''; var id = null; var c = /\\caption\{/.exec(body); if (c) cap = readBrace(body, c.index + '\\caption'.length).text; var lab = /\\label\{([^}]*)\}/.exec(body); if (lab) id = lab[1]; var inner = ''; var alg = /\\begin\{algorithmic\}(?:\[[^\]]*\])?/.exec(body); if (alg) { var start = alg.index + alg[0].length; var end = body.indexOf('\\end{algorithmic}', start); inner = end < 0 ? body.slice(start) : body.slice(start, end); } return { type: 'algorithm', caption: cap, id: id, lines: parseAlgo(inner) }; }
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', opt: opt, 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 === 'algorithm') return parseAlgorithm(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 items = []; var re = /\\bibitem\b/g; var starts = []; var m; while ((m = re.exec(body))) starts.push(m.index); starts.forEach(function (pos, idx) { var i = pos + '\\bibitem'.length; if (body[i] === '[') i = readBracket(body, i).end; if (body[i] !== '{') return; var key = readBrace(body, i); var end = idx + 1 < starts.length ? starts[idx + 1] : body.length; items.push({ key: key.text, text: body.slice(key.end, end).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 === 'appendix') { state.appendix = true; state.sec = 0; state.sub = 0; return; } 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 = state.appendix ? String.fromCharCode(64 + state.sec) : String(state.sec); } else if (n.level === 2) { state.sub++; var secNo = state.appendix ? String.fromCharCode(64 + state.sec) : String(state.sec); n.num = secNo + '.' + 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 === 'algorithm') { state.alg++; n.num = String(state.alg); if (n.id) state.labels[n.id] = n.num; assignMath(n.caption, state); n.lines.forEach(function (ln) { assignMath(ln.text, state); if (ln.comment) assignMath(ln.comment, 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 === 'newblock') { out += ' '; i = p; continue; } if (cmd === 'penalty') { while (p < s.length && /[0-9]/.test(s[p])) p++; i = p; continue; } if (cmd === 'url') { var u = readBrace(s, p); out += '<a href="' + esc(u.text) + '">' + esc(u.text) + '</a>'; i = u.end; continue; } if (cmd === 'cite' || cmd === 'citep' || cmd === 'citet') { 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 proofName = (n.opt && String(n.opt).trim()) || 'Proof'; var bodyHtml = mergeBody('<span class="proof-head"><em>' + esc(proofName) + '.</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) { if (/\.pdf$/i.test(src)) src = src.replace(/\.pdf$/i, '.png'); return '<img src="' + esc(src) + '" alt="">'; }).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 === 'algorithm') { var rows = n.lines.map(function (ln) { var comment = ln.comment ? ' <span class="algo-comment">' + inline(ln.comment, state) + '</span>' : ''; return '<li class="d' + ln.indent + '"><span class="algo-body">' + inline(ln.text, state) + '</span>' + comment + '</li>'; }).join(''); var aid = n.id ? ' id="' + esc(n.id) + '"' : ''; return '<figure class="algo"' + aid + '><figcaption><strong>Algorithm ' + esc(n.num) + '.</strong> ' + inline(n.caption, state) + '</figcaption><ol class="algo-lines">' + rows + '</ol></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 initialCounters(preamble) { var counters = {}; var re = /\\setcounter\s*\{([^}]+)\}\s*\{(\d+)\}/g; var m; while ((m = re.exec(preamble))) counters[m[1]] = +m[2]; return counters; }
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, alg: 0, appendix: false, counters: initialCounters(preamble), 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);.gitattributes+1
README.md+16-4
index.html+135-17
multi_radix_heap.pdfAdded+3
multi_radix_heap.texAdded+289
refs.bblAdded+79
style.cssDeleted-28
tex2html.jsAdded+1123