Set operator names upright and declare new ones

This commit is contained in:
gloamxun committed 2026-10-26 01:24:46 +08:00
1 parent a4c4864d2b
commit 7ba66392ea
6 files changed
+120 -32

No files matched your search

+1 -1
View File
@@ -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{<size>}{<baselineskip>}` 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. `\hypersetup{pdftitle=...}` writes the PDF Info dictionary (title, author, subject and keywords, UTF-16BE for non-ASCII text), each numbered heading becomes a PDF bookmark nested by heading level, `\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 `??`), and `\pageref{label}` reports that heading's formatted page number after a probe layout, `\appendix` restarts sectioning with letter numbers, `\tableofconLine truncated
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{<size>}{<baselineskip>}` 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. `\hypersetup{pdftitle=...}` writes the PDF Info dictionary (title, author, subject and keywords, UTF-16BE for non-ASCII text), each numbered heading becomes a PDF bookmark nested by heading level, `\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 `??`), and `\pageref{label}` reports that heading's formatted page number after a probe layout, `\appendix` restarts sectioning with letter numbers, `\tableofconLine truncated
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.
+61 -27
View File
@@ -120,6 +120,11 @@ pub enum MathAtom {
centered: bool,
},
StackLines(Vec<MathAtom>),
/// An `\operatorname` name, with optional default limits.
OperatorName {
name: String,
limits: bool,
},
Stack {
top: Box<MathAtom>,
base: Box<MathAtom>,
@@ -527,6 +532,7 @@ fn atom_class(atom: &MathAtom) -> MathClass {
MathAtom::Negated { base } => atom_class(base),
MathAtom::Cancel { base, .. } => atom_class(base),
MathAtom::BigOperator { .. } => MathClass::Op,
MathAtom::OperatorName { .. } => MathClass::Op,
MathAtom::Limits { base, .. } => atom_class(base),
MathAtom::Fraction { .. } | MathAtom::Binomial { .. } | MathAtom::Delimited { .. } => {
MathClass::Inner
@@ -1183,6 +1189,26 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
depth: layout.depth,
}
}
MathAtom::OperatorName { name, .. } => {
let roman = Cmr10Metrics::Roman;
let mut width = 0;
let mut height = 0;
let mut depth = 0;
for character in name.chars() {
if character == ' ' {
width += roman.space();
continue;
}
width += roman.width(character);
height = height.max(roman.height(character));
depth = depth.max(roman.depth(character));
}
MathBox {
width: width.max(1),
height: height.max(8 * 65_536),
depth,
}
}
MathAtom::Stack { top, base, above } => {
let top = layout_math(top, font);
let base = layout_math(base, font);
@@ -1436,6 +1462,7 @@ fn limits_override(chars: &[char], index: usize) -> Option<(bool, usize)> {
fn operator_default_limits(base: &MathAtom) -> bool {
match base {
MathAtom::BigOperator { name } => name != "int",
MathAtom::OperatorName { limits, .. } => *limits,
_ => true,
}
}
@@ -2146,6 +2173,28 @@ fn parse_atom(chars: &[char], index: usize) -> (MathAtom, usize) {
after,
)
}
"operatorname" => {
let mut after = next;
while chars.get(after) == Some(&'\u{0}')
|| chars.get(after).is_some_and(|c| c.is_whitespace())
{
after += 1;
}
let (limits, after) = if chars.get(after) == Some(&'*') {
(true, after + 1)
} else {
(false, after)
};
if let Some((name, after)) = read_braced_text(chars, after) {
let base = MathAtom::OperatorName {
name: name.trim().to_string(),
limits,
};
parse_limits(chars, after, base)
} else {
(MathAtom::Symbol('?'), after)
}
}
"sum" | "prod" | "int" => {
let base = MathAtom::BigOperator {
name: command.clone(),
@@ -2425,33 +2474,6 @@ fn parse_atom(chars: &[char], index: usize) -> (MathAtom, usize) {
after,
)
}
"operatorname" => {
let mut after = next;
let starred = chars.get(after) == Some(&'*');
if starred {
after += 1;
}
if chars.get(after) == Some(&'{') {
after += 1;
}
let start = after;
while after < chars.len() && chars[after] != '}' {
after += 1;
}
let text: String = chars[start..after]
.iter()
.map(|ch| if *ch == '\u{0}' { ' ' } else { *ch })
.collect();
if after < chars.len() {
after += 1;
}
let atom = MathAtom::Text(text);
if starred {
parse_limits(chars, after, atom)
} else {
(atom, after)
}
}
"text" | "mathrm" => {
let mut after = next;
if chars.get(after) == Some(&'{') {
@@ -3182,6 +3204,18 @@ mod tests {
let limited = layout_math(&parse_math(r"\mathop{argmax}_{x}"), &font);
assert!(limited.depth > plain.depth);
}
#[test]
fn operator_names_are_upright_and_stack_when_starred() {
let font = Cmr10Metrics::default();
let upright = layout_math(&parse_math("\\operatorname{Tr}"), &font);
let italic = layout_math(&parse_math("\\mathit{Tr}"), &font);
assert_ne!(upright.width, italic.width);
let stacked = layout_math(&parse_math("\\operatorname*{arg}_{x}"), &font);
let beside = layout_math(&parse_math("\\operatorname{arg}_{x}"), &font);
assert!(stacked.width < beside.width);
assert!(stacked.height + stacked.depth > beside.height + beside.depth);
}
#[test]
fn substack_rows_stack_downward() {
let atom = parse_math(r"\substack{a \\ b}");
+18
View File
@@ -794,6 +794,24 @@ impl Page {
});
}
}
MathAtom::OperatorName { name, .. } => {
let roman = crate::cmr10::Cmr10Metrics::Roman;
let mut cursor = x;
for character in name.chars() {
if character == ' ' {
cursor += roman.space();
continue;
}
list.push(DisplayItem::Text {
font: FontFace::Roman,
x: cursor,
y: baseline,
size,
text: character.to_string(),
});
cursor += roman.width(character);
}
}
MathAtom::Text(text) => {
let mut cursor = x;
for character in text.chars() {
+1 -1
View File
@@ -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`). 828 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 830 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.
+3 -3
View File
@@ -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 425 unit tests plus ten route-D integration tests and thirty-eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 828 tests (425 route-D unit, 219 engine binary unit, 10 route-D integration, 38 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 426 unit tests plus ten route-D integration tests and thirty-eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 830 tests (426 route-D unit, 220 engine binary unit, 10 route-D integration, 38 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 828 tests.
workspace suite is at 830 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`, `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`/`alignat` row layout with per-row tags, `split` blocks numbered once and `multline` edge alignment, equation numbering with `\eqref`/`\ref`/`\tag`/`\notag`, `cases` with `&`-separated cells, matrix delimiters and `array` column specs (matrix rows advance 12pt and cases 14.4pt, matching amsmath's `\arraystretch`, and pmatrix/cases word positions are checked against pdfLaTeX within 1pt), 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`/`alignat` row layout with per-row tags, `split` blocks numbered once and `multline` edge alignment, equation numbering with `\eqref`/`\ref`/`\tag`/`\notag`, `cases` with `&`-separated cells, matrix delimiters and `array` column specs (matrix rows advance 12pt and cases 14.4pt, matching amsmath's `\arraystretch`, and pmatrix/cases word positions are checked against pdfLaTeX within 1pt), math alphabets (`\mathbf`/`\mathit`/`\mathsf`/`\mathtt`/`\mathcal`/`\mathbb`/`\mathfrak`) wide-display line splitting, `\operatorname`/`\operatorname*` upright operator names with optional stacked limits, and `\DeclareMathOperator` definitions. |
| 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. |
+36
View File
@@ -1231,6 +1231,31 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
geometry.list_table_name = Some(name);
continue;
}
if let Some(rest) = trimmed.strip_prefix("\\DeclareMathOperator") {
let mut rest = rest.trim_start();
let mut starred = false;
if let Some(after) = rest.strip_prefix('*') {
starred = true;
rest = after.trim_start();
}
if let Some((command, tail)) = braced(rest) {
if let Some((body, _)) = braced(tail.trim_start()) {
let name = command.trim().trim_start_matches('\\').to_string();
let operator = if starred {
format!("\\operatorname*{{{}}}", body.trim())
} else {
format!("\\operatorname{{{}}}", body.trim())
};
geometry.macros.push(MacroDefinition {
name,
args: 0,
default: None,
body: operator,
});
}
}
continue;
}
if trimmed.starts_with("\\newcommand")
|| trimmed.starts_with("\\renewcommand")
|| trimmed.starts_with("\\providecommand")
@@ -7560,6 +7585,17 @@ mod source_tests {
}
#[test]
#[test]
fn operator_names_and_declared_operators_render() {
let source = r"\DeclareMathOperator{\Tr}{Tr}
Body $\operatorname{rank}(A)$ and $\Tr(B)$.";
let json = preview_json(source).expect("preview");
assert!(json.contains(">r</text>"));
assert!(!json.contains("operatorname"));
assert!(!json.contains("DeclareMathOperator"));
}
#[test]
fn substack_scripts_paint_their_rows() {
let json = preview_json("\\[\\sum_{\\substack{i=1 \\\\ j=2}} x\\]").expect("preview");