diff --git a/README.md b/README.md index 4d15ed6..0972c06 100644 --- a/README.md +++ b/README.md @@ -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. 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. 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, `\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` (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, `verbatim` keeps monospaced source lines, `\verb|...|` renders inline literal text monospaced, `\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. `\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` embeds the referenced project image when it decodes (PNG/JPEG/BMP become a PDF XObject; missing files keep the rule placeholder), a standalone `\includegraphics` paragraph becomes an in-text graphic float; `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; the glue on each side of a tabular column follows `\tabcolsep` (6pt by default), `\arraystretch` scales the tabular row heights, 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, 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. 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 keep their `[term]` as `term — `, an optional `\item[label]` replaces the generated marker, and each depth adds 12pt of indentation. -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; 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. +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. 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. diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 89d0d1a..5e30c8d 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`). 742 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 744 workspace tests are green and no oracle fixture is ignored. Status after G1 (P0-P2): the paragraph model reproduces TeX's passes, diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 9569ed1..e9bc22c 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -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 and an eight-pass recursion guard), 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), 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; a deployment can default to route-D with `TEXRRA_ENGINE=route-d`, and an explicit `?engine=v1` still overrides it; 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. `Engine::edit` preserves the face when reflowing an edited paragraph. -The crate currently has 410 unit tests plus nine route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 742 tests (410 route-D unit, 159 engine binary unit, 9 route-D integration, 35 oracle, 71 v1 integration, 53 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. +The crate currently has 410 unit tests plus nine route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 744 tests (410 route-D unit, 161 engine binary unit, 9 route-D integration, 35 oracle, 71 v1 integration, 53 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. ### M0 incremental demo diff --git a/src/route_d.rs b/src/route_d.rs index 66ac107..215b096 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -234,6 +234,7 @@ struct TheoremDefinition { struct MacroDefinition { name: String, args: u8, + default: Option, body: String, } @@ -351,7 +352,12 @@ fn macro_definition(line: &str) -> Option { let open = rest.find('{')?; let args = definition_argument_count(&rest[..open])?; let (body, _) = take_group_after_open(&rest[open + 1..])?; - return Some(MacroDefinition { name, args, body }); + return Some(MacroDefinition { + name, + args, + default: None, + body, + }); } let rest = line .strip_prefix("\\newcommand") @@ -385,14 +391,22 @@ fn macro_definition(line: &str) -> Option { 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 mut rest = rest.trim_start(); + let mut default = None; + if let Some(after_bracket) = rest.strip_prefix('[') { + let close = after_bracket.find(']')?; + default = Some(after_bracket[..close].to_string()); + rest = &after_bracket[close + 1..]; } + let rest = rest.trim_start(); let body = rest.strip_prefix('{')?; let (body, _) = take_group_after_open(body)?; - Some(MacroDefinition { name, args, body }) + Some(MacroDefinition { + name, + args, + default, + body, + }) } /// Replace `#1`..`#9` in a macro body with its arguments. @@ -525,14 +539,35 @@ fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String { .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; + 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 !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; + } } } } @@ -1091,11 +1126,13 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) { .unwrap_or(MacroDefinition { name: name.clone(), args: 0, + default: None, body: String::new(), }); geometry.macros.push(MacroDefinition { name, args: definition.args, + default: definition.default, body: definition.body, }); continue; @@ -6096,17 +6133,34 @@ See \ref{fig:a} and \ref{tab:b}."; ); } + #[test] + fn optional_macro_arguments_use_defaults() { + let definition = + macro_definition("\\newcommand{\\vect}[2][x]{(#1,#2)}").expect("definition"); + assert_eq!(definition.default.as_deref(), Some("x")); + assert_eq!( + expand_macros("\\vect{y}", std::slice::from_ref(&definition)), + "(x,y)" + ); + assert_eq!( + expand_macros("\\vect[z]{w}", std::slice::from_ref(&definition)), + "(z,w)" + ); + } + #[test] fn macros_expand_nested_and_stop_on_recursion() { let definitions = vec![ MacroDefinition { name: "\\a".into(), args: 0, + default: None, body: "\\b".into(), }, MacroDefinition { name: "\\b".into(), args: 0, + default: None, body: "B".into(), }, ]; @@ -6114,12 +6168,24 @@ See \ref{fig:a} and \ref{tab:b}."; let recursive = vec![MacroDefinition { name: "\\loop".into(), args: 0, + default: None, body: "\\loop".into(), }]; assert_eq!(expand_macros("\\loop", &recursive), "\\loop"); assert_eq!(expand_macros("\\missing", &definitions), "\\missing"); } + #[test] + fn newcommand_optional_arguments_expand() { + let source = "\\newcommand{\\half}[1][2]{1/#1}\n\nA \\half.\n\nB \\half[4]."; + let (body, geometry) = geometry_and_body(source); + assert_eq!(geometry.macros[0].default.as_deref(), Some("2")); + let paragraphs = + paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks"); + assert_eq!(paragraphs[0].text, "A 1/2."); + assert_eq!(paragraphs[1].text, "B 1/4."); + } + #[test] fn macros_expand_in_previews() { let json = preview_json("\\newcommand{\\name}{Ada}\n\nHello \\name.").expect("preview");