From 32b0064e5fc9c3638b3e53ccfad0e59b6d68dc83 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Mon, 19 Oct 2026 12:58:21 +0800 Subject: [PATCH] Add inline box raise and makebox alignment --- README.md | 11 +- crates/texrra-core/src/document.rs | 19 ++- crates/texrra-core/src/document_parser.rs | 59 ++++++-- crates/texrra-core/src/expanded.rs | 6 +- docs/ROADMAP.md | 3 +- docs/STATUS.md | 7 +- src/rust_typeset/pdf.rs | 170 ++++++++++++++++++---- src/rust_typeset/pdf/layout.rs | 31 ++-- src/rust_typeset/texlang_adapter.rs | 69 ++++++++- src/rust_typeset/text_layout.rs | 55 +++++-- tests/typeset.rs | 68 +++++++++ 11 files changed, 425 insertions(+), 73 deletions(-) diff --git a/README.md b/README.md index ce97017..74bdda6 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,8 @@ is measured as a single unbreakable unit, spaces inside become fixed-width kerns (no stretching, no line break, and hyphenation is suppressed inside the box), and nested boxes and inline rules are preserved. Boxes that do not fit on the current line overflow like an overfull TeX hbox rather than wrapping. +`\makebox[width][l|c|r]{...}` fixes the box width and aligns its content, and +`\raisebox{lift}{...}` lifts inline content (or a nested box) by a dimension. `\checkmark`, `\textdagger`, `\textdaggerdbl`, `\textperiodcentered`, `\textsection`, `\textparagraph`, `\textbrokenbar`, and `\textvisiblespace` @@ -290,10 +292,9 @@ Known gaps for full document classes: base font-size class options (`10pt`/`11pt`/`12pt`) are parsed but the engine still uses 11pt; footnotes and `\thanks` are dropped, custom `\maketitle` implementations are ignored (the engine title layout is -used), `\raisebox` and `\minipage` are not implemented yet, inline `\fbox` -still starts a block instead of an inline frame, `\parbox` is block-level -rather than inline, and the abstract prints as body text without an -"Abstract" heading. +used), `\minipage` is not implemented yet, inline `\fbox` still starts a block +instead of an inline frame, `\parbox` is block-level rather than inline, and the +abstract prints as body text without an "Abstract" heading. Basic `\input{file}` imports are read relative to the main `.tex` file. Imported files participate in source mapping and frontend cache invalidation. Local style @@ -453,7 +454,7 @@ advisory breaks, starred `\vspace`/`\hspace`, `center`, `\hrule`, `\fbox`, | Area | Implemented | Remaining | | --- | --- | --- | -| Boxes | `\rule`, `\fbox`, `\parbox`, inline `\mbox`/`\makebox`, `center`, `\hrule` | inline framed `\fbox`, `\raisebox`, `\minipage`, VBox | +| Boxes | `\rule`, block `\fbox`/`\parbox`, inline `\mbox`/`\makebox` (fixed width and alignment), `\raisebox`, `center`, `\hrule` | inline framed `\fbox`, `\minipage`, VBox | | Fonts | serif/sans/mono faces, bold/italic/mono/sans declarations, group scoping, true scaled small caps | — | | Paragraphs | Knuth-Plass breaking, TeX hyphenation, justification, centering, `\parindent` (17pt default), `\hfill`/`\hfil` | `\raggedright`/`\raggedleft` | | Notes/floats | — | footnote insertion area, figure/table floats | diff --git a/crates/texrra-core/src/document.rs b/crates/texrra-core/src/document.rs index d846b1b..511d340 100644 --- a/crates/texrra-core/src/document.rs +++ b/crates/texrra-core/src/document.rs @@ -187,10 +187,25 @@ pub enum UnresolvedReference { Citation(Vec), } -/// An unbreakable inline box such as `\mbox{...}` or `\makebox{...}`. +/// Horizontal alignment of a fixed-width inline box. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum InlineBoxAlign { + #[default] + Left, + Center, + Right, +} + +/// An unbreakable inline box such as `\mbox{...}`, `\makebox{...}`, +/// `\raisebox{...}`, or `\fbox{...}`. #[derive(Clone, PartialEq, Eq, Hash)] pub struct InlineBox { pub runs: Vec, + /// Fixed width from `\makebox[width]{...}`, if any. + pub width: Option, + pub align: InlineBoxAlign, + /// Vertical lift from `\raisebox{lift}{...}`. + pub raise: common::Scaled, } /// A filled rectangle produced by `\rule`. @@ -215,6 +230,7 @@ pub struct Run { pub penalty: Option, pub rule: Option, pub box_run: Option, + pub y_offset: Option, pub unresolved_reference: Option, pub bold: bool, pub italic: bool, @@ -235,6 +251,7 @@ impl Run { penalty: None, rule: None, box_run: None, + y_offset: None, unresolved_reference: None, bold: false, italic: false, diff --git a/crates/texrra-core/src/document_parser.rs b/crates/texrra-core/src/document_parser.rs index a50b594..8c5f46e 100644 --- a/crates/texrra-core/src/document_parser.rs +++ b/crates/texrra-core/src/document_parser.rs @@ -3,8 +3,9 @@ use std::collections::{HashMap, VecDeque}; use crate::{ TeXGlue, document::{ - Block, ColumnAlignment, DocumentModel, EquationNumber, InlineBox, ListBlock, ListItem, - PageMargins, PageSize, ParsedDocument, RuleBox, Run, UnresolvedReference, + Block, ColumnAlignment, DocumentModel, EquationNumber, InlineBox, InlineBoxAlign, + ListBlock, ListItem, PageMargins, PageSize, ParsedDocument, RuleBox, Run, + UnresolvedReference, }, expanded, math_expr::*, @@ -374,6 +375,13 @@ fn consume_environment_preamble( start_index } +struct InlineBoxSpec { + runs: Vec, + width: Option, + align: InlineBoxAlign, + raise: common::Scaled, +} + struct Parser { document: DocumentModel, paragraph: Vec, @@ -404,7 +412,7 @@ struct Parser { framed_box: Option>, box_frame: bool, box_width: Option, - inline_boxes: Vec>, + inline_boxes: Vec, centered: Option>, current_source: Option, paragraph_source: Option, @@ -681,12 +689,21 @@ impl Parser { self.document.show_title = true; self.suppress_indent = true; } - expanded::FrontendEventKind::InlineBoxStart => { - self.inline_boxes.push(Vec::new()); + expanded::FrontendEventKind::InlineBoxStart { + width, + align, + raise, + } => { + self.inline_boxes.push(InlineBoxSpec { + runs: Vec::new(), + width: *width, + align: *align, + raise: *raise, + }); } expanded::FrontendEventKind::InlineBoxEnd => { - if let Some(mut runs) = self.inline_boxes.pop() { - trim_run_end(&mut runs); + if let Some(mut spec) = self.inline_boxes.pop() { + trim_run_end(&mut spec.runs); let run = Run { text: String::new(), math: None, @@ -694,7 +711,12 @@ impl Parser { glue: None, penalty: None, rule: None, - box_run: Some(InlineBox { runs }), + box_run: Some(InlineBox { + runs: spec.runs, + width: spec.width, + align: spec.align, + raise: spec.raise, + }), unresolved_reference: None, bold: false, italic: false, @@ -704,6 +726,8 @@ impl Parser { sans: false, small_caps: false, + + y_offset: None, }; self.target_runs().push(run); } @@ -973,6 +997,8 @@ impl Parser { sans: false, small_caps: false, + + y_offset: None, }); } @@ -1093,6 +1119,8 @@ impl Parser { sans: false, small_caps: false, + + y_offset: None, }); } @@ -1126,6 +1154,8 @@ impl Parser { sans: false, small_caps: false, + + y_offset: None, }); } @@ -1164,6 +1194,8 @@ impl Parser { sans: false, small_caps: false, + + y_offset: None, }); } @@ -1212,6 +1244,8 @@ impl Parser { sans: false, small_caps: false, + + y_offset: None, }); } @@ -1231,8 +1265,8 @@ impl Parser { if paragraph_target { self.begin_paragraph_if_needed(); } - if let Some(runs) = self.inline_boxes.last_mut() { - runs + if let Some(spec) = self.inline_boxes.last_mut() { + &mut spec.runs } else if let Some(runs) = &mut self.centered { runs } else if let Some(runs) = &mut self.framed_box { @@ -1326,6 +1360,8 @@ impl Parser { sans: false, small_caps: false, + + y_offset: None, }); } @@ -1652,6 +1688,7 @@ fn indent_run(indent: common::Scaled) -> Run { monospace: false, sans: false, small_caps: false, + y_offset: None, paragraph_indent: true, } } @@ -1718,6 +1755,8 @@ fn append_run( sans, small_caps, paragraph_indent: false, + + y_offset: None, }); } diff --git a/crates/texrra-core/src/expanded.rs b/crates/texrra-core/src/expanded.rs index a7c8971..f8efc5d 100644 --- a/crates/texrra-core/src/expanded.rs +++ b/crates/texrra-core/src/expanded.rs @@ -98,7 +98,11 @@ pub enum FrontendEventKind { width: Option, }, FramedBoxEnd, - InlineBoxStart, + InlineBoxStart { + width: Option, + align: crate::document::InlineBoxAlign, + raise: common::Scaled, + }, InlineBoxEnd, MetadataStart(MetadataField), MetadataEnd(MetadataField), diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 927aa11..ee47d4a 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -6,7 +6,7 @@ are still missing. Each item names the files/functions to touch. Completed: paragraph indentation (`\parindent`) and `\hfill`/`\hfil`; sans family and true scaled small caps (see `docs/STATUS.md`). -## 1. Inline framed boxes / `\raisebox` +## 1. Inline framed `\fbox` - Add `y_offset: Mm` to `PositionedSpan` and `PositionedRule`; PDF/SVG painters add it to the baseline. @@ -15,7 +15,6 @@ family and true scaled small caps (see `docs/STATUS.md`). advances by its width. - Paint child items at `x + inset`, baseline `- raise`; draw frame rules at the box rectangle when `frame` is set. -- `\raisebox{lift}{...}` reuses the same nested item with `raise = lift`. ## 2. Footnotes diff --git a/docs/STATUS.md b/docs/STATUS.md index c452466..87f0e76 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -13,7 +13,8 @@ the source changes; the SVG preview is refreshed per page. - Headings: numbered `\section`/`\subsection`/`\subsubsection` and starred `\section*` variants (starred headings do not advance the counter). - Box material: `\rule` (raise/width/height), block `\fbox`, `\parbox`, - inline `\mbox`/`\makebox`, `center`, `\hrule` with `width`/`height`. + inline `\mbox`, `\makebox[width][align]`, `\raisebox`, `center`, `\hrule` + with `width`/`height`. - Fonts: Liberation Serif/Sans/Mono faces, bold/italic/monospace/sans declarations with group scoping, grouped text-style commands, true small caps (lowercase uppercase glyphs at 80% size), and sans/serif/mono small caps. @@ -37,7 +38,7 @@ See `docs/ROADMAP.md` for concrete implementation plans. ## Known approximations / gaps - Boxes: `\fbox`/`\parbox` are block-level (an inline `\fbox` starts a block); - `\raisebox`, `\minipage`, and VBox material are missing. + `\minipage` and VBox material are missing. - Pages: no footnote insertion area, no floats, no headers/footers (fancyhdr commands are accepted as no-ops), planner and renderer are separate. - Lengths: `\textwidth`/`\textheight`/`\linewidth`/`\columnwidth` are fixed @@ -50,7 +51,7 @@ See `docs/ROADMAP.md` for concrete implementation plans. - `examples/hello.tex`, `examples/boxes.tex`, `examples/compat.tex` compile to one A4 page each; the arXiv template project compiles to 3 Letter pages. -- `cargo fmt --check` passes; `cargo test --workspace` (17 tests) covers the three +- `cargo fmt --check` passes; `cargo test --workspace` (19 tests) covers the three examples, the arXiv fixture, SVG/PDF output, project API, static frontend assets, path traversal, the legacy `/texrra` endpoint, and page-hash cache stability. diff --git a/src/rust_typeset/pdf.rs b/src/rust_typeset/pdf.rs index 187f1b5..da7d1e2 100644 --- a/src/rust_typeset/pdf.rs +++ b/src/rust_typeset/pdf.rs @@ -1002,6 +1002,65 @@ fn box_font_id_variant( } } +fn flat_runs_width( + runs: &[Run], + font_repo: &box_font::Repo, + latin_font_ids: &FontFamily, + monospace_font_ids: Option<&FontFamily>, + sans_font_ids: Option<&FontFamily>, + small_latin_font_ids: &FontFamily, + small_monospace_font_ids: Option<&FontFamily>, + small_sans_font_ids: Option<&FontFamily>, + cjk_font_id: Option, +) -> common::Scaled { + let mut width = common::Scaled::ZERO; + for run in runs { + if let Some(rule) = &run.rule { + width = common::Scaled(width.0.saturating_add(rule.width.0)); + continue; + } + if let Some(kern) = run.kern { + width = common::Scaled(width.0.saturating_add(kern.0)); + continue; + } + if let Some(glue) = &run.glue { + width = common::Scaled(width.0.saturating_add(glue.width.0)); + continue; + } + for character in run.text.chars() { + let mut glyph_character = character; + let mut font_id = paragraph_font_id( + latin_font_ids, + cjk_font_id, + monospace_font_ids, + sans_font_ids, + run, + character, + ); + if run.small_caps && character.is_lowercase() { + let mut upper = character.to_uppercase(); + if let Some(upper_character) = upper.next() + && upper.next().is_none() + { + glyph_character = upper_character; + let small_family = if run.monospace { + small_monospace_font_ids.unwrap_or(small_latin_font_ids) + } else if run.sans { + small_sans_font_ids.unwrap_or(small_latin_font_ids) + } else { + small_latin_font_ids + }; + font_id = box_font_id_variant(small_family, run.bold, run.italic); + } + } + if let Some(glyph_width) = font_repo.get(font_id).width(glyph_character) { + width = common::Scaled(width.0.saturating_add(glyph_width.0)); + } + } + } + width +} + fn paragraph_font_id( latin: &FontFamily, cjk: Option, @@ -1025,48 +1084,84 @@ fn paragraph_font_id( } #[allow(clippy::too_many_arguments)] -const INLINE_BOX_START: char = '\u{F1000}'; -const INLINE_BOX_END: char = '\u{F1001}'; - +#[allow(clippy::too_many_arguments)] fn flatten_inline_boxes( runs: &[Run], font_repo: &mut box_font::Repo, latin_font_ids: &FontFamily, monospace_font_ids: Option<&FontFamily>, sans_font_ids: Option<&FontFamily>, + small_latin_font_ids: &FontFamily, + small_monospace_font_ids: Option<&FontFamily>, + small_sans_font_ids: Option<&FontFamily>, cjk_font_id: Option, + size: u8, + markers: &mut HashMap>, + next_marker: &mut u32, inside: bool, ) -> Vec { let mut flattened = Vec::new(); for run in runs { if let Some(inline) = &run.box_run { - let mut start = run.clone(); - start.box_run = None; - start.text = INLINE_BOX_START.to_string(); - start.math = None; - start.kern = None; - start.glue = None; - start.penalty = None; - start.rule = None; - flattened.push(start); - flattened.extend(flatten_inline_boxes( + let mut content = flatten_inline_boxes( &inline.runs, font_repo, latin_font_ids, monospace_font_ids, sans_font_ids, + small_latin_font_ids, + small_monospace_font_ids, + small_sans_font_ids, cjk_font_id, + size, + markers, + next_marker, true, - )); - let mut end = run.clone(); - end.box_run = None; - end.text = INLINE_BOX_END.to_string(); - end.math = None; - end.kern = None; - end.glue = None; - end.penalty = None; - end.rule = None; - flattened.push(end); + ); + let content_width = flat_runs_width( + &content, + font_repo, + latin_font_ids, + monospace_font_ids, + sans_font_ids, + small_latin_font_ids, + small_monospace_font_ids, + small_sans_font_ids, + cjk_font_id, + ); + let (left_pad, right_pad) = match inline.width { + Some(width) if width > content_width => { + let extra = width.0 - content_width.0; + let left = match inline.align { + texrra_core::document::InlineBoxAlign::Left => 0, + texrra_core::document::InlineBoxAlign::Center => extra / 2, + texrra_core::document::InlineBoxAlign::Right => extra, + }; + (common::Scaled(left), common::Scaled(extra - left)) + } + _ => (common::Scaled::ZERO, common::Scaled::ZERO), + }; + let start_char = char::from_u32(*next_marker) + .expect("inline box markers stay inside a Unicode private use plane"); + *next_marker += 1; + let end_char = char::from_u32(*next_marker) + .expect("inline box markers stay inside a Unicode private use plane"); + *next_marker += 1; + markers.insert(start_char, Some(inline.raise)); + markers.insert(end_char, None); + flattened.push(Run::plain(start_char.to_string())); + if left_pad.0 > 0 { + let mut pad = Run::plain(String::new()); + pad.kern = Some(left_pad); + flattened.push(pad); + } + flattened.extend(content.drain(..)); + if right_pad.0 > 0 { + let mut pad = Run::plain(String::new()); + pad.kern = Some(right_pad); + flattened.push(pad); + } + flattened.push(Run::plain(end_char.to_string())); continue; } if !inside { @@ -1194,13 +1289,21 @@ fn boxworks_line_break( if let Some(sans) = &small_sans_font_ids { register_style_ids(&mut style_by_font, sans, true, false, small_size); } + let mut inline_markers: HashMap> = HashMap::new(); + let mut next_inline_marker = 0xF2000_u32; let flattened = flatten_inline_boxes( runs, &mut font_repo, &latin_font_ids, monospace_font_ids.as_ref(), sans_font_ids.as_ref(), + &small_latin_font_ids, + small_monospace_font_ids.as_ref(), + small_sans_font_ids.as_ref(), cjk_font_id, + size, + &mut inline_markers, + &mut next_inline_marker, false, ); let mut horizontal = Vec::new(); @@ -1259,7 +1362,7 @@ fn boxworks_line_break( previous_font_id = None; } for character in run.text.chars() { - if character == INLINE_BOX_START || character == INLINE_BOX_END { + if inline_markers.contains_key(&character) { horizontal.push( ds::Char { char: character, @@ -1401,6 +1504,7 @@ fn boxworks_line_break( .break_line(&mut vertical, &mut horizontal); let mut lines = Vec::new(); + let mut raise_stack: Vec = Vec::new(); for item in vertical { let ds::Vertical::HBox(line_box) = item else { continue; @@ -1456,16 +1560,25 @@ fn boxworks_line_break( for item in &line_box.list { match item { ds::Horizontal::Char(character) => { - if character.font == null_font_id - && (character.char == INLINE_BOX_START || character.char == INLINE_BOX_END) - { + if let Some(marker) = inline_markers.get(&character.char) { + match marker { + Some(raise) => { + let current = raise_stack.last().copied().unwrap_or_default(); + raise_stack.push(common::Scaled(current.0.saturating_add(raise.0))); + } + None => { + raise_stack.pop(); + } + } continue; } + let y_offset = raise_stack.last().copied().unwrap_or_default(); if let Some(rule) = rules.get(&character.char) { line_items.push(text_layout::LineItem::Rule { width: rule.width, raise: rule.raise, height: rule.height, + y_offset, }); } else { let (bold, italic, monospace, sans, glyph_size) = style_by_font @@ -1479,6 +1592,7 @@ fn boxworks_line_break( monospace, sans, font_size: glyph_size, + y_offset, }); } } @@ -2364,6 +2478,8 @@ pub(super) fn render_pdf( sans: false, small_caps: false, + + y_offset: None, }]; document.push(paragraph( &heading, diff --git a/src/rust_typeset/pdf/layout.rs b/src/rust_typeset/pdf/layout.rs index 84cbd5f..ee17b60 100644 --- a/src/rust_typeset/pdf/layout.rs +++ b/src/rust_typeset/pdf/layout.rs @@ -871,6 +871,7 @@ fn layout_framed_runs( width: rule.width, raise: rule.raise, height: rule.height, + y_offset: run.y_offset.unwrap_or_default(), }); width += Mm::from(scaled_units_to_mm(i64::from(rule.width.0))); let above = i64::from(rule.raise.0) + i64::from(rule.height.0); @@ -945,6 +946,7 @@ fn layout_framed_runs( monospace: run.monospace, sans: run.sans, font_size: glyph_size, + y_offset: run.y_offset.unwrap_or_default(), }); } } @@ -1960,6 +1962,7 @@ pub(super) fn build_positioned_pages( width: rule_width, raise: common::Scaled::ZERO, height: *height, + y_offset: common::Scaled::ZERO, }], pre_display_size: None, }; @@ -2690,18 +2693,26 @@ pub(super) fn text_line_metrics_scaled( cjk_family: Option>, mono_family: Option>, sans_family: Option>, - font_size: u8, + _font_size: u8, ) -> (i64, i64) { let mut ascent_mm = Mm::from(0.0); let mut descent_mm = Mm::from(0.0); for item in &line.items { - if let text_layout::LineItem::Rule { raise, height, .. } = item { - let above = i64::from(raise.0) + i64::from(height.0); + if let text_layout::LineItem::Rule { + raise, + height, + y_offset, + .. + } = item + { + let above = i64::from(raise.0) + i64::from(height.0) + i64::from(y_offset.0); if above > 0 { ascent_mm = ascent_mm.max(Mm::from(scaled_units_to_mm(above))); } - if raise.0 < 0 { - descent_mm = descent_mm.max(Mm::from(scaled_units_to_mm(i64::from(-raise.0)))); + if raise.0 + y_offset.0 < 0 { + descent_mm = descent_mm.max(Mm::from(scaled_units_to_mm(i64::from( + -raise.0 - y_offset.0, + )))); } continue; } @@ -2712,6 +2723,7 @@ pub(super) fn text_line_metrics_scaled( monospace, sans, font_size: glyph_size, + y_offset, } = item else { continue; @@ -2738,10 +2750,11 @@ pub(super) fn text_line_metrics_scaled( } } let font = style.font(font_cache); - let glyph_height = font.glyph_height(font_size); - ascent_mm = ascent_mm.max(glyph_height); - descent_mm = - descent_mm.max((style.line_height(font_cache) - glyph_height).max(Mm::from(0.0))); + let glyph_height = font.glyph_height(*glyph_size); + let y_offset = Mm::from(scaled_units_to_mm(i64::from(y_offset.0))); + ascent_mm = ascent_mm.max(glyph_height + y_offset); + descent_mm = descent_mm + .max((style.line_height(font_cache) - glyph_height - y_offset).max(Mm::from(0.0))); } let ascent = i64::from(scaled_points(f64::from(ascent_mm) * PDF_POINTS_PER_INCH / 25.4).0); let height = diff --git a/src/rust_typeset/texlang_adapter.rs b/src/rust_typeset/texlang_adapter.rs index 837afcd..2c1b338 100644 --- a/src/rust_typeset/texlang_adapter.rs +++ b/src/rust_typeset/texlang_adapter.rs @@ -2940,9 +2940,72 @@ fn makebox_primitive( token: token::Token, input: &mut vm::ExecutionInput, ) -> texlang::prelude::Result<()> { + let width = match read_optional_bracketed_argument(input, token, "makebox width")? { + Some(tokens) => Some(dimension_from_argument(input, token, &tokens)?), + None => None, + }; + let align = match read_optional_bracketed_argument(input, token, "makebox alignment")? { + Some(tokens) => { + let value = tokens + .iter() + .filter_map(|token| token.char()) + .collect::(); + match value.trim() { + "l" | "" => texrra_core::document::InlineBoxAlign::Left, + "c" => texrra_core::document::InlineBoxAlign::Center, + "r" => texrra_core::document::InlineBoxAlign::Right, + other => { + return Err(input.fatal_error(error::SimpleTokenError::new( + token, + format!("makebox alignment must be l, c, or r, found `{other}`"), + ))); + } + } + } + None => texrra_core::document::InlineBoxAlign::Left, + }; let content = read_unexpanded_argument(input, token, "expects box content")?; let inner = strip_braced_tokens(&content).to_vec(); - write_event(input, token, FrontendEventKind::InlineBoxStart); + write_event( + input, + token, + FrontendEventKind::InlineBoxStart { + width, + align, + raise: common::Scaled::ZERO, + }, + ); + let trace_key = token.trace_key(); + let mut expansion = inner; + expansion.push(control_sequence_token( + input, + "texrrainlineboxend", + trace_key, + )); + input + .as_mut() + .expansions_mut() + .extend(expansion.into_iter().rev()); + Ok(()) +} + +fn raisebox_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + let lift_tokens = read_unexpanded_argument(input, token, "expects a raise amount")?; + let lift = dimension_from_argument(input, token, &lift_tokens)?; + let content = read_unexpanded_argument(input, token, "expects box content")?; + let inner = strip_braced_tokens(&content).to_vec(); + write_event( + input, + token, + FrontendEventKind::InlineBoxStart { + width: None, + align: texrra_core::document::InlineBoxAlign::Left, + raise: lift, + }, + ); let trace_key = token.trace_key(); let mut expansion = inner; expansion.push(control_sequence_token( @@ -6284,6 +6347,10 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn { flush_text( &mut items, @@ -123,6 +134,7 @@ impl TextLine { sans_family, *glyph_size, ), + y_offset: scaled_to_mm(*y_offset), })); } LineItem::Glyph { @@ -132,8 +144,9 @@ impl TextLine { monospace, sans, font_size: glyph_size, + y_offset, } => { - let style_key = (*bold, *italic, *monospace, *sans, *glyph_size); + let style_key = (*bold, *italic, *monospace, *sans, *glyph_size, *y_offset); if text_style != Some(style_key) { flush_text( &mut items, @@ -152,6 +165,7 @@ impl TextLine { width, raise, height, + y_offset, } => { flush_text( &mut items, @@ -166,6 +180,7 @@ impl TextLine { width: scaled_to_mm(*width), raise: scaled_to_mm(*raise), height: scaled_to_mm(*height), + y_offset: scaled_to_mm(*y_offset), }); } LineItem::Glue(width) => { @@ -239,15 +254,17 @@ impl TextLine { width, raise, height, + y_offset, } => { if *height > Mm::from(0.0) { - ascent = ascent.max(*raise + *height); - descent = descent.max(Mm::from(0.0) - *raise); + ascent = ascent.max(*raise + *height + *y_offset); + descent = descent.max(Mm::from(0.0) - *raise - *y_offset); rules.push(PositionedRule { x, width: *width, raise: *raise, height: *height, + y_offset: *y_offset, }); } } @@ -255,12 +272,14 @@ impl TextLine { let font = span.style.font(fonts); let glyph_height = font.glyph_height(span.style.font_size()); let line_height = span.style.line_height(fonts); - ascent = ascent.max(glyph_height); - descent = descent.max((line_height - glyph_height).max(Mm::from(0.0))); + ascent = ascent.max(glyph_height + span.y_offset); + descent = descent + .max((line_height - glyph_height - span.y_offset).max(Mm::from(0.0))); spans.push(PositionedSpan { text: span.text.clone(), style: span.style, x, + y_offset: span.y_offset, }); x += span.style.str_width(fonts, &span.text); } @@ -306,7 +325,7 @@ impl TextLine { output, "", f64::from(x + horizontal_offset + rule.x), - f64::from(baseline - rule.raise - rule.height), + f64::from(baseline - rule.y_offset - rule.raise - rule.height), f64::from(rule.width), f64::from(rule.height), ); @@ -332,7 +351,7 @@ impl TextLine { output, "{}", f64::from(x + horizontal_offset + span.x), - f64::from(baseline), + f64::from(baseline - span.y_offset), svg_font_size(span.style.font_size()), escape_html(&span.text), ); @@ -343,7 +362,7 @@ impl TextLine { fn flush_text( items: &mut Vec, text: &mut String, - style_key: &mut Option<(bool, bool, bool, bool, u8)>, + style_key: &mut Option<(bool, bool, bool, bool, u8, Scaled)>, cjk_family: Option>, monospace_family: Option>, sans_family: Option>, @@ -353,9 +372,10 @@ fn flush_text( *style_key = None; return; } - let (bold, italic, monospace, sans, glyph_size) = style_key - .take() - .unwrap_or((false, false, false, false, font_size)); + let (bold, italic, monospace, sans, glyph_size, y_offset) = + style_key + .take() + .unwrap_or((false, false, false, false, font_size, Scaled::ZERO)); items.push(TextLineItem::Text(TextSpan { text: std::mem::take(text), style: text_style_for( @@ -369,6 +389,7 @@ fn flush_text( sans_family, glyph_size, ), + y_offset: scaled_to_mm(y_offset), })); } @@ -436,7 +457,10 @@ impl Element for TextLine { let scale_y = f64::from(rule.height) * 300.0 / 25.4; area.add_image( &black, - Position::new(rule.x + horizontal_offset, layout.ascent - rule.raise), + Position::new( + rule.x + horizontal_offset, + layout.ascent - rule.y_offset - rule.raise, + ), Scale::new(scale_x, scale_y), Rotation::default(), Some(300.0), @@ -450,7 +474,10 @@ impl Element for TextLine { let glyph_height = style .font(&context.font_cache) .glyph_height(style.font_size()); - let position = Position::new(span.x + horizontal_offset, layout.ascent - glyph_height); + let position = Position::new( + span.x + horizontal_offset, + layout.ascent - glyph_height - span.y_offset, + ); if area .text_section(&context.font_cache, position, style) .is_none() diff --git a/tests/typeset.rs b/tests/typeset.rs index ac25211..4b64d13 100644 --- a/tests/typeset.rs +++ b/tests/typeset.rs @@ -336,3 +336,71 @@ fn small_caps_uses_reduced_uppercase_glyphs() { "full-size capitals should remain full-size" ); } + +fn text_y(svg: &str, needle: &str) -> f64 { + let closing = format!("{needle}"); + let index = svg + .find(&closing) + .unwrap_or_else(|| panic!("missing text element containing `{needle}`")); + let start = svg[..index] + .rfind("().ok()) + .unwrap_or_else(|| panic!("text element for `{needle}` has no y coordinate")) +} + +#[test] +fn raisebox_lifts_content_inline() { + let source = r#"\documentclass{article} +\begin{document} +\setlength{\parindent}{0pt} +A\raisebox{4pt}{raised}B +\end{document} +"#; + let value = fresh_preview(source, "raisebox.tex"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + let svg = page_svg(&value, 0); + let baseline = text_y(&svg, "A"); + let raised = text_y(&svg, "raised"); + let lift = baseline - raised; + // 4pt = 1.411mm. + assert!((lift - 1.411).abs() < 0.15, "raisebox lift: {lift}"); +} + +#[test] +fn makebox_honours_width_and_alignment() { + let source = r#"\documentclass{article} +\begin{document} +\setlength{\parindent}{0pt} +X\makebox[20mm][c]{mid}Y + +\makebox[40mm][l]{L}\makebox[40mm][r]{R} +\end{document} +"#; + let value = fresh_preview(source, "makebox.tex"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + let svg = page_svg(&value, 0); + let x = text_x(&svg, "X"); + let mid = text_x(&svg, "mid"); + let y = text_x(&svg, "Y"); + assert!( + mid > x + 7.0, + "centered box content did not move right: {mid}" + ); + assert!(mid < y - 4.0, "centered box content overflowed: {mid}"); + assert!( + (y - x - 22.8).abs() < 0.5, + "fixed box width not honoured: {}", + y - x + ); + let left = text_x(&svg, "L"); + let right = text_x(&svg, "R"); + assert!( + right > left + 70.0, + "right-aligned box did not fill width: {right}" + ); +}