Execute newcommand macros from the preamble

This commit is contained in:
gloamxun committed 2026-10-24 22:07:04 +08:00
1 parent e008741aa5
commit a5da5c9521
4 files changed
+217 -4

No files matched your search

+1 -1
View File
@@ -469,7 +469,7 @@ the assignable TeX parameters `\\delimiterfactor` (default 901) and
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. 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); a size command inside a paragraph still overrides the class default. The paragraph measure follows `\textwidth`/`\hsize` (or `\setlength{\textwidth}{...}`), and `\setlength` accepts the other supported layout lengths, including a `\parskip` with plus/minus glue. 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. `\title`, `\author` and `\date` are captured from the preamble, and `\maketitle` expands into a centered title block at the article class sizes. `\section`, `\subsection` and `\subsubsection` advance article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize`; starred headings stay unnumbered and an optional `[short]` title is dropped. 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, 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. `\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 `[?]`). A `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and feeds `\ref`, and `\includegraphics[width=...]` reserves a rule placeholder. `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. 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, with `\label`/`\ref` resolving to tLine truncated
Inline `$...$` and `\(...\)` math is laid out inside 10pt paragraphs (larger sizes keep the delimiters literal).
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.
Route-D integration can also be checked against a real TeX page: `cargo test -p texrra-tex-core --test route_d` includes `route_d_page_matches_pdftex_raster_geometry`, which renders the route-D PDF and a pdfTeX Letter page at the same scaled-point geometry, rasterizes both with `pdftoppm`, and compares ink line count plus left, right, and bottom edges. It is skipped when `pdflatex`/`pdftoppm` are unavailable. `route_d_multiline_bands_track_pdftex` extends that check to a wrapped paragraph: the pixel rows that carry ink form one band per TeX line, and every band top, bottom, left edge and (except for the last line, whose width follows the break point) right edge must land within a couple of pixels of the pdfTeX page.
+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`). 644 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 648 workspace tests are green and no oracle
fixture is ignored.
Status after G1 (P0-P2): the paragraph model reproduces TeX's passes,
+2 -2
View File
@@ -332,7 +332,7 @@ for a later overlaid slash.
| M3 halign | partial | natural columns, spans, omit, hline rows, templates, noalign skip, rules; no PDF painter |
| M4 math | partial | atoms, scripts, fractions (including infix `\over`/`\atop`/`\choose`), roots, delimiters, accents, operators, classes, braces, boxed, negated, math alphabets (incl. `\mathcal`, `\mathbb` and `\mathfrak`), `align`/`gather` rows with per-row tags; no math painter/shrink wrapping |
| M5 NFSS/TFM | partial | runtime `cmr10.tfm` widths/heights/depths/kern pairs and ff/fi/fl/ffi/ffl ligatures; text faces embed Liberation Serif/Mono as Type0 CID fonts with Identity-H, ToUnicode and width arrays; used faces embed per-document TrueType glyf subsets that keep the original glyph IDs, include composite components, and carry a matching ToUnicode CMap; ASCII documents use the compact tier; no Base-14 dependency; SVG carries family/weight/style; route-D PDFs embed Knuth's Computer Modern Type1 programs (cmr10/cmbx10/cmti10/cmbxti10/cmtt10/cmss10/cmssbx10/cmssi10/cmcsc10/cmsl10/cmbxsl10/cmitt10) as `/Subtype /Type1` fonts with `/FontFile` (`Length1/2/3`), `/Encoding /Differences` and TFM `/Widths`, falling back per face to Liberation when the program does not encode every character |
| M6 specials/XObject | partial | raw specials, RGB image XObjects, URI link annotations; route-D reads `\documentclass` size options (10/11/12pt) into the paragraph base size and `\baselineskip`; executing class or package code remains absent |
| M6 specials/XObject | partial | raw specials, RGB image XObjects, URI link annotations; route-D reads `\documentclass` size options (10/11/12pt) into the paragraph base size and `\baselineskip`, executes `\newcommand`/`\renewcommand` macros textually (with numbered arguments and an eight-pass recursion guard), and expands `geometry`, `\setlength`, title/author/date, `\maketitle`, sectioning, theorem, float and bibliography markup; executing `.cls`/`.sty` files remains absent |
| M7 incremental integration | partial | route-D preview/PDF/edit endpoints plus opt-in `?engine=route-d` project preview, content-based page hashes and section/emphasis/display-math/inline-math/itemize/enumerate/description/quote/center/flushleft/flushright mapping; editor toggle in `texrra-web`; inline `$...$`/`\(...\)` math is laid out inside 10pt paragraphs, while larger paragraphs keep delimiters literal |
v1 remains the production renderer; the route-D core is additive and tested independently.
@@ -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. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 403 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 644 tests (403 route-D unit, 91 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 31 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
The crate currently has 403 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 648 tests (403 route-D unit, 95 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 31 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
### M0 incremental demo
+213
View File
@@ -166,6 +166,8 @@ struct PageGeometry {
bibliography: Vec<(String, String)>,
/// `\newtheorem` definitions from the preamble.
theorem_definitions: Vec<TheoremDefinition>,
/// `\newcommand` definitions from the preamble.
macros: Vec<MacroDefinition>,
}
/// A `\newtheorem` declaration: display name, shared counter and section scope.
@@ -180,6 +182,155 @@ struct TheoremDefinition {
/// Parse `\newtheorem{env}[shared]{Display}`,
/// `\newtheorem{env}{Display}[within]` and `\newtheorem*{env}{Display}`.
/// A user macro captured from `\newcommand`.
#[derive(Clone, Debug, PartialEq, Eq)]
struct MacroDefinition {
name: String,
args: u8,
body: String,
}
/// Consume a braced group; the returned count includes the closing brace.
fn take_group_after_open(text: &str) -> Option<(String, usize)> {
let mut depth = 0_i32;
for (offset, character) in text.char_indices() {
match character {
'{' => depth += 1,
'}' if depth == 0 => {
return Some((text[..offset].to_string(), offset + 1));
}
'}' => depth -= 1,
_ => {}
}
}
None
}
/// Parse `\newcommand{\name}[n]{body}` (and renew/provide variants).
fn macro_definition(line: &str) -> Option<MacroDefinition> {
let rest = line
.strip_prefix("\\newcommand")
.or_else(|| line.strip_prefix("\\renewcommand"))
.or_else(|| line.strip_prefix("\\providecommand"))?;
let rest = rest.trim_start();
let rest = rest.strip_prefix('*').unwrap_or(rest).trim_start();
let (name, rest) = if let Some(after_open) = rest.strip_prefix('{') {
let close = after_open.find('}')?;
(
after_open[..close].trim().to_string(),
&after_open[close + 1..],
)
} else {
let after_slash = rest.strip_prefix('\\')?;
let length = after_slash
.find(|character: char| !character.is_ascii_alphabetic())
.unwrap_or(after_slash.len());
(
format!("\\{}", &after_slash[..length]),
&after_slash[length..],
)
};
if name.is_empty() {
return None;
}
let mut rest = rest.trim_start();
let mut args = 0_u8;
if let Some(after_bracket) = rest.strip_prefix('[') {
let close = after_bracket.find(']')?;
args = after_bracket[..close].trim().parse().ok()?;
rest = &after_bracket[close + 1..];
}
let rest = rest.trim_start();
if rest.starts_with('[') {
// Optional arguments are not supported yet.
return None;
}
let body = rest.strip_prefix('{')?;
let (body, _) = take_group_after_open(body)?;
Some(MacroDefinition { name, args, body })
}
/// Replace `#1`..`#9` in a macro body with its arguments.
fn substitute_macro_args(body: &str, args: &[String]) -> String {
let mut output = String::with_capacity(body.len());
let mut characters = body.chars().peekable();
while let Some(character) = characters.next() {
if character == '#' {
if let Some(next) = characters.peek().copied() {
if let Some(index) = next.to_digit(10) {
if index >= 1 && (index as usize) <= args.len() {
output.push_str(&args[index as usize - 1]);
characters.next();
continue;
}
}
}
}
output.push(character);
}
output
}
/// Collect `count` braced arguments starting at `text`; the count is bytes
/// consumed including leading whitespace and braces.
fn macro_arguments(text: &str, count: u8) -> Option<(Vec<String>, usize)> {
let mut args = Vec::new();
let mut consumed = 0_usize;
let mut cursor = text;
for _ in 0..count {
let trimmed = cursor.trim_start();
consumed += cursor.len() - trimmed.len();
cursor = trimmed;
let after_open = cursor.strip_prefix('{')?;
let (argument, used) = take_group_after_open(after_open)?;
args.push(argument);
consumed += 1 + used;
cursor = &after_open[used..];
}
Some((args, consumed))
}
/// Expand user macros in a single pass, repeating until nothing changes.
fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
if macros.is_empty() {
return source.to_string();
}
let mut text = source.to_string();
for _ in 0..8 {
let mut output = String::with_capacity(text.len());
let mut index = 0;
let mut changed = false;
while index < text.len() {
let rest = &text[index..];
if let Some(after_slash) = rest.strip_prefix('\\') {
let length = after_slash
.find(|character: char| !character.is_ascii_alphabetic())
.unwrap_or(after_slash.len());
if length > 0 {
let name = format!("\\{}", &after_slash[..length]);
if let Some(definition) = macros.iter().find(|macro_| macro_.name == name)
&& let Some((args, consumed)) =
macro_arguments(&after_slash[length..], definition.args)
{
output.push_str(&substitute_macro_args(&definition.body, &args));
index += 1 + length + consumed;
changed = true;
continue;
}
}
}
let character = rest.chars().next().expect("non-empty tail");
output.push(character);
index += character.len_utf8();
}
text = output;
if !changed {
break;
}
}
text
}
fn newtheorem_definition(line: &str) -> Option<TheoremDefinition> {
let rest = line.strip_prefix("\\newtheorem")?;
let (starred, rest) = match rest.strip_prefix('*') {
@@ -349,6 +500,15 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
}
continue;
}
if trimmed.starts_with("\\newcommand")
|| trimmed.starts_with("\\renewcommand")
|| trimmed.starts_with("\\providecommand")
{
if let Some(definition) = macro_definition(trimmed) {
geometry.macros.push(definition);
}
continue;
}
if trimmed.starts_with("\\newtheorem") {
if let Some(definition) = newtheorem_definition(trimmed) {
geometry.theorem_definitions.push(definition);
@@ -575,6 +735,7 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
// paragraphs of their own.
let mut body = latex_body(&stripped).trim_matches('\n').to_string();
geometry.bibliography = extract_bibliography(&mut body);
body = expand_macros(&body, &geometry.macros);
(body, geometry)
}
@@ -3982,6 +4143,58 @@ See \ref{fig:a} and \ref{tab:b}.";
assert_eq!(blocks[0].left_skip, 12);
}
#[test]
fn newcommand_definitions_expand_in_the_body() {
let source = "\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\pair}[2]{(#1,#2)}\n\n$\\R$ and $\\pair{x}{y}$";
let (body, geometry) = geometry_and_body(source);
assert_eq!(geometry.macros.len(), 2);
assert!(!body.contains("\\newcommand"));
assert!(body.contains("\\mathbb{R}"));
assert!(body.contains("(x,y)"));
}
#[test]
fn macro_arguments_substitute_in_order() {
let definition =
macro_definition("\\newcommand{\\vect}[2]{\\mathbf{#2}^{#1}}").expect("definition");
assert_eq!(definition.args, 2);
assert_eq!(
expand_macros("\\vect{2}{x}", std::slice::from_ref(&definition)),
"\\mathbf{x}^{2}"
);
}
#[test]
fn macros_expand_nested_and_stop_on_recursion() {
let definitions = vec![
MacroDefinition {
name: "\\a".into(),
args: 0,
body: "\\b".into(),
},
MacroDefinition {
name: "\\b".into(),
args: 0,
body: "B".into(),
},
];
assert_eq!(expand_macros("\\a", &definitions), "B");
let recursive = vec![MacroDefinition {
name: "\\loop".into(),
args: 0,
body: "\\loop".into(),
}];
assert_eq!(expand_macros("\\loop", &recursive), "\\loop");
assert_eq!(expand_macros("\\missing", &definitions), "\\missing");
}
#[test]
fn macros_expand_in_previews() {
let json = preview_json("\\newcommand{\\name}{Ada}\n\nHello \\name.").expect("preview");
assert!(json.contains(">A</text>"));
assert!(json.contains(">d</text>"));
}
#[test]
fn newtheorem_definitions_are_captured() {
let source = "\\newtheorem{claim}[theorem]{Claim}\n\\newtheorem*{note}{Note}\n\\newtheorem{observation}{Observation}[section]\n\nBody.";