Parse declaration groups in inline styled text

This commit is contained in:
gloamxun committed 2026-10-24 02:12:29 +08:00
1 parent 53fabe95db
commit 0e8999671b
3 files changed
+155 -58

No files matched your search

+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`). 519 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 522 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
@@ -353,7 +353,7 @@ M3 painter: `Page::display_list()` and `Halign::display_list()` produce absolute
PDF writer: `crates/texrra-tex-core/src/pdf.rs` writes multi-page PDF 1.4 with five embedded Liberation Type0/CID faces (Identity-H + ToUnicode + `/W` arrays), filled rectangles, diagonal rules, raw-RGB `/XObject` images, `/Annots` URI links and arbitrary `/special` operators. Ligature substitution and line-end italic correction are implemented; full NFSS family switching remains open.
M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic,Mono}`. Roman/Bold/Italic/BoldItalic/Mono text are painted with embedded Liberation Type0/CID fonts, each with a ToUnicode CMap and `/W` width array. `cmr10.tfm` is parsed at runtime for widths, heights/depths, kern pairs and ff/fi/fl/ffi/ffl ligatures; line-end and math-script italic corrections and monospace/sans paragraph faces are applied; paragraph-level NFSS declarations (`\rmfamily`, `\sffamily`, `\ttfamily`, `\bfseries`, `\itshape`, `\texttt`, `\textsf`) select those faces and the `\fontfamily`/`\fontseries`/`\fontshape`/`\fontencoding`/`\selectfont` command forms plus legacy `\rm`/`\sf`/`\tt`/`\bf`/`\it`/`\sl`/`\up`/`\normalfont` declarations are parsed; inline `\textbf`/`\emph`/`\textit`/`\texttt`/`\textsf` groups split a paragraph into styled runs, each shaped by its own TFM and painted with its own face; true family/series/shape switching and Type1/CM outlines remain open. `Unit::paragraph` now builds its item stream with `layout_paragraph_with_font`, so CMR10 advances, kerns and ligatures drive paragraph widths; each glyph box also carries the TFM height/depth, and the painter emits 10pt glyphs and the Type0 `/W` array reports CMR10 advances, and ligature boxes paint their component letters, so `pdftotext` keeps word boundaries instead of inserting spaces between letters.
M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic,Mono}`. Roman/Bold/Italic/BoldItalic/Mono text are painted with embedded Liberation Type0/CID fonts, each with a ToUnicode CMap and `/W` width array. `cmr10.tfm` is parsed at runtime for widths, heights/depths, kern pairs and ff/fi/fl/ffi/ffl ligatures; line-end and math-script italic corrections and monospace/sans paragraph faces are applied; paragraph-level NFSS declarations (`\rmfamily`, `\sffamily`, `\ttfamily`, `\bfseries`, `\itshape`, `\texttt`, `\textsf`) select those faces and the `\fontfamily`/`\fontseries`/`\fontshape`/`\fontencoding`/`\selectfont` command forms plus legacy `\rm`/`\sf`/`\tt`/`\bf`/`\it`/`\sl`/`\up`/`\normalfont` declarations are parsed; inline `\textbf`/`\emph`/`\textit`/`\texttt`/`\textsf` groups and `{\bfseries ...}` declaration groups (including nesting) split a paragraph into styled runs, each shaped by its own TFM and painted with its own face; true family/series/shape switching and Type1/CM outlines remain open. `Unit::paragraph` now builds its item stream with `layout_paragraph_with_font`, so CMR10 advances, kerns and ligatures drive paragraph widths; each glyph box also carries the TFM height/depth, and the painter emits 10pt glyphs and the Type0 `/W` array reports CMR10 advances, and ligature boxes paint their component letters, so `pdftotext` keeps word boundaries instead of inserting spaces between letters.
M6 (partial): `DisplayItem::Image` becomes a PDF XObject; `DisplayItem::Link` becomes `/Annots /Subtype /Link /URI`; `DisplayItem::Special` injects raw content-stream operators. SVG previews show images as grey rectangles and specials as comments.
@@ -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`) supplies advances, kerns, ligatures, and italic correction for layout, while the display list and PDF select the matching Liberation face. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 347 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 519 tests (347 route-D unit, 27 engine binary unit, 7 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
The crate currently has 347 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 522 tests (347 route-D unit, 30 engine binary unit, 7 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
### M0 incremental demo
+152 -55
View File
@@ -1070,69 +1070,130 @@ fn nfss_font(raw: &str) -> Option<(ParagraphFont, String)> {
/// Split a paragraph containing inline style commands into styled runs.
///
/// Only whole-group commands are recognised (`\textbf{...}` and friends); the
/// braces are removed and their contents become a run in the requested face.
/// Handles `\textbf{...}`-style wrappers, declaration groups such as
/// `{\bfseries ...}` and arbitrary nesting of both, including braces inside a
/// group. Plain text inherits the surrounding face.
fn inline_runs(text: &str, base: ParagraphFont) -> Option<Vec<(ParagraphFont, String)>> {
const COMMANDS: [(&str, Option<ParagraphFont>); 11] = [
("\\textbf", Some(ParagraphFont::Bold)),
("\\emph", Some(ParagraphFont::Italic)),
("\\textit", Some(ParagraphFont::Italic)),
("\\textsl", Some(ParagraphFont::Italic)),
("\\texttt", Some(ParagraphFont::Mono)),
("\\textsf", Some(ParagraphFont::Sans)),
("\\textmd", None),
("\\textnormal", None),
("\\textup", None),
("\\textrm", None),
("\\textsc", None),
];
let mut runs: Vec<(ParagraphFont, String)> = Vec::new();
let mut plain = String::new();
let mut rest = text;
let mut runs = Vec::new();
let mut found = false;
loop {
let mut next: Option<(usize, usize, Option<ParagraphFont>)> = None;
for (command, font) in COMMANDS {
let Some(position) = rest.find(command) else {
continue;
};
let after = &rest[position + command.len()..];
if !after.starts_with('{') {
continue;
}
if next.is_none_or(|(best, _, _)| position < best) {
next = Some((position, command.len(), font));
}
}
let Some((position, length, font)) = next else {
break;
};
let body_start = position + length + 1;
let Some(offset) = rest[body_start..].find('}') else {
break;
};
let body_end = body_start + offset;
plain.push_str(&rest[..position]);
if !plain.is_empty() {
runs.push((base, std::mem::take(&mut plain)));
}
let body = &rest[body_start..body_end];
if !body.is_empty() {
runs.push((font.unwrap_or(base), body.to_string()));
}
rest = &rest[body_end + 1..];
found = true;
}
parse_runs(text, base, &mut runs, &mut found);
if !found {
return None;
}
plain.push_str(rest);
if !plain.is_empty() {
runs.push((base, plain));
}
Some(runs)
}
fn push_run(runs: &mut Vec<(ParagraphFont, String)>, font: ParagraphFont, text: &str) {
if text.is_empty() {
return;
}
if let Some((last_font, last_text)) = runs.last_mut()
&& *last_font == font
{
last_text.push_str(text);
return;
}
runs.push((font, text.to_string()));
}
/// Match a balanced `{...}` at the start of `rest`, returning its contents and
/// the number of bytes consumed (including both braces).
fn braced_group(rest: &str) -> Option<(&str, usize)> {
if !rest.starts_with('{') {
return None;
}
let mut depth = 0usize;
for (offset, character) in rest.char_indices() {
match character {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
return Some((&rest[1..offset], offset + 1));
}
}
_ => {}
}
}
None
}
const INLINE_COMMANDS: [(&str, Option<ParagraphFont>); 11] = [
("\\textbf", Some(ParagraphFont::Bold)),
("\\emph", Some(ParagraphFont::Italic)),
("\\textit", Some(ParagraphFont::Italic)),
("\\textsl", Some(ParagraphFont::Italic)),
("\\texttt", Some(ParagraphFont::Mono)),
("\\textsf", Some(ParagraphFont::Sans)),
("\\textmd", None),
("\\textnormal", None),
("\\textup", None),
("\\textrm", None),
("\\textsc", None),
];
/// Match a styled wrapper command at the start of `rest`.
fn inline_wrapper(rest: &str) -> Option<(Option<ParagraphFont>, &str, usize)> {
for (command, font) in INLINE_COMMANDS {
let Some(after) = rest.strip_prefix(command) else {
continue;
};
if let Some((inner, length)) = braced_group(after) {
return Some((font, inner, command.len() + length));
}
}
None
}
fn parse_runs(
text: &str,
font: ParagraphFont,
runs: &mut Vec<(ParagraphFont, String)>,
found: &mut bool,
) {
let mut index = 0;
while index < text.len() {
let rest = &text[index..];
if let Some((inner, length)) = braced_group(rest) {
let (inner_font, inner_text) = match nfss_font(inner) {
Some((declared, body)) => (declared, body),
None => (font, inner.to_string()),
};
if nfss_font(inner).is_some() {
*found = true;
}
parse_runs(&inner_text, inner_font, runs, found);
index += length;
continue;
}
if let Some((wrapper_font, inner, length)) = inline_wrapper(rest) {
*found = true;
parse_runs(inner, wrapper_font.unwrap_or(font), runs, found);
index += length;
continue;
}
if rest.starts_with('\\') {
let step = rest
.char_indices()
.skip(1)
.find(|(_, character)| !character.is_ascii_alphabetic())
.map(|(offset, _)| offset.max(1))
.unwrap_or(rest.len());
push_run(runs, font, &rest[..step]);
index += step;
continue;
}
let step = rest
.char_indices()
.skip(1)
.find(|(_, character)| *character == '{' || *character == '\\')
.map(|(offset, _)| offset)
.unwrap_or(rest.len());
push_run(runs, font, &rest[..step]);
index += step;
}
}
fn parse_paragraph(raw: &str) -> SourceParagraph {
if let Some((font, body)) = nfss_font(raw) {
return SourceParagraph {
@@ -1954,6 +2015,42 @@ mod inline_tests {
}
#[test]
#[test]
fn declaration_groups_switch_the_face() {
let runs = inline_runs("{\\bfseries bold} normal", ParagraphFont::Roman).expect("runs");
assert_eq!(
runs,
vec![
(ParagraphFont::Bold, "bold".to_string()),
(ParagraphFont::Roman, " normal".to_string()),
]
);
}
#[test]
fn nested_groups_recurse() {
let runs = inline_runs(
"{\\bfseries bold \\textit{italic} bold} plain",
ParagraphFont::Roman,
)
.expect("runs");
assert_eq!(
runs,
vec![
(ParagraphFont::Bold, "bold ".to_string()),
(ParagraphFont::Italic, "italic".to_string()),
(ParagraphFont::Bold, " bold".to_string()),
(ParagraphFont::Roman, " plain".to_string()),
]
);
}
#[test]
fn wrapper_groups_keep_nested_braces() {
let runs = inline_runs("\\textbf{a {b} c}", ParagraphFont::Roman).expect("runs");
assert_eq!(runs, vec![(ParagraphFont::Bold, "a b c".to_string())]);
}
fn styled_runs_paint_with_their_face() {
let document = Document::new(
550 * 65_536,