Paint inline NFSS runs with their own faces

This commit is contained in:
gloamxun committed 2026-10-24 02:09:56 +08:00
1 parent 67898d6a8a
commit 53fabe95db
6 files changed
+223 -17

No files matched your search

+20
View File
@@ -1244,6 +1244,26 @@ impl Unit {
Self::paragraph_with_style_and_face(id, source, style, ParagraphFont::Roman)
}
/// Build a paragraph unit whose text is split into styled runs.
pub fn paragraph_with_style_and_runs(
id: UnitId,
source: impl Into<String>,
style: ParagraphStyle,
runs: Vec<(ParagraphFont, String)>,
) -> Self {
let source = source.into();
let paragraph = crate::paragraph::layout_paragraph_runs(&runs, &style);
Self {
id,
source,
items: vec![VerticalItem::Paragraph(paragraph)],
paragraph_style: Some(style),
space_before: 0,
space_stretch: 0,
space_shrink: 0,
}
}
/// Build a paragraph unit with both an explicit style and font face.
pub fn paragraph_with_style_and_face(
id: UnitId,
+54
View File
@@ -11,6 +11,9 @@ pub struct HorizontalBox {
/// TeX italic correction in scaled points.
#[serde(default)]
pub italic: i64,
/// Font face for this glyph when it comes from a styled run.
#[serde(default)]
pub font: Option<ParagraphFont>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -389,6 +392,7 @@ pub fn text_items(text: &str, style: &ParagraphStyle) -> Vec<HorizontalItem> {
depth: 0,
character: Some(character),
italic: 0,
font: None,
}));
}
}
@@ -852,6 +856,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
depth: 0,
character: Some('-'),
italic: 0,
font: None,
}));
} else if *no_break_width > 0 {
line.push(HorizontalItem::Box(HorizontalBox {
@@ -860,6 +865,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
depth: 0,
character: None,
italic: 0,
font: None,
}));
}
}
@@ -1196,6 +1202,7 @@ pub fn text_items_with_font(
depth: font.depth(character),
character: Some(character),
italic: font.italic(character),
font: None,
}));
let boundary = character_index + 1;
// TeX's defaults for American English are \lefthyphenmin=2 and
@@ -1267,6 +1274,52 @@ pub fn layout_paragraph_with_font(
layout_items(&items, style)
}
/// Lay out a paragraph whose text is split into styled runs.
///
/// Each run is shaped with the TFM of its face, so bold and italic runs get
/// their own advances; a single interword glue is inserted at a run boundary
/// when the source text had whitespace there.
pub fn layout_paragraph_runs(
runs: &[(ParagraphFont, String)],
style: &ParagraphStyle,
) -> Paragraph {
let mut items = Vec::new();
let mut previous: Option<(ParagraphFont, String)> = None;
for (font, text) in runs {
if text.is_empty() {
continue;
}
if let Some((previous_font, previous_text)) = &previous {
let boundary_space = previous_text
.chars()
.next_back()
.is_some_and(char::is_whitespace)
|| text.chars().next().is_some_and(char::is_whitespace);
if boundary_space {
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*previous_font);
items.push(HorizontalItem::Glue {
width: metrics.space(),
stretch: metrics.stretch(),
shrink: metrics.shrink(),
order: 0,
});
}
}
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*font);
let mut run = text_items_with_font(text, style, &metrics);
for item in &mut run {
if let HorizontalItem::Box(box_) = item {
box_.font = Some(*font);
}
}
items.extend(run);
previous = Some((*font, text.clone()));
}
let mut paragraph = layout_items(&items, style);
paragraph.font = runs.first().map(|run| run.0).unwrap_or_default();
paragraph
}
pub fn layout_paragraph(text: &str, style: &ParagraphStyle) -> Paragraph {
let items = text_items(text, style);
layout_items(&items, style)
@@ -1455,6 +1508,7 @@ mod tests {
depth,
character: Some(character),
italic: 0,
font: None,
})
};
let items = vec![
+12 -8
View File
@@ -250,6 +250,16 @@ fn escape(text: &str) -> String {
.replace('>', "&gt;")
}
fn paragraph_face(font: ParagraphFont) -> FontFace {
match font {
ParagraphFont::Roman => FontFace::Roman,
ParagraphFont::Bold => FontFace::Bold,
ParagraphFont::Italic => FontFace::Italic,
ParagraphFont::Mono => FontFace::Mono,
ParagraphFont::Sans => FontFace::Sans,
}
}
fn character_text(character: char) -> String {
match character {
'\u{FB00}' => "ff".to_owned(),
@@ -441,13 +451,7 @@ impl Page {
y += *height + *depth;
}
VerticalItem::Paragraph(paragraph) => {
let face = match paragraph.font {
ParagraphFont::Roman => FontFace::Roman,
ParagraphFont::Bold => FontFace::Bold,
ParagraphFont::Italic => FontFace::Italic,
ParagraphFont::Mono => FontFace::Mono,
ParagraphFont::Sans => FontFace::Sans,
};
let face = paragraph_face(paragraph.font);
let lines = paragraph.lines.len().max(1) as i64;
let line_height = (paragraph.height / lines).max(1);
let size = 10 * 65_536;
@@ -479,7 +483,7 @@ impl Page {
HorizontalItem::Box(box_) => {
if let Some(character) = box_.character {
list.push(DisplayItem::Text {
font: face,
font: box_.font.map_or(face, paragraph_face),
x,
y: baseline,
size,
+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`). 515 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 519 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; 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 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 515 tests (347 route-D unit, 23 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 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.
### M0 incremental demo
+134 -6
View File
@@ -1068,6 +1068,71 @@ fn nfss_font(raw: &str) -> Option<(ParagraphFont, String)> {
Some((font, text.to_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.
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 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;
}
if !found {
return None;
}
plain.push_str(rest);
if !plain.is_empty() {
runs.push((base, plain));
}
Some(runs)
}
fn parse_paragraph(raw: &str) -> SourceParagraph {
if let Some((font, body)) = nfss_font(raw) {
return SourceParagraph {
@@ -1283,12 +1348,20 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do
space_skip: geometry.space_skip,
xspace_skip: geometry.xspace_skip,
};
let mut unit = Unit::paragraph_with_style_and_face(
index as u64,
paragraph.text.clone(),
style,
paragraph.font,
);
let mut unit = match inline_runs(&paragraph.text, paragraph.font) {
Some(runs) => Unit::paragraph_with_style_and_runs(
index as u64,
paragraph.text.clone(),
style,
runs,
),
None => Unit::paragraph_with_style_and_face(
index as u64,
paragraph.text.clone(),
style,
paragraph.font,
),
};
unit.space_before = paragraph.space_before;
unit.space_stretch = paragraph.space_stretch;
unit.space_shrink = paragraph.space_shrink;
@@ -1850,3 +1923,58 @@ mod nfss_tests {
assert_eq!(paragraph_font("\\texttt{code words}"), ParagraphFont::Mono);
}
}
#[cfg(test)]
mod inline_tests {
use super::*;
#[test]
fn inline_commands_split_runs() {
let runs = inline_runs("Plain \\textbf{bold} tail", ParagraphFont::Roman).expect("runs");
assert_eq!(
runs,
vec![
(ParagraphFont::Roman, "Plain ".to_string()),
(ParagraphFont::Bold, "bold".to_string()),
(ParagraphFont::Roman, " tail".to_string()),
]
);
}
#[test]
fn plain_paragraphs_have_no_runs() {
assert!(inline_runs("no commands here", ParagraphFont::Sans).is_none());
}
#[test]
fn base_font_fills_plain_segments() {
let runs = inline_runs("\\texttt{code} and text", ParagraphFont::Sans).expect("runs");
assert_eq!(runs[0], (ParagraphFont::Mono, "code".to_string()));
assert_eq!(runs[1], (ParagraphFont::Sans, " and text".to_string()));
}
#[test]
fn styled_runs_paint_with_their_face() {
let document = Document::new(
550 * 65_536,
vec![Unit::paragraph_with_style_and_runs(
1,
"plain bold",
ParagraphStyle::default(),
vec![
(ParagraphFont::Roman, "plain ".to_string()),
(ParagraphFont::Bold, "bold".to_string()),
],
)],
);
let engine = Engine::layout_paged(&document).expect("pages");
let list = engine.pages()[0].display_list_with_goal(document.page_goal);
assert!(list.items.iter().any(|item| matches!(
item,
texrra_tex_core::render::DisplayItem::Text {
font: texrra_tex_core::render::FontFace::Bold,
..
}
)));
}
}