Expand the macro after an expandafter prefix once
This commit is contained in:
1 parent
863f3e1b80
commit
fa93b198bf
4 files changed
+90
-37
No files matched your search
@@ -471,7 +471,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. 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. A `\textcolor{name}{...}` run paints in one of the standard named colours in both the SVG preview and the PDF. 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'Line 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, `\edef`/`\xdef` expand their bodies once at definition time and `\csname...\endcsname` builds the named control sequence, 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.
|
||||
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, `\edef`/`\xdef` expand their bodies once at definition time and `\csname...\endcsname` builds the named control sequence, `\expandafter` runs the macro after its prefix once, 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.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -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`). 837 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 839 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
@@ -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 glyph to a Liberation subset when a character is outside the encoding while the rest of the face stays in Computer Modern |
|
||||
| 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, one `[default]` optional first argument and an eight-pass recursion guard; `\edef`/`\xdef` expand their bodies at definition time and `\csname...\endcsname` resolves to the named control sequence), and expands `geometry`, `\setlength`, title/author/date, `\maketitle`, sectioning, theorem, float and bibliography markup; local `.cls`/`.sty` files are inlined, execute their `\DeclareOption` subset for the options given on `\documentclass`/`\usepackage`, and recurse through local `\LoadClass` bases, while full class layout execution 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, one `[default]` optional first argument and an eight-pass recursion guard; `\edef`/`\xdef` expand their bodies at definition time and `\csname...\endcsname` resolves to the named control sequence; `\expandafter` expands the zero-argument macro after its prefix once), and expands `geometry`, `\setlength`, title/author/date, `\maketitle`, sectioning, theorem, float and bibliography markup; local `.cls`/`.sty` files are inlined, execute their `\DeclareOption` subset for the options given on `\documentclass`/`\usepackage`, and recurse through local `\LoadClass` bases, while full class layout execution 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`; project route-D previews are memoised by a hash of the expanded source (32 entries) and invalidated automatically when the source changes; project route-D PDF exports are cached by the same expanded-source hash (eight entries) and report `X-Texrra-Cache: hit`/`miss`; the flat `POST /api/route-d/preview` and `/api/route-d/pdf` endpoints likewise memoise the last 32 previews and eight PDFs by source hash and report the same header; malformed sources answer 422 with a JSON `{"error": "..."}` body and never populate either cache, the flat caches keep the newest 32 previews and eight PDFs in FIFO order (eviction is covered by tests), and four concurrent identical flat previews (or three flat PDFs) share a single mutex-protected cache entry and return identical bodies; a deployment can default to route-D with `TEXRRA_ENGINE=route-d`, and an explicit `?engine=` overrides that default for both project previews and PDFs (v1 and route-d alike; covered by an engine-parameter matrix test); inline `$...$`/`\(...\)` math is laid out inside 10pt paragraphs, while larger paragraphs keep delimiters literal; `\href` labels paint PDF `/Link` URI annotations over their runs |
|
||||
|
||||
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; 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 427 unit tests plus ten route-D integration tests and thirty-eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 837 tests (427 route-D unit, 226 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 427 unit tests plus ten route-D integration tests and thirty-eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 839 tests (427 route-D unit, 228 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,7 +415,7 @@ 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 837 tests.
|
||||
workspace suite is at 839 tests.
|
||||
|
||||
| Milestone | Evidence |
|
||||
| --- | --- |
|
||||
|
||||
+85
-32
@@ -601,6 +601,41 @@ fn expand_links_line(line: &str) -> String {
|
||||
output
|
||||
}
|
||||
|
||||
fn expand_macro_at(text: &str, macros: &[MacroDefinition]) -> Option<(String, usize)> {
|
||||
let after_slash = text.strip_prefix('\\')?;
|
||||
let length = after_slash
|
||||
.find(|character: char| !character.is_ascii_alphabetic())
|
||||
.unwrap_or(after_slash.len());
|
||||
if length == 0 {
|
||||
return None;
|
||||
}
|
||||
let name = format!("\\{}", &after_slash[..length]);
|
||||
let definition = macros.iter().find(|macro_| macro_.name == name)?;
|
||||
let tail = &after_slash[length..];
|
||||
let mut args = Vec::new();
|
||||
let mut consumed = 0_usize;
|
||||
let mut supplied_default = false;
|
||||
if let Some(default) = &definition.default {
|
||||
let trimmed = tail.trim_start();
|
||||
let spaces = tail.len() - trimmed.len();
|
||||
if let Some(after_bracket) = trimmed.strip_prefix('[') {
|
||||
if let Some(close) = after_bracket.find(']') {
|
||||
args.push(after_bracket[..close].to_string());
|
||||
consumed = spaces + 1 + close + 1;
|
||||
supplied_default = true;
|
||||
}
|
||||
}
|
||||
if !supplied_default {
|
||||
args.push(default.clone());
|
||||
}
|
||||
}
|
||||
let required = definition.args.saturating_sub(args.len() as u8);
|
||||
let (rest_args, used) = macro_arguments(&tail[consumed..], required)?;
|
||||
args.extend(rest_args);
|
||||
let expanded = substitute_macro_args(&definition.body, &args);
|
||||
Some((expanded, 1 + length + consumed + used))
|
||||
}
|
||||
|
||||
fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
|
||||
if macros.is_empty() {
|
||||
return source.to_string();
|
||||
@@ -612,44 +647,50 @@ fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
|
||||
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 tail = &after_slash[length..];
|
||||
let mut args = Vec::new();
|
||||
let mut consumed = 0_usize;
|
||||
let mut supplied_default = false;
|
||||
if let Some(default) = &definition.default {
|
||||
let trimmed = tail.trim_start();
|
||||
let spaces = tail.len() - trimmed.len();
|
||||
if let Some(after_bracket) = trimmed.strip_prefix('[') {
|
||||
if let Some(close) = after_bracket.find(']') {
|
||||
args.push(after_bracket[..close].to_string());
|
||||
consumed = spaces + 1 + close + 1;
|
||||
supplied_default = true;
|
||||
if let Some(after) = rest.strip_prefix(r"\expandafter") {
|
||||
let boundary = after
|
||||
.chars()
|
||||
.next()
|
||||
.is_none_or(|character| !character.is_ascii_alphabetic());
|
||||
if boundary {
|
||||
let trimmed = after.trim_start();
|
||||
if let Some(command) = trimmed.strip_prefix('\\') {
|
||||
let length = command
|
||||
.find(|character: char| !character.is_ascii_alphabetic())
|
||||
.unwrap_or(command.len());
|
||||
if length > 0 {
|
||||
let kept = 1 + length;
|
||||
let name = format!("\\{}", &command[..length]);
|
||||
let definition = macros.iter().find(|macro_| macro_.name == name);
|
||||
if let Some(definition) = definition
|
||||
&& definition.args == 0
|
||||
&& definition.default.is_none()
|
||||
{
|
||||
let tail = &trimmed[kept..];
|
||||
let spaces = tail.len() - tail.trim_start().len();
|
||||
let argument = &tail[spaces..];
|
||||
if let Some((expanded, used)) = expand_macro_at(argument, macros) {
|
||||
output.push_str(&definition.body);
|
||||
output.push_str(&expanded);
|
||||
index += r"\expandafter".len()
|
||||
+ (after.len() - trimmed.len())
|
||||
+ kept
|
||||
+ spaces
|
||||
+ used;
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if !supplied_default {
|
||||
args.push(default.clone());
|
||||
}
|
||||
}
|
||||
let required = definition.args.saturating_sub(args.len() as u8);
|
||||
if let Some((rest_args, used)) =
|
||||
macro_arguments(&tail[consumed..], required)
|
||||
{
|
||||
args.extend(rest_args);
|
||||
output.push_str(&substitute_macro_args(&definition.body, &args));
|
||||
index += 1 + length + consumed + used;
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((expanded, used)) = expand_macro_at(rest, macros) {
|
||||
output.push_str(&expanded);
|
||||
index += used;
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
let character = rest.chars().next().expect("non-empty tail");
|
||||
output.push(character);
|
||||
index += character.len_utf8();
|
||||
@@ -8062,6 +8103,18 @@ a & b
|
||||
assert_eq!(body, "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expandafter_expands_the_following_token_first() {
|
||||
let (body, _) = geometry_and_body("\\def\\x{y}\n\\def\\y{Z}\n\n\\expandafter\\x\\y");
|
||||
assert_eq!(body, "yZ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expandafter_concatenates_zero_argument_expansions() {
|
||||
let (body, _) = geometry_and_body("\\def\\a{1}\n\\def\\b{2}\n\n\\expandafter\\a\\b");
|
||||
assert_eq!(body, "12");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_numbers_follow_the_page_counter() {
|
||||
let offset = preview_json("\\setcounter{page}{5}\n\nAlpha\n\n\\newpage\n\nBeta")
|
||||
|
||||
Reference in new issue
Block a user