diff --git a/README.md b/README.md index 54ad27b..687019f 100644 --- a/README.md +++ b/README.md @@ -469,7 +469,7 @@ from the font's MATH assembly parts. `\\left...\\right` target sizing follows the assignable TeX parameters `\\delimiterfactor` (default 901) and `\\delimitershortfall` (default 5pt), including local and global assignments. -Route-D text faces follow the NFSS declarations and compose with the surrounding run: `\sffamily\bfseries` selects cmssbx10, `\sffamily\itshape` selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. `\scshape`/`\textsc` select the real cmcsc10 small-caps face, `\slshape`/`\textsl` use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and `\ttfamily\itshape` reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Characters outside a program's encoding fall back per glyph to a Liberation subset, so the ASCII letters of an accented word still use Computer Modern and Greek text keeps its Unicode text under PDF extraction, including capital Omega, because the embedded Type1 faces carry a ToUnicode CMap built from the requested characters rather than relying on glyph names. Accent commands such as `\'`, `` \` ``, `\"`, `\^`, `\~`, `\c`, `\v` and `\=` compose precomposed Unicode letters and fall back to the base letter plus a combining mark. `\textsuperscript` and `\textsubscript` set a 70% run raised or lowered by 0.4em. `\MakeUppercase` and `\MakeLowercase` (also `\uppercase`/`\lowercase`) transform their braced text while keeping the surrounding face. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. Section-wide declarations such as `\bfseries` apply from where they appear to the end of their group, and `\em` toggles emphasis relative to the surrounding face. Paragraph base sizes come from `\fontsize{}{}` and the article size commands (`\tiny` through `\Huge`), scaling glyph metrics and the default interline glue while the measure, indentation and authored skips stay absolute. The class options `10pt`/`11pt`/`12pt` on `\documentclass[...]` set the default base size (and article `\baselineskip` of 12pt/13.6pt/14.5pt), and `\linespread{factor}` (or `\renewcommand{\baselinestretch}{factor}`) scales that baseline; a size command inside a paragraph overrides the class default and keeps its own glyph size in that run. Inline math inside a styled run keeps its math face while the surrounding text retains its style. The paragraph measure follows `\textwidth`/`\hsize` (or `\setlength{\textwidth}{...}`), and `\setlength` accepts the other supported layout lengths, including a `\parskip` with plus/minus glue; a counter declared with `\newcounter{name}` starts at zero and can be changed by `\setcounter`/`\addtocounter`, and a length declared with `\newlength{\name}` can be set by `\setlength{\name}{...}` and then used as the value of a later `\setlength{\parindent}{\name}`, and `\addtolength{\name}{...}` adds to such a length, so class code that stores its dimensions in named lengths takes effect. The `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom`/`textwidth`/`textheight` options (or `\geometry{...}`) are applied to the page measure and height; other package code is not executed. Block environments `center`, `flushleft` and `flushright` set the paragraph alignment, and aligned short lines are centring/flushing within the full measure rather than at the natural line width. A leading `\noindent` starts its paragraph flush with the measure. Page numbers print centred below the text block, `\setcounter{page}` offsets the printed number, `\addtocounter{page}` shifts it (`\pagenumbering` resets it to 1), and `\pagenumbering{roman|Roman|alph|Alph|arabic}` changes their format and `\pagestyle{empty}` suppresses them on every page and `\thispagestyle{empty}` on the first page. `\title`, `\author` and `\date` are captured from the preamble, `\today` expands to the current date, and `\maketitle` expands into a centered title block at the article class sizes (using today's date when `\date` is absent and none for `\date{}`). `\section`, `\subsection`, `\subsubsection`, `\paragraph` and `\subparagraph` advance five-level article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize` (the two deepest levels stay at the base size); starred headings stay unnumbered, and an optional `[short]` title replaces the long title in the table of contents. The `abstract` environment expands into a centered bold heading and a 9pt body, and `\maketitle` joins multiple `\and` authors and turns `\thanks` notes into title footnotes. Section labels resolve `\ref`/`\eqref` to the heading number (standalone `\label` lines attach to the previous heading, unknown references print `??`), `\appendix` restarts sectioning with letter numbers, `\tableofcontents` lists the numbered headings through `\subsubsection` with their page numbers right-aligned after dot leaders (the default article `tocdepth` of 3, changed by `\setcounter{tocdepth}`), `\setcounter{secnumdepth}` limits which levels are numbered, `\setcounter{section}`/`{figure}`/`{table}`/`{equation}`/`{theorem}` offsets the next counter value, `\listoffigures`/`\listoftables` reproduce the numbered captions with each float's page number right-aligned after dot leaders, `verbatim` keeps monospaced source lines, `\verb|...|` renders inline literal text monospaced, and text commands such as `\LaTeX`, `\TeX`, `\ldots`, `\S`, `\ss`, `\ae`, `\oe`, `\o`, `\l`, `\dh`, `\th`, `\textdegree`, `\textmu`, `\textonehalf` and `\texteuro` expand to their characters (a control word swallows the spaces that follow it), `\href` keeps its link text and paints a PDF `/Link` URI annotation over the label, and `\url` becomes typewriter text, and the `abstract` environment expands to its heading and body. In route-D, math uses Computer Modern metrics from the bundled `cmmi10`, `cmsy10`, `cmex10`, `msbm10` and `eufm10` TFMs and embeds their Type1 programs, so italic letters, relation symbols, big operators, `\mathcal` capitals, `\mathbb` capitals and `\mathfrak` Fraktur letters each paint with their own face. Fractions can be written as `\frac` or with TeX's infix forms (`\over`, `\atop`, `\choose`, `\brace`, `\brack`, `\overwithdelims`, `\atopwithdelims`); only `\over`-style fractions draw a bar and fractions never draw parentheses. `displaymath` and `math` environments are accepted alongside `$$`, `\[` and `\(...\)`, and a `cases` environment stacks its `&`-separated rows beside a brace sized to the column extent. `\left`/`\right` choose CMEX delimiter sizes from the body extent using TeX's delimiterfactor and shortfall, `\middle` delimiters are sized with their group, and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size. `align`/`align*` displays share column widths, right-align even columns at their relations, and number each row (with `\tag`/`\notag` per row); `gather`/`gather*` centre each row instead. Inter-atom spacing uses TeX's 3/4/5mu classes (`1mu` is `1/18em`), `\mid` is a relation and `\colon` punctuation, and `\mskip`/`\mkern`/`\mspace`/`\hskip`/`\kern`/`\hspace` scan TeX dimensions, taking the natural width of any `plus`/`minus` parts. `\footnote{...}` leaves a numbered marker in the paragraph and sets the note as a 9pt page insertion at the bottom of the page that mentions it. A `thebibliography` environment turns its `\bibitem` entries into numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`; optional citation notes are dropped, `\citep`/`\citet` behave like `\cite`, `\nocite` is ignored, and `\bibliography`/`\bibliographystyle` are consumed without BibTeX). A `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and feeds `\ref`, and `\includegraphics` embeds the referenced project image when it decodes (PNG/JPEG/BMP become a PDF XObject; missing or undecodable files keep the rule placeholder), a standalone `\includegraphics` paragraph becomes an in-text graphic float, and a standalone `\rule{width}{height}` becomes an in-text rule box; `width=`/`height=` take dimensions or fractions of `\textwidth`/`\textheight`, `scale=` a percentage, `keepaspectratio` fits both dimensions, and `\graphicspath` directories are searched (with `.png`/`.jpg`/`.bmp` fallbacks) when a path has no suffix. `table` environments likewise become floats carrying their captured `tabular` body, with `Table n:` captions that resolve from `\ref`. Table captions sit above the tabular as in LaTeX, figure captions below the graphic, and `\caption*` leaves either unnumbered; an optional `[short]` caption is used by `\listoffigures`/`\listoftables` while the long caption stays on the float; the glue on each side of a tabular column follows `\tabcolsep` (6pt by default), `\arraystretch` scales the tabular row heights, a begin-position option is accepted and ignored, and `\\[dim]` adds an extra gap after that row, and `|` rules in the column template paint vertical rules, and `*{n}{cols}` repeats a column group, and `\renewcommand` can rename the `Figure`/`Table` caption prefixes, the `Abstract` heading, and the `References`/`Contents`/`List of Figures`/`List of Tables` headings that open the bibliography, table of contents and float lists. Theorem-like environments (`theorem`, `lemma`, `corollary`, `proposition`, `definition`, `example`, `remark`, `proof`) produce a bold numbered heading with an optional `[title]`, italic statements for the theorem group, and unnumbered proofs whose optional argument replaces the heading, with `\label`/`\ref` resolving to the theorem number. `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` add custom theorem environments: a shared counter numbers the env with its parent, `[section]` scopes numbers to the enclosing section, and the starred form stays unnumbered. In project previews and PDF exports, `\input{...}` and `\include{...}` expand from files in the same project (a missing `.tex` suffix is added), so chapter files render in place; a project's own `.sty`/`.cls` files are inlined for `\usepackage{name}`/`\documentclass{name}` with local `\RequirePackage` dependencies inlined recursively, local base classes named by `\LoadClass`/`\LoadClassWithOptions` inlined the same way, class and package bodies inlining their local `\input{...}` files (missing files are dropped), and package/class boilerplate dropped, `\AtBeginDocument`/`\AtEndDocument` bodies executed, and `\makeatletter`/`\makeatother` stripped; local class and package files run their `\DeclareOption` code for the options named on `\documentclass[...]` / `\usepackage[...]` (with `\ExecuteOptions` defaults), and preamble `\PassOptionsToPackage`/`\PassOptionsToClass` lines are merged into the next request, and unknown paths stay as literal text. Preview JSON also reports a `warnings` array naming environments route-D cannot lay out and control words that survived layout, so unsupported source is reported rather than silently typeset. Route-D project previews are memoised by a hash of the expanded source (32 entries) and invalidated on edit; PDF exports cache the last eight results and the cache key also covers decoded image bytes, so replacing an image re-renders both. A malformed source answers 422 with a JSON error body and never populates either cache. `itemize`/`enumerate`/`description` environments nest arbitrarily: bullet labels cycle `•`/`–`/`*`, sub-enumerations use `(a)`, roman and upper-letter labels, description items print their `[term]` in bold before the definition, an optional `\item[label]` replaces the generated marker, each depth adds 12pt of indentation, and list items take article's per-level `\topsep`, `\itemsep` and `\partopsep` (top level 8+2/4pt at 10pt, 9+3/4.5pt at 11pt and 10+3/5pt at 12pt; second level 4+2/2pt, 4.5+3/2pt and 5+3/2pt) unless `\setlength{\topsep}`, `\setlength{\itemsep}` or `\setlength{\partopsep}` override them, a wrapped item hangs its continuation lines at the text indent while its first line stays at the bullet indent, and an `\setcounter{enumi}` (or `enumii`/`enumiii`/`enumiv`) line before the first `\item` resumes enumerate numbering. A `quotation` environment splits its blank-line-separated paragraphs into blocks indented 20pt on both sides, and `quote` uses the same 20pt margins, and `verse` keeps its explicit line breaks as separate 20pt-indented lines, and a `minipage{w}` environment lays its body out at width `w` (its optional position argument is ignored). +Route-D text faces follow the NFSS declarations and compose with the surrounding run: `\sffamily\bfseries` selects cmssbx10, `\sffamily\itshape` selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. `\scshape`/`\textsc` select the real cmcsc10 small-caps face, `\slshape`/`\textsl` use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and `\ttfamily\itshape` reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Characters outside a program's encoding fall back per glyph to a Liberation subset, so the ASCII letters of an accented word still use Computer Modern and Greek text keeps its Unicode text under PDF extraction, including capital Omega, because the embedded Type1 faces carry a ToUnicode CMap built from the requested characters rather than relying on glyph names. Accent commands such as `\'`, `` \` ``, `\"`, `\^`, `\~`, `\c`, `\v` and `\=` compose precomposed Unicode letters and fall back to the base letter plus a combining mark. `\textsuperscript` and `\textsubscript` set a 70% run raised or lowered by 0.4em. `\MakeUppercase` and `\MakeLowercase` (also `\uppercase`/`\lowercase`) transform their braced text while keeping the surrounding face. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. Section-wide declarations such as `\bfseries` apply from where they appear to the end of their group, and `\em` toggles emphasis relative to the surrounding face. Paragraph base sizes come from `\fontsize{}{}` and the article size commands (`\tiny` through `\Huge`), scaling glyph metrics and the default interline glue while the measure, indentation and authored skips stay absolute. The class options `10pt`/`11pt`/`12pt` on `\documentclass[...]` set the default base size (and article `\baselineskip` of 12pt/13.6pt/14.5pt), and `\linespread{factor}` (or `\renewcommand{\baselinestretch}{factor}`) scales that baseline; a size command inside a paragraph overrides the class default and keeps its own glyph size in that run. Inline math inside a styled run keeps its math face while the surrounding text retains its style. The paragraph measure follows `\textwidth`/`\hsize` (or `\setlength{\textwidth}{...}`), and `\setlength` accepts the other supported layout lengths, including a `\parskip` with plus/minus glue; a counter declared with `\newcounter{name}` starts at zero and can be changed by `\setcounter`/`\addtocounter`, and a length declared with `\newlength{\name}` can be set by `\setlength{\name}{...}` and then used as the value of a later `\setlength{\parindent}{\name}`, and `\addtolength{\name}{...}` adds to such a length, so class code that stores its dimensions in named lengths takes effect. The `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom`/`textwidth`/`textheight` options (or `\geometry{...}`) are applied to the page measure and height; other package code is not executed. Block environments `center`, `flushleft` and `flushright` set the paragraph alignment, and aligned short lines are centring/flushing within the full measure rather than at the natural line width. A leading `\noindent` starts its paragraph flush with the measure. Page numbers print centred below the text block, `\setcounter{page}` offsets the printed number, `\addtocounter{page}` shifts it (`\pagenumbering` resets it to 1), and `\pagenumbering{roman|Roman|alph|Alph|arabic}` changes their format and `\pagestyle{empty}` suppresses them on every page and `\thispagestyle{empty}` on the first page. `\title`, `\author` and `\date` are captured from the preamble, `\today` expands to the current date, and `\maketitle` expands into a centered title block at the article class sizes (using today's date when `\date` is absent and none for `\date{}`). `\section`, `\subsection`, `\subsubsection`, `\paragraph` and `\subparagraph` advance five-level article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize` (the two deepest levels stay at the base size); starred headings stay unnumbered, and an optional `[short]` title replaces the long title in the table of contents. The `abstract` environment expands into a centered bold heading and a 9pt body, and `\maketitle` joins multiple `\and` authors and turns `\thanks` notes into title footnotes. Section labels resolve `\ref`/`\eqref` to the heading number (standalone `\label` lines attach to the previous heading, unknown references print `??`), `\appendix` restarts sectioning with letter numbers, `\tableofcontents` lists the numbered headings through `\subsubsection` with their page numbers right-aligned after dot leaders (the default article `tocdepth` of 3, changed by `\setcounter{tocdepth}`), `\setcounter{secnumdepth}` limits which levels are numbered, `\setcounter{section}`/`{figure}`/`{table}`/`{equation}`/`{theorem}` offsets the next counter value, `\listoffigures`/`\listoftables` reproduce the numbered captions with each float's page number right-aligned after dot leaders, `verbatim` keeps monospaced source lines, `\verb|...|` renders inline literal text monospaced, and text commands such as `\LaTeX`, `\TeX`, `\ldots`, `\S`, `\ss`, `\ae`, `\oe`, `\o`, `\l`, `\dh`, `\th`, `\textdegree`, `\textmu`, `\textonehalf` and `\texteuro` expand to their characters (a control word swallows the spaces that follow it), `\href` keeps its link text and paints a PDF `/Link` URI annotation over the label, and `\url` becomes typewriter text, and the `abstract` environment expands to its heading and body. In route-D, math uses Computer Modern metrics from the bundled `cmmi10`, `cmsy10`, `cmex10`, `msbm10` and `eufm10` TFMs and embeds their Type1 programs, so italic letters, relation symbols, big operators, `\mathcal` capitals, `\mathbb` capitals and `\mathfrak` Fraktur letters each paint with their own face. Fractions can be written as `\frac` or with TeX's infix forms (`\over`, `\atop`, `\choose`, `\brace`, `\brack`, `\overwithdelims`, `\atopwithdelims`); only `\over`-style fractions draw a bar and fractions never draw parentheses. `displaymath` and `math` environments are accepted alongside `$$`, `\[` and `\(...\)`, and `cases`, `matrix`/`pmatrix`/`bmatrix`/`Bmatrix`/`vmatrix`/`Vmatrix` and `array` environments build a grid with the matching delimiters (an `array` column spec chooses left, centred or right alignment). `\left`/`\right` choose CMEX delimiter sizes from the body extent using TeX's delimiterfactor and shortfall, `\middle` delimiters are sized with their group, and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size. `align`/`align*` displays share column widths, right-align even columns at their relations, and number each row (with `\tag`/`\notag` per row); `gather`/`gather*` centre each row instead. Inter-atom spacing uses TeX's 3/4/5mu classes (`1mu` is `1/18em`), `\mid` is a relation and `\colon` punctuation, and `\mskip`/`\mkern`/`\mspace`/`\hskip`/`\kern`/`\hspace` scan TeX dimensions, taking the natural width of any `plus`/`minus` parts. `\footnote{...}` leaves a numbered marker in the paragraph and sets the note as a 9pt page insertion at the bottom of the page that mentions it. A `thebibliography` environment turns its `\bibitem` entries into numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`; optional citation notes are dropped, `\citep`/`\citet` behave like `\cite`, `\nocite` is ignored, and `\bibliography`/`\bibliographystyle` are consumed without BibTeX). A `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and feeds `\ref`, and `\includegraphics` embeds the referenced project image when it decodes (PNG/JPEG/BMP become a PDF XObject; missing or undecodable files keep the rule placeholder), a standalone `\includegraphics` paragraph becomes an in-text graphic float, and a standalone `\rule{width}{height}` becomes an in-text rule box; `width=`/`height=` take dimensions or fractions of `\textwidth`/`\textheight`, `scale=` a percentage, `keepaspectratio` fits both dimensions, and `\graphicspath` directories are searched (with `.png`/`.jpg`/`.bmp` fallbacks) when a path has no suffix. `table` environments likewise become floats carrying their captured `tabular` body, with `Table n:` captions that resolve from `\ref`. Table captions sit above the tabular as in LaTeX, figure captions below the graphic, and `\caption*` leaves either unnumbered; an optional `[short]` caption is used by `\listoffigures`/`\listoftables` while the long caption stays on the float; the glue on each side of a tabular column follows `\tabcolsep` (6pt by default), `\arraystretch` scales the tabular row heights, a begin-position option is accepted and ignored, and `\\[dim]` adds an extra gap after that row, and `|` rules in the column template paint vertical rules, and `*{n}{cols}` repeats a column group, and `\renewcommand` can rename the `Figure`/`Table` caption prefixes, the `Abstract` heading, and the `References`/`Contents`/`List of Figures`/`List of Tables` headings that open the bibliography, table of contents and float lists. Theorem-like environments (`theorem`, `lemma`, `corollary`, `proposition`, `definition`, `example`, `remark`, `proof`) produce a bold numbered heading with an optional `[title]`, italic statements for the theorem group, and unnumbered proofs whose optional argument replaces the heading, with `\label`/`\ref` resolving to the theorem number. `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` add custom theorem environments: a shared counter numbers the env with its parent, `[section]` scopes numbers to the enclosing section, and the starred form stays unnumbered. In project previews and PDF exports, `\input{...}` and `\include{...}` expand from files in the same project (a missing `.tex` suffix is added), so chapter files render in place; a project's own `.sty`/`.cls` files are inlined for `\usepackage{name}`/`\documentclass{name}` with local `\RequirePackage` dependencies inlined recursively, local base classes named by `\LoadClass`/`\LoadClassWithOptions` inlined the same way, class and package bodies inlining their local `\input{...}` files (missing files are dropped), and package/class boilerplate dropped, `\AtBeginDocument`/`\AtEndDocument` bodies executed, and `\makeatletter`/`\makeatother` stripped; local class and package files run their `\DeclareOption` code for the options named on `\documentclass[...]` / `\usepackage[...]` (with `\ExecuteOptions` defaults), and preamble `\PassOptionsToPackage`/`\PassOptionsToClass` lines are merged into the next request, and unknown paths stay as literal text. Preview JSON also reports a `warnings` array naming environments route-D cannot lay out and control words that survived layout, so unsupported source is reported rather than silently typeset. Route-D project previews are memoised by a hash of the expanded source (32 entries) and invalidated on edit; PDF exports cache the last eight results and the cache key also covers decoded image bytes, so replacing an image re-renders both. A malformed source answers 422 with a JSON error body and never populates either cache. `itemize`/`enumerate`/`description` environments nest arbitrarily: bullet labels cycle `•`/`–`/`*`, sub-enumerations use `(a)`, roman and upper-letter labels, description items print their `[term]` in bold before the definition, an optional `\item[label]` replaces the generated marker, each depth adds 12pt of indentation, and list items take article's per-level `\topsep`, `\itemsep` and `\partopsep` (top level 8+2/4pt at 10pt, 9+3/4.5pt at 11pt and 10+3/5pt at 12pt; second level 4+2/2pt, 4.5+3/2pt and 5+3/2pt) unless `\setlength{\topsep}`, `\setlength{\itemsep}` or `\setlength{\partopsep}` override them, a wrapped item hangs its continuation lines at the text indent while its first line stays at the bullet indent, and an `\setcounter{enumi}` (or `enumii`/`enumiii`/`enumiv`) line before the first `\item` resumes enumerate numbering. A `quotation` environment splits its blank-line-separated paragraphs into blocks indented 20pt on both sides, and `quote` uses the same 20pt margins, and `verse` keeps its explicit line breaks as separate 20pt-indented lines, and a `minipage{w}` environment lays its body out at width `w` (its optional position argument is ignored). Inline `$...$` and `\(...\)` math is laid out inside 10pt paragraphs (larger sizes keep the delimiters literal). `\newcommand`/`\renewcommand` definitions are captured from the preamble and expanded textually, including numbered arguments and one `[default]` optional first argument; TeX's `\def` parameter texts and `\let` aliases are executed the same way, and `\newenvironment` definitions wrap their bodies with the declared begin/end material. `\newif` flags select between `\if...\else...\fi` branches, with assignments honoured in the preamble or the body, so class conditionals like `\ifdraft` work. diff --git a/crates/texrra-tex-core/src/math.rs b/crates/texrra-tex-core/src/math.rs index d815543..ba2f890 100755 --- a/crates/texrra-tex-core/src/math.rs +++ b/crates/texrra-tex-core/src/math.rs @@ -18,6 +18,14 @@ pub enum MathAlphabet { Fraktur, } +/// Horizontal alignment of a matrix/array column. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum MathColumnAlign { + Left, + Center, + Right, +} + #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum MathAtom { Symbol(char), @@ -88,9 +96,12 @@ pub enum MathAtom { }, /// A `\middle` delimiter; TeX sizes it with the enclosing `\left`/`\right`. Middle(char), - /// A `cases` environment: each row holds the cells split on `&`. - Cases { + /// A matrix-like environment: rows of cells with per-column alignment. + Matrix { rows: Vec>, + align: Vec, + left: Option, + right: Option, }, /// Rows of an `align` (column-aligned) or `gather` (centred) display. Aligned { @@ -540,21 +551,30 @@ pub fn italic_correction(atom: &MathAtom, font: &Cmr10Metrics) -> i64 { } } -/// Geometry shared by the layout and painter of a `cases` environment. -pub(crate) struct CasesLayout { +/// Geometry shared by the layout and painter of a matrix-like environment. +pub(crate) struct MatrixLayout { pub boxes: Vec>, pub column_widths: Vec, pub column_starts: Vec, pub baselines: Vec, pub first_height: i64, - pub brace: (i64, i64, i64), + pub left: Option<(char, i64, i64, i64)>, + pub right: Option<(char, i64, i64, i64)>, + pub body_width: i64, + pub border: i64, pub width: i64, pub height: i64, pub depth: i64, } -/// Lay out the rows of a `cases` environment and the brace beside them. -pub(crate) fn cases_layout(rows: &[Vec], font: &Cmr10Metrics) -> CasesLayout { +/// Lay out the rows of a matrix/array and the delimiters around them. +pub(crate) fn matrix_layout( + rows: &[Vec], + font: &Cmr10Metrics, + _align: &[MathColumnAlign], + left: Option, + right: Option, +) -> MatrixLayout { let boxes: Vec> = rows .iter() .map(|row| row.iter().map(|cell| layout_math(cell, font)).collect()) @@ -592,17 +612,42 @@ pub(crate) fn cases_layout(rows: &[Vec], font: &Cmr10Metrics) -> Cases let last_depth = row_depths.last().copied().unwrap_or(0); let extent = first_height + last_baseline + last_depth; let axis = 2 * 65_536 + 32_768; - let brace = select_delimiter(*font, '{', extent); - CasesLayout { + let left_metrics = left.map(|delimiter| { + let (width, height, depth) = select_delimiter(*font, delimiter, extent); + (delimiter, width, height, depth) + }); + let right_metrics = right.map(|delimiter| { + let (width, height, depth) = select_delimiter(*font, delimiter, extent); + (delimiter, width, height, depth) + }); + let border = if left_metrics.is_some() || right_metrics.is_some() { + 32_768 + } else { + 0 + }; + let left_width = left_metrics.map(|(_, width, _, _)| width).unwrap_or(0); + let right_width = right_metrics.map(|(_, width, _, _)| width).unwrap_or(0); + let mut height = extent / 2 + axis; + let mut depth = (extent / 2 - axis).max(0); + for (_, _, delimiter_height, delimiter_depth) in + [left_metrics, right_metrics].into_iter().flatten() + { + height = height.max(delimiter_height); + depth = depth.max(delimiter_depth); + } + MatrixLayout { boxes, column_widths, column_starts, baselines, first_height, - brace, - width: brace.0 + 3 * 65_536 + body_width, - height: (extent / 2 + axis).max(brace.1), - depth: (extent / 2 - axis).max(0).max(brace.2), + left: left_metrics, + right: right_metrics, + body_width, + border, + width: left_width + border + body_width + border + right_width, + height, + depth, } } @@ -711,27 +756,64 @@ fn math_environment(chars: &[char], index: usize) -> Option<(MathAtom, usize)> { return None; } cursor += 1; - let (inner, end) = read_environment(chars, cursor, &name)?; - match name.as_str() { - "cases" => { - let rows = split_environment_rows(&inner) - .into_iter() - .map(|row| { - row.into_iter() - .map(|cell| { - if cell.is_empty() { - MathAtom::Row(Vec::new()) - } else { - parse_math(&cell) - } - }) - .collect() - }) - .collect(); - Some((MathAtom::Cases { rows }, end)) + let mut align = Vec::new(); + if name == "array" && chars.get(cursor) == Some(&'{') { + cursor += 1; + while let Some(&character) = chars.get(cursor) { + if character == '}' { + cursor += 1; + break; + } + match character { + 'l' => align.push(MathColumnAlign::Left), + 'c' => align.push(MathColumnAlign::Center), + 'r' => align.push(MathColumnAlign::Right), + _ => {} + } + cursor += 1; } - _ => None, } + let (inner, end) = read_environment(chars, cursor, &name)?; + let rows: Vec> = split_environment_rows(&inner) + .into_iter() + .map(|row| { + row.into_iter() + .map(|cell| { + if cell.is_empty() { + MathAtom::Row(Vec::new()) + } else { + parse_math(&cell) + } + }) + .collect() + }) + .collect(); + let (left, right, default_align) = match name.as_str() { + "cases" => (Some('{'), None, MathColumnAlign::Left), + "matrix" => (None, None, MathColumnAlign::Center), + "pmatrix" => (Some('('), Some(')'), MathColumnAlign::Center), + "bmatrix" => (Some('['), Some(']'), MathColumnAlign::Center), + "Bmatrix" => (Some('{'), Some('}'), MathColumnAlign::Center), + "vmatrix" => (Some('|'), Some('|'), MathColumnAlign::Center), + "Vmatrix" => (Some('\u{2016}'), Some('\u{2016}'), MathColumnAlign::Center), + "array" => (None, None, MathColumnAlign::Center), + _ => return None, + }; + let columns = rows.iter().map(|row| row.len()).max().unwrap_or(0); + let align = if align.is_empty() { + vec![default_align; columns] + } else { + align + }; + Some(( + MathAtom::Matrix { + rows, + align, + left, + right, + }, + end, + )) } pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox { @@ -825,8 +907,13 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox { depth: body_box.depth.max(left_box.2).max(right_box.2), } } - MathAtom::Cases { rows } => { - let layout = cases_layout(rows, font); + MathAtom::Matrix { + rows, + align, + left, + right, + } => { + let layout = matrix_layout(rows, font, align, *left, *right); MathBox { width: layout.width, height: layout.height, @@ -2489,21 +2576,100 @@ mod tests { let atom = match atom { MathAtom::Row(atoms) => atoms .into_iter() - .find(|atom| matches!(atom, MathAtom::Cases { .. })) + .find(|atom| matches!(atom, MathAtom::Matrix { .. })) .expect("cases atom in the row"), other => other, }; - let MathAtom::Cases { rows } = atom else { - panic!("expected a cases atom"); + let MathAtom::Matrix { + rows, + align, + left, + right, + } = atom + else { + panic!("expected a cases matrix"); }; assert_eq!(rows.len(), 2); assert_eq!(rows[0].len(), 2); assert_eq!(rows[1].len(), 2); - let box_ = layout_math(&MathAtom::Cases { rows }, &Cmr10Metrics::default()); + assert_eq!(left, Some('{')); + assert_eq!(right, None); + assert_eq!(align[0], MathColumnAlign::Left); + let box_ = layout_math( + &MathAtom::Matrix { + rows, + align, + left: Some('{'), + right: None, + }, + &Cmr10Metrics::default(), + ); assert!(box_.width > 3 * 65_536); assert!(box_.height > 0); } + #[test] + fn matrix_environments_wrap_their_grid() { + let atom = parse_math("\\begin{pmatrix} a & b \\\\ c & d \\end{pmatrix}"); + let atom = match atom { + MathAtom::Row(atoms) => atoms + .into_iter() + .find(|atom| matches!(atom, MathAtom::Matrix { .. })) + .expect("matrix atom in the row"), + other => other, + }; + let MathAtom::Matrix { + rows, + align, + left, + right, + } = atom + else { + panic!("expected a matrix atom"); + }; + assert_eq!(rows.len(), 2); + assert_eq!(rows[0].len(), 2); + assert_eq!(left, Some('(')); + assert_eq!(right, Some(')')); + assert_eq!(align[0], MathColumnAlign::Center); + let box_ = layout_math( + &MathAtom::Matrix { + rows, + align, + left: Some('('), + right: Some(')'), + }, + &Cmr10Metrics::default(), + ); + assert!(box_.width > 0); + assert!(box_.height > 0); + } + + #[test] + fn array_environments_use_their_column_spec() { + let atom = parse_math("\\begin{array}{lr} a & b \\\\ c & d \\end{array}"); + let atom = match atom { + MathAtom::Row(atoms) => atoms + .into_iter() + .find(|atom| matches!(atom, MathAtom::Matrix { .. })) + .expect("array atom in the row"), + other => other, + }; + let MathAtom::Matrix { + rows, + align, + left, + right, + } = atom + else { + panic!("expected an array matrix"); + }; + assert_eq!(rows.len(), 2); + assert_eq!(left, None); + assert_eq!(right, None); + assert_eq!(align, vec![MathColumnAlign::Left, MathColumnAlign::Right]); + } + #[test] fn big_delimiters_allow_math_spaces() { let font = Cmr10Metrics::default(); diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 4ef0d5e..0df55ef 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -6,7 +6,7 @@ //! wired up. use crate::cmr10::Cmr10Metrics; -use crate::math::{self, MathAtom}; +use crate::math::{self, MathAtom, MathColumnAlign}; use crate::paragraph::ParagraphFont; use crate::{CellAlignment, Float, FloatPlacement, Halign, HorizontalItem, Page, VerticalItem}; @@ -1026,32 +1026,70 @@ impl Page { }); } } - MathAtom::Cases { rows } => { - let layout = math::cases_layout(rows, font); - let base_extent = font.height('{') + font.depth('{'); - let scale = if base_extent > 0 { - (layout.brace.1 + layout.brace.2) as f64 / base_extent as f64 - } else { - 1.0 + MathAtom::Matrix { + rows, + align, + left, + right, + } => { + let layout = math::matrix_layout(rows, font, align, *left, *right); + let base_extent = |delimiter: char| font.height(delimiter) + font.depth(delimiter); + let scaled = |metrics: (char, i64, i64, i64)| -> (i64, i64) { + let base = base_extent(metrics.0); + let scale = if base > 0 { + (metrics.2 + metrics.3) as f64 / base as f64 + } else { + 1.0 + }; + let glyph_size = (size as f64 * scale) as i64; + let shift = ((glyph_size - size) as f64 * 0.35) as i64; + (glyph_size, shift) }; - let glyph_size = (size as f64 * scale) as i64; - let shift = ((glyph_size - size) as f64 * 0.35) as i64; - list.push(DisplayItem::Text { - font: FontFace::Roman, - x, - y: baseline + shift, - size: glyph_size, - text: "{".to_string(), - }); - let start_x = x + layout.brace.0 + 3 * 65_536; + let left_width = layout.left.map(|(_, width, _, _)| width).unwrap_or(0); + if let Some(metrics) = layout.left { + let (glyph_size, shift) = scaled(metrics); + list.push(DisplayItem::Text { + font: FontFace::Roman, + x, + y: baseline + shift, + size: glyph_size, + text: metrics.0.to_string(), + }); + } + let body_x = x + left_width + layout.border; let first_baseline = baseline - layout.height + layout.first_height; for (row_index, cells) in rows.iter().enumerate() { let row_baseline = first_baseline + layout.baselines[row_index]; for (column, cell) in cells.iter().enumerate() { - let cell_x = start_x + layout.column_starts[column]; + let offset = match align + .get(column) + .copied() + .unwrap_or(MathColumnAlign::Center) + { + MathColumnAlign::Left => 0, + MathColumnAlign::Center => { + (layout.column_widths[column] + - layout.boxes[row_index][column].width) + / 2 + } + MathColumnAlign::Right => { + layout.column_widths[column] - layout.boxes[row_index][column].width + } + }; + let cell_x = body_x + layout.column_starts[column] + offset; Self::paint_math(cell, font, cell_x, row_baseline, size, list); } } + if let Some(metrics) = layout.right { + let (glyph_size, shift) = scaled(metrics); + list.push(DisplayItem::Text { + font: FontFace::Roman, + x: body_x + layout.body_width + layout.border, + y: baseline + shift, + size: glyph_size, + text: metrics.0.to_string(), + }); + } } MathAtom::Accent { accent, base } => { let base_box = math::layout_math(base, font); diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 36125b2..0b57c33 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`, `\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and -PDF opt-in with `?engine=route-d`). 806 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 809 workspace tests are green and no oracle fixture is ignored. Preview JSON also carries a `warnings` array naming environments route-D cannot lay out and control words that survived layout, so unsupported source is reported instead of being silently typeset. diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 251ccea..fbf7360 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -367,7 +367,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph. -The crate currently has 415 unit tests plus ten route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 806 tests (415 route-D unit, 210 engine binary unit, 10 route-D integration, 35 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. +The crate currently has 417 unit tests plus ten route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 809 tests (417 route-D unit, 211 engine binary unit, 10 route-D integration, 35 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. ### M0 incremental demo @@ -415,12 +415,12 @@ Residual approximations, documented rather than special-cased: The `M3`-`M7` stage of the roadmap is implemented to the extent recorded below. The goal ran for 90 rounds and landed 123 commits (`8c42f2d..c9a074b`); the -workspace suite is at 806 tests. +workspace suite is at 809 tests. | Milestone | Evidence | | --- | --- | | M3 `\halign` | shared column widths, `l`/`c`/`r`/`p{width}` with wrapped cells, `\tabskip`, `@{}`/`@{\hspace{...}}`, booktabs rule weights and partial spans, `\cline`, `\noalign{\vskip}`, `\multicolumn`, longtable heads/feet, `*{n}{cols}`, vertical `|` rules, optional position/bracket arguments, row `\\[dim]` gaps, LaTeX `tabular`/`longtable` capture, and page splitting that keeps column geometry. | -| M4 math | `cases` environments laid out as stacked rows with a sized left brace; Computer Modern math metrics (cmmi/cmsy/cmex/msbm/eufm) embedded as Type1 outlines, TeX's 3/4/5mu class table, `\mid`/`\colon`, `\mskip`-family dimension scans, `\frac` and infix fraction forms, `\left`/`\right`/`\middle` and `\big` CMEX sizing, `align`/`gather` row layout with per-row tags, equation numbering with `\eqref`/`\ref`/`\tag`/`\notag`, `cases` with `&`-separated cells, math alphabets (`\mathbf`/`\mathit`/`\mathsf`/`\mathtt`/`\mathcal`/`\mathbb`/`\mathfrak`) and wide-display line splitting. | +| M4 math | `cases`, `matrix`/`pmatrix`/`bmatrix`/`Bmatrix`/`vmatrix`/`Vmatrix` and `array` environments laid out as two-dimensional grids with sized delimiters; Computer Modern math metrics (cmmi/cmsy/cmex/msbm/eufm) embedded as Type1 outlines, TeX's 3/4/5mu class table, `\mid`/`\colon`, `\mskip`-family dimension scans, `\frac` and infix fraction forms, `\left`/`\right`/`\middle` and `\big` CMEX sizing, `align`/`gather` row layout with per-row tags, equation numbering with `\eqref`/`\ref`/`\tag`/`\notag`, `cases` with `&`-separated cells, matrix delimiters and `array` column specs, math alphabets (`\mathbf`/`\mathit`/`\mathsf`/`\mathtt`/`\mathcal`/`\mathbb`/`\mathfrak`) and wide-display line splitting. | | M5 fonts | twelve Computer Modern text programs (roman/bold/italic/bold-italic/mono/sans/sans-bold/sans-italic/small-caps/slanted/bold-slanted/mono-italic) plus four math programs, all embedded as Type1 with TFM widths; NFSS declarations, legacy switches, paragraph/inline runs with relative composition, per-run base sizes, superscripts/subscripts, accent composition, case commands, per-glyph Liberation fallback and Type1 ToUnicode CMaps. | | M6 class execution | article size options and `\linespread`, title/author/date and `\maketitle`, five-level sectioning with counters, TOC and float lists with page numbers and dot leaders, floats and in-text graphics with `\includegraphics` sizing/`\graphicspath`, footnote insertions, `thebibliography`/`\cite`, theorem environments and `\newtheorem`, nested lists with article skips and hanging indents, `quotation`/`quote`/`verse`, `minipage`, `\today`, page numbering, label/counter renaming, and preamble macro execution (`\newcommand`/`\def`/`\let`/`\newenvironment`/`\newif`/`\newlength`/`\newcounter`). Project `.cls`/`.sty` files are inlined with `\DeclareOption`/`\ProcessOptions`/`\ExecuteOptions`, `\LoadClass` inheritance, recursive `\RequirePackage`, local `\input`, `\AtBeginDocument` hooks and `\PassOptionsToClass`/`\PassOptionsToPackage`. | | M7 service | route-D preview/PDF/edit endpoints and the `?engine=route-d` project switch, `TEXRRA_ENGINE` default, memoised project previews/PDFs (source and image bytes in the key), flat endpoint caches with FIFO eviction and concurrency coverage, JSON 422 errors, PDF `/Link` annotations from `\href`, per-glyph Unicode extraction, and a `warnings` array in preview JSON that reports unsupported environments and control words that survived layout instead of failing silently. | diff --git a/src/route_d.rs b/src/route_d.rs index 00232b5..9c4c792 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -6424,6 +6424,13 @@ const SUPPORTED_ENVIRONMENTS: &[&str] = &[ "align", "gather", "cases", + "matrix", + "pmatrix", + "bmatrix", + "Bmatrix", + "vmatrix", + "Vmatrix", + "array", "thebibliography", "theorem", "lemma", @@ -7191,6 +7198,16 @@ mod source_tests { assert_eq!(geometry_counter(&geometry, "steps"), 4); } + #[test] + fn matrix_environments_paint_their_delimiters() { + let json = preview_json("\\[\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}\\]") + .expect("matrix preview"); + assert!(json.contains(">["), "{json}"); + assert!(json.contains(">]"), "{json}"); + assert!(json.contains(">a"), "{json}"); + assert!(!json.contains("unsupported environment"), "{json}"); + } + #[test] fn cases_environments_paint_rows_and_a_brace() { let json = preview_json("\\[\\begin{cases} x & x>0 \\\\ 0 & \\text{else} \\end{cases}\\]")