diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 45faf85..c4c4df3 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`). 989 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 990 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 5c93477..297ca7a 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -370,7 +370,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 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 989 tests (437 route-D unit, 364 engine binary unit, 10 route-D integration, 42 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 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 990 tests (437 route-D unit, 365 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. ### M0 incremental demo @@ -532,8 +532,11 @@ honest open items against the "feature-complete LaTeX compiler" objective are: expansion keeps a scope stack for `{}` and `\begingroup`/`\endgroup`: a `\def` inside a group is local to it, while a top-level `\def` or any `\gdef` updates the document table; grouping braces are removed after - command parsing. There is still no catcode state and no token stream, so - class code that relies on those semantics degrades. + command parsing. Runtime `\let\alias=\target` and `\chardef\name=` + also define (or locally shadow) commands, and the line-based capture only + runs before `\begin{document}` and outside braces, so a definition on its own + line inside a group stays local. There is still no catcode state and no token + stream, so class code that relies on those semantics degrades. - **Boxes**: `\sbox`/`\savebox` content and `\mbox`/`\hbox`/`\makebox` bodies are inserted as one unbreakable inline box (interword spaces become fixed-width boxes), so `\usebox` no longer reflows across lines. Savebox diff --git a/src/route_d.rs b/src/route_d.rs index 3da95b1..315cb6c 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -768,6 +768,87 @@ fn upsert_macro(table: &mut Vec, definition: MacroDefinition) { } } +fn brace_depth_delta(line: &str) -> i32 { + let mut depth = 0_i32; + let mut escaped = false; + for character in line.chars() { + if escaped { + escaped = false; + continue; + } + match character { + '\\' => escaped = true, + '{' => depth += 1, + '}' => depth -= 1, + _ => {} + } + } + depth +} + +/// Runtime `\let\alias=\target` and `\chardef\name=` definitions. +fn runtime_plain_definition(text: &str) -> Option<(MacroDefinition, usize)> { + let (command, used) = control_sequence(text)?; + let rest = &text[used..]; + let trimmed = rest.trim_start(); + let skipped = rest.len() - trimmed.len(); + let (name, name_used) = control_sequence(trimmed)?; + let after_name = trimmed[name_used..].trim_start(); + let name_gap = trimmed[name_used..].len() - after_name.len(); + match command.as_str() { + "\\let" => { + let after = after_name + .strip_prefix('=') + .map(str::trim_start) + .unwrap_or(after_name); + let eq_skipped = after_name.len() - after.len(); + let (target, target_used) = if let Some((target, target_used)) = control_sequence(after) + { + (target, target_used) + } else { + let character = after.chars().next()?; + (character.to_string(), character.len_utf8()) + }; + Some(( + MacroDefinition { + name: format!("\\{}", name.trim_start_matches('\\')), + args: 0, + default: None, + params: None, + body: target, + }, + used + skipped + name_used + name_gap + eq_skipped + target_used, + )) + } + "\\chardef" => { + let after = after_name + .strip_prefix('=') + .map(str::trim_start) + .unwrap_or(after_name); + let eq_skipped = after_name.len() - after.len(); + let digits: String = after + .chars() + .take_while(|character| character.is_ascii_digit()) + .collect(); + if digits.is_empty() { + return None; + } + let value: u32 = digits.parse().ok()?; + Some(( + MacroDefinition { + name: format!("\\{}", name.trim_start_matches('\\')), + args: 0, + default: None, + params: None, + body: char::from_u32(value)?.to_string(), + }, + used + skipped + name_used + name_gap + eq_skipped + digits.len(), + )) + } + _ => None, + } +} + /// Parse a simple runtime `\def\name{body}` / `\gdef\name{body}` and return /// the definition, bytes consumed and whether it is global. fn runtime_definition(text: &str) -> Option<(MacroDefinition, usize, bool)> { @@ -1283,6 +1364,16 @@ fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String { changed = true; continue; } + if let Some((definition, used)) = runtime_plain_definition(rest) { + if scopes.is_empty() { + upsert_macro(&mut runtime, definition); + } else if let Some(scope) = scopes.last_mut() { + upsert_macro(scope, definition); + } + index += used; + changed = true; + continue; + } if rest.starts_with(r"\begingroup") { scopes.push(Vec::new()); index += r"\begingroup".len(); @@ -2231,8 +2322,12 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) { let mut geometry = PageGeometry::default(); let mut body = String::new(); let mut tabular: Option<(String, String, &'static str, Option, usize)> = None; + let mut in_document = false; for line in source.lines() { let trimmed = line.trim(); + if trimmed.contains("\\begin{document}") { + in_document = true; + } if let Some((_, text, environment, _, depth)) = tabular.as_mut() { let end = format!("\\end{{{environment}}}"); let closed = trimmed.strip_suffix(&end); @@ -2553,12 +2648,13 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) { || rest.chars().next().is_some_and(char::is_whitespace) }) }; - if is_macro_command("\\newcommand") - || is_macro_command("\\renewcommand") - || is_macro_command("\\DeclareRobustCommand") - || is_macro_command("\\providecommand") - || is_macro_command("\\def") - || is_macro_command("\\gdef") + if !in_document + && (is_macro_command("\\newcommand") + || is_macro_command("\\renewcommand") + || is_macro_command("\\DeclareRobustCommand") + || is_macro_command("\\providecommand") + || is_macro_command("\\def") + || is_macro_command("\\gdef")) { if is_macro_command("\\renewcommand") && let Some(width) = renewcommand_length(definition_line, "headrulewidth") @@ -4803,7 +4899,13 @@ fn capture_body_definitions( ) { let mut kept = String::new(); let mut changed = false; + let mut depth = 0_i32; + let mut depths = Vec::new(); for line in body.lines() { + depths.push(depth); + depth += brace_depth_delta(line); + } + for (line, depth) in body.lines().zip(depths) { let trimmed = line.trim_start(); let definition_line = strip_definition_prefixes(trimmed); if trimmed.starts_with("\\newenvironment") || trimmed.starts_with("\\renewenvironment") { @@ -4831,19 +4933,24 @@ fn capture_body_definitions( changed = true; continue; } - if let Some(definition) = macro_definition(definition_line) + if depth == 0 + && let Some(definition) = macro_definition(definition_line) && definition_consumes_line(definition_line) { macros.push(definition); changed = true; continue; } - if let Some(definition) = char_definition(definition_line) { + if depth == 0 + && let Some(definition) = char_definition(definition_line) + { macros.push(definition); changed = true; continue; } - if let Some((name, target)) = macro_alias(definition_line) { + if depth == 0 + && let Some((name, target)) = macro_alias(definition_line) + { let source = macros .iter() .find(|definition| definition.name == target) @@ -14884,6 +14991,28 @@ A definition. assert!(grouped.contains("twoone"), "{grouped}"); } + #[test] + fn group_lines_and_runtime_aliases() { + let text_of = |source: &str| -> String { + let json = preview_json(source).expect("preview"); + let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); + let svg = value["pages"][0]["svg"].as_str().expect("svg"); + svg.split('>') + .filter_map(|piece| piece.split('<').next()) + .collect::() + .split_whitespace() + .collect() + }; + let grouped = text_of( + "\\documentclass{article}\n\\begin{document}\n\n\\def\\a{one}\n{\n\\def\\a{two}\n\\a\n}\n\\a\n\n\\end{document}\n", + ); + assert!(grouped.contains("twoone"), "{grouped}"); + let aliased = text_of( + "\\documentclass{article}\n\\begin{document}\n\n\\def\\b{Hi}\\let\\c=\\b\\c and \\chardef\\d=65\\d\n\n\\end{document}\n", + ); + assert!(aliased.contains("HiandA"), "{aliased}"); + } + #[test] fn inline_definitions_and_makeatletter_expand() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\makeatletter\\def\\@foo{bar}\\makeatother\\@foo and \\def\\greet{Hello}\\greet.\n\n\\end{document}\n";