Honour raggedright and raggedleft paragraph alignment

This commit is contained in:
gloamxun committed 2026-10-19 14:16:50 +08:00
1 parent c7b7660049
commit 2c8d5e12d8
13 files changed
+238 -40

No files matched your search

+7 -5
View File
@@ -298,7 +298,10 @@ block.
The `center` environment is a block: its content wraps at the text width and
every line is centered without justification (natural spaces), so
`\begin{center}\url{...}\end{center}` and centered short text match LaTeX.
`\centering` inside a paragraph is still a no-op.
`\centering` inside a paragraph is still a no-op. `\raggedright` and
`\raggedleft` are paragraph-level declarations: the affected runs use natural
space widths, the declaration is scoped by groups and the `raggedright`/
`raggedleft` environments, and the final line is not stretched to the margin.
`\rule[raise]{width}{height}` is rendered as a filled rectangle in both the
PDF and the SVG preview, including raised and dropped rules; a zero-thickness
@@ -313,9 +316,8 @@ size and propagate through headings, title material, lists, tables, block
boxes, footnotes, and the default paragraph indent.
Known gaps for full document classes: custom `\maketitle` implementations
are ignored (the engine title layout is used), `\parbox`/`\minipage` are
block-level rather than inline, `\vbox` and `\vtop` map to a full-width block
box rather than true nested VBox material, and the abstract prints as body text
without an "Abstract" heading.
block-level rather than inline, and `\vbox` and `\vtop` map to a full-width
block box rather than true nested VBox material.
`\footnote{...}` captures its content, emits a superscript marker, reserves
space on the page where the paragraph ends, and paints the notes with a
@@ -483,7 +485,7 @@ advisory breaks, starred `\vspace`/`\hspace`, `center`, `\hrule`, `\fbox`,
| --- | --- | --- |
| Boxes | `\rule`, inline framed `\fbox`, block `\parbox`/`\minipage`, `\vbox`/`\vtop` (as full-width block), inline `\mbox`/`\makebox`, `\raisebox`, `center`, `\hrule` | true nested VBox material |
| 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` |
| Paragraphs | Knuth-Plass breaking, TeX hyphenation, justification, centering, `\raggedright`/`\raggedleft`, `\parindent` (17pt default), `\hfill`/`\hfil` | `\centering` in running text |
| Notes/floats | footnotes with page-bottom insertion area, title/author `\thanks`, figure/table `[htbp]` placement (top/bottom/page/here approximations) | deferred float queue, `\textfraction` |
| Contents | `\tableofcontents`, `\listoffigures`, `\listoftables` generated from numbered headings and captions, page numbers resolved after pagination | dotted leaders, per-chapter book/report contents |
| Pages | A4/Letter/... page sizes, margins/geometry, automatic pagination, `\newpage`, `\pagebreak`, plain/fancy page styles, `\thispagestyle`, fancyhdr L/C/R headers and footers | — |
+12
View File
@@ -314,6 +314,15 @@ pub struct RuleBox {
pub height: common::Scaled,
}
/// Paragraph-level alignment requested by `\raggedright` or `\raggedleft`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ParagraphAlignment {
#[default]
Justified,
RaggedRight,
RaggedLeft,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Run {
pub text: String,
@@ -333,6 +342,8 @@ pub struct Run {
pub small_caps: bool,
/// True for the synthetic kern that carries paragraph indentation.
pub paragraph_indent: bool,
/// Alignment declaration active when this run started its paragraph.
pub alignment: Option<ParagraphAlignment>,
}
impl Run {
@@ -354,6 +365,7 @@ impl Run {
sans: false,
small_caps: false,
paragraph_indent: false,
alignment: None,
}
}
}
+62 -3
View File
@@ -4,8 +4,8 @@ use crate::{
TeXGlue, TeXGlueOrder,
document::{
Block, ColumnAlignment, DocumentModel, EquationNumber, InlineBox, InlineBoxAlign,
ListBlock, ListItem, PageMargins, PageSize, PageStyleOverride, ParsedDocument, RuleBox,
Run, UnresolvedReference,
ListBlock, ListItem, PageMargins, PageSize, PageStyleOverride, ParagraphAlignment,
ParsedDocument, RuleBox, Run, UnresolvedReference,
},
expanded,
math_expr::*,
@@ -494,6 +494,8 @@ struct Parser {
paragraph_source: Option<SourceLocation>,
paragraph_indent: Option<common::Scaled>,
suppress_indent: bool,
paragraph_alignment: ParagraphAlignment,
alignment_saves: Vec<ParagraphAlignment>,
}
impl Parser {
@@ -540,6 +542,8 @@ impl Parser {
paragraph_source: None,
paragraph_indent: None,
suppress_indent: false,
paragraph_alignment: ParagraphAlignment::Justified,
alignment_saves: Vec::new(),
}
}
@@ -816,6 +820,7 @@ impl Parser {
sans,
small_caps,
paragraph_indent: false,
alignment: None,
};
self.target_runs().push(marker);
}
@@ -857,6 +862,7 @@ impl Parser {
monospace: false,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
@@ -1001,7 +1007,13 @@ impl Parser {
expanded::FrontendEventKind::ListOfTables => {
self.push_contents_placeholder(CONTENTS_TABLES_MARKER);
}
expanded::FrontendEventKind::GroupStart => self.group_depth += 1,
expanded::FrontendEventKind::ParagraphAlignment(alignment) => {
self.paragraph_alignment = *alignment;
}
expanded::FrontendEventKind::GroupStart => {
self.group_depth += 1;
self.alignment_saves.push(self.paragraph_alignment);
}
expanded::FrontendEventKind::GroupEnd => {
let depth = self.group_depth;
while self
@@ -1014,6 +1026,10 @@ impl Parser {
}
}
self.group_depth = self.group_depth.saturating_sub(1);
self.paragraph_alignment = self
.alignment_saves
.pop()
.unwrap_or(ParagraphAlignment::Justified);
}
expanded::FrontendEventKind::LiteralAmpersand
| expanded::FrontendEventKind::MathCell => self.append_literal_ampersand(),
@@ -1224,6 +1240,7 @@ impl Parser {
monospace: false,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
@@ -1330,6 +1347,12 @@ impl Parser {
small_caps,
);
}
let alignment = self.paragraph_alignment;
if alignment != ParagraphAlignment::Justified
&& let Some(run) = self.target_runs().last_mut()
{
run.alignment = Some(alignment);
}
}
fn append_kern(&mut self, width: common::Scaled) {
@@ -1366,6 +1389,7 @@ impl Parser {
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
@@ -1403,6 +1427,7 @@ impl Parser {
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
@@ -1445,6 +1470,7 @@ impl Parser {
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
@@ -1497,6 +1523,7 @@ impl Parser {
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
@@ -1636,6 +1663,7 @@ impl Parser {
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
@@ -1752,6 +1780,11 @@ impl Parser {
let indent = self.paragraph_indent.take().unwrap_or(common::Scaled::ZERO);
if !self.paragraph.is_empty() {
let mut runs = std::mem::take(&mut self.paragraph);
if self.paragraph_alignment != ParagraphAlignment::Justified
&& let Some(first) = runs.first_mut()
{
first.alignment = Some(self.paragraph_alignment);
}
prepend_paragraph_indent(&mut runs, indent);
let source = self.paragraph_source.take();
self.push_block_at(Block::Paragraph(runs), source);
@@ -1851,6 +1884,30 @@ impl Parser {
});
}
(false, "abstract") => self.flush_paragraph(),
(true, "raggedright") => {
self.flush_paragraph();
self.alignment_saves.push(self.paragraph_alignment);
self.paragraph_alignment = ParagraphAlignment::RaggedRight;
}
(false, "raggedright") => {
self.flush_paragraph();
self.paragraph_alignment = self
.alignment_saves
.pop()
.unwrap_or(ParagraphAlignment::Justified);
}
(true, "raggedleft") => {
self.flush_paragraph();
self.alignment_saves.push(self.paragraph_alignment);
self.paragraph_alignment = ParagraphAlignment::RaggedLeft;
}
(false, "raggedleft") => {
self.flush_paragraph();
self.paragraph_alignment = self
.alignment_saves
.pop()
.unwrap_or(ParagraphAlignment::Justified);
}
(true, "center") => {
self.flush_paragraph();
if self.centered.is_none() {
@@ -2108,6 +2165,7 @@ fn indent_run(indent: common::Scaled) -> Run {
y_offset: None,
footnote_number: None,
paragraph_indent: true,
alignment: None,
}
}
@@ -2193,6 +2251,7 @@ fn append_run(
sans,
small_caps,
paragraph_indent: false,
alignment: None,
y_offset: None,
+1
View File
@@ -245,6 +245,7 @@ pub enum FrontendEventKind {
header: bool,
},
PageNumber,
ParagraphAlignment(crate::document::ParagraphAlignment),
TableOfContents,
ListOfFigures,
ListOfTables,
+5 -10
View File
@@ -9,7 +9,8 @@ family and true scaled small caps; inline box geometry (`\fbox`, `\makebox`,
footnotes/`\thanks`; figure/table `[htbp]` placement approximations; page
styles (plain/fancy, `\thispagestyle`, fancyhdr headers/footers, `\thepage`);
geometry-aware `\textwidth`/`\textheight` named length registers; table of
contents and figure/table lists; native PDF rectangles; unified pagination
contents and figure/table lists; native PDF rectangles; unified pagination;
`\raggedright`/`\raggedleft` declarations and environments
(`build_positioned_pages` is the only page builder and no separate break
planner remains).
@@ -19,24 +20,18 @@ planner remains).
per-page float queue with `\textfraction`/`\topfraction` tuning so a later
float can move ahead of text while preserving source order numbers.
## 2. Paragraph alignment declarations (remaining)
- `\raggedright`/`\raggedleft` are parsed as no-ops. Thread a per-paragraph
alignment into `Block::Paragraph`, then select natural spaces rather than
justification in `boxworks_line_break`/`cached_paragraph_lines`.
## 3. True vertical boxes (remaining)
## 2. True vertical boxes (remaining)
- `\vbox`/`\vtop` currently map to a full-width block `\parbox`. A real VBox
needs a vertical-material capture with its own natural width, baseline, and
nested line/box children in the positioned renderer.
## 4. Contents leaders (remaining)
## 3. Contents leaders (remaining)
- TOC/list entries use infinite glue for right-aligned page numbers. Dotted
leaders require a glue item that repeats a character across its stretch.
## 5. Custom title blocks (remaining)
## 4. Custom title blocks (remaining)
- Let a document-level `\renewcommand{\maketitle}` contribute a real title
block once the engine's title model can run box material.
+3 -2
View File
@@ -20,7 +20,8 @@ the source changes; the SVG preview is refreshed per page.
declarations with group scoping, grouped text-style commands, true small caps
(lowercase uppercase glyphs at 80% size), and sans/serif/mono small caps.
- Paragraphs: Knuth-Plass breaking, TeX hyphenation patterns, justification,
centering, first-line `\parindent` (17pt default, group-scoped, `\setlength`/
centering, `\raggedright`/`\raggedleft` declarations and environments,
first-line `\parindent` (17pt default, group-scoped, `\setlength`/
`\addtolength`/`\noindent` aware), and `\hfill`/`\hfil` infinite glue.
- Pages: A4/A5/B5/Letter/Legal/Executive, landscape, geometry margins and
text block, geometry-aware `\textwidth`/`\textheight`/`\linewidth`/
@@ -71,7 +72,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 --offline` (33 tests: 29 compiler
- `cargo fmt --check` passes; `cargo test --offline` (35 tests: 31 compiler
integration tests + 4 server tests) covers the three examples, the arXiv
fixture, floats/newpage, page styles and `\thispagestyle`, SVG/PDF output,
project API, static frontend assets, path traversal, the legacy
-2
View File
@@ -32,8 +32,6 @@ const PRELUDE: &str = r#"
\def\allowbreak{\penalty0}
\def\nobreak{\penalty10000}
\def\centering{}
\def\raggedright{}
\def\raggedleft{}
\def\bibliographystyle#1{}
\def\textbf#1{\texrrastylestart{bold}#1\texrrastyleend{bold}}
\def\emph#1{\texrrastylestart{italic}#1\texrrastyleend{italic}}
+5
View File
@@ -86,6 +86,7 @@ struct PositionedLine {
y: i64,
x: i64,
centered: bool,
ragged: bool,
}
struct PositionedTableLine {
@@ -495,6 +496,9 @@ impl Element for PositionedPages {
} else {
text_line
};
if planned_line.ragged {
text_line = text_line.ragged();
}
text_line.render(context, line_area, inherited_style)?
}
PositionedLineContent::InlineMath(element) => {
@@ -2346,6 +2350,7 @@ pub(super) fn render_pdf(
monospace: false,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
+34 -2
View File
@@ -1,5 +1,5 @@
use super::*;
use texrra_core::document::UnresolvedReference;
use texrra_core::document::{ParagraphAlignment, UnresolvedReference};
const ARTICLE_11PT_LIST_TOPSEP_PT: f64 = 9.0;
const ARTICLE_11PT_LIST_TOPSEP_STRETCH_PT: f64 = 3.0;
@@ -1172,6 +1172,7 @@ fn append_page_footnotes(
y,
x: 0,
centered: false,
ragged: false,
}));
y = y.saturating_add(separator_gap);
for line in note_lines {
@@ -1185,6 +1186,7 @@ fn append_page_footnotes(
y,
x: millimeters_to_scaled(8.0),
centered: false,
ragged: false,
}));
y = y.saturating_add(height);
}
@@ -1315,6 +1317,7 @@ pub(super) fn build_positioned_pages(
y: cursor,
x: 0,
centered: true,
ragged: false,
}));
cursor = cursor.saturating_add(line.height);
}
@@ -1387,6 +1390,27 @@ pub(super) fn build_positioned_pages(
max_depth,
);
let paragraph_alignment = runs.iter().find_map(|run| run.alignment);
let ragged = paragraph_alignment.is_some();
let x = match (paragraph_alignment, &line.content) {
(
Some(ParagraphAlignment::RaggedLeft),
PositionedLineContent::Text { line, font_size },
) => {
let text_line = text_layout::TextLine::new(
line,
cjk_family,
mono_family,
sans_family,
*font_size,
);
millimeters_to_scaled(
(content_width_mm - text_line.natural_width_mm(font_cache))
.max(0.0),
)
}
_ => 0,
};
pages
.last_mut()
.expect("the page list starts with one page")
@@ -1395,8 +1419,9 @@ pub(super) fn build_positioned_pages(
anchor,
content: line.content,
y: cursor,
x: 0,
x,
centered: false,
ragged,
}));
cursor = cursor.saturating_add(line_height);
}
@@ -1561,6 +1586,7 @@ pub(super) fn build_positioned_pages(
y: cursor,
x: 0,
centered: false,
ragged: false,
}));
cursor = cursor.saturating_add(rule_height);
pending_gap = paragraph_gap;
@@ -1726,6 +1752,7 @@ pub(super) fn build_positioned_pages(
y: cursor,
x: millimeters_to_scaled(label_x_mm),
centered: false,
ragged: false,
}));
}
}
@@ -1739,6 +1766,7 @@ pub(super) fn build_positioned_pages(
y: cursor,
x: millimeters_to_scaled(x_mm),
centered: false,
ragged: false,
}));
cursor = cursor.saturating_add(line.height);
}
@@ -1802,6 +1830,7 @@ pub(super) fn build_positioned_pages(
y: cursor,
x: 0,
centered: true,
ragged: false,
}));
cursor = cursor.saturating_add(line.height);
line_index += 1;
@@ -2034,6 +2063,7 @@ pub(super) fn build_positioned_pages(
y: cursor,
x: 0,
centered: false,
ragged: false,
}));
cursor = cursor.saturating_add(line.height);
line_index += 1;
@@ -2083,6 +2113,7 @@ pub(super) fn build_positioned_pages(
y: cursor,
x: 0,
centered: false,
ragged: false,
}));
cursor = cursor.saturating_add(line.height);
line_index += 1;
@@ -2343,6 +2374,7 @@ fn append_decoration(
y,
x,
centered: false,
ragged: false,
}));
y = y.saturating_add(line.height);
}
+27 -12
View File
@@ -91,6 +91,7 @@ fn page_svg(
} else {
Alignment::Left
},
line.ragged,
content_width,
fonts,
cjk_family,
@@ -180,6 +181,7 @@ fn write_table(
x,
y + Mm::from(cursor + cell_y),
alignment,
false,
column_width,
fonts,
cjk_family,
@@ -228,6 +230,7 @@ fn write_figure(
Mm::from(0.0),
y + Mm::from(cursor),
Alignment::Center,
false,
content_width,
fonts,
cjk_family,
@@ -245,6 +248,7 @@ fn write_line_content(
x: Mm,
y: Mm,
alignment: Alignment,
ragged: bool,
area_width: Mm,
fonts: &fonts::FontCache,
cjk_family: Option<FontFamily<fonts::Font>>,
@@ -253,18 +257,27 @@ fn write_line_content(
) {
match content {
PositionedLineContent::Text { line, font_size } => {
text_layout::TextLine::new(line, cjk_family, monospace_family, sans_family, *font_size)
.aligned(alignment)
.write_svg(
fonts,
cjk_family,
monospace_family,
sans_family,
area_width,
x,
y,
output,
);
let mut text_line = text_layout::TextLine::new(
line,
cjk_family,
monospace_family,
sans_family,
*font_size,
)
.aligned(alignment);
if ragged {
text_line = text_line.ragged();
}
text_line.write_svg(
fonts,
cjk_family,
monospace_family,
sans_family,
area_width,
x,
y,
output,
);
}
PositionedLineContent::InlineMath(element) => {
element.write_svg(
@@ -324,6 +337,7 @@ fn write_framed_box(
Mm::from(element.inset_mm),
line_y,
Alignment::Left,
false,
Mm::from(width - 2.0 * element.inset_mm),
fonts,
cjk_family,
@@ -359,6 +373,7 @@ fn write_centered(
Mm::from(0.0),
line_y,
Alignment::Center,
false,
content_width,
fonts,
cjk_family,
+36
View File
@@ -1710,6 +1710,34 @@ fn page_style_primitive(
Ok(())
}
fn ragged_right_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
write_event(
input,
token,
FrontendEventKind::ParagraphAlignment(
texrra_core::document::ParagraphAlignment::RaggedRight,
),
);
Ok(())
}
fn ragged_left_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
write_event(
input,
token,
FrontendEventKind::ParagraphAlignment(
texrra_core::document::ParagraphAlignment::RaggedLeft,
),
);
Ok(())
}
fn table_of_contents_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
@@ -6765,6 +6793,14 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn<Compil
texlang::command::BuiltIn::new_execution(page_break_primitive)
.with_tag(layout_primitive_tag(LayoutPrimitive::PageBreak)),
);
built_ins.insert(
"raggedright",
texlang::command::BuiltIn::new_execution(ragged_right_primitive),
);
built_ins.insert(
"raggedleft",
texlang::command::BuiltIn::new_execution(ragged_left_primitive),
);
built_ins.insert(
"pagestyle",
texlang::command::BuiltIn::new_execution(page_style_primitive),
+18 -4
View File
@@ -83,6 +83,8 @@ pub(super) struct TextLine {
width: Scaled,
items: Vec<TextLineItem>,
alignment: Alignment,
/// Keep natural inter-word spaces instead of the justified glue widths.
ragged: bool,
font_size: u8,
}
@@ -270,6 +272,7 @@ impl TextLine {
width: line.width,
items,
alignment: Alignment::Left,
ragged: false,
font_size,
}
}
@@ -279,6 +282,11 @@ impl TextLine {
self
}
pub(super) fn ragged(mut self) -> Self {
self.ragged = true;
self
}
pub(super) fn aligned(mut self, alignment: Alignment) -> Self {
self.alignment = alignment;
self
@@ -286,17 +294,23 @@ impl TextLine {
/// Natural (unjustified) width of the line in millimetres, for centering
/// and right-aligning decorations whose box may be wider than the text.
pub(super) fn natural_width_mm(&self, fonts: &fonts::FontCache) -> f64 {
pub(crate) fn natural_width_mm(&self, fonts: &fonts::FontCache) -> f64 {
let natural_space = Style::new()
.with_font_size(self.font_size)
.str_width(fonts, " ");
let mut x = Mm::from(0.0);
for item in &self.items {
let last_content = self
.items
.iter()
.rposition(|item| !matches!(item, TextLineItem::Glue(_)))
.unwrap_or(0);
for (index, item) in self.items.iter().enumerate() {
match item {
TextLineItem::Text(span) => {
x += span.style.str_width(fonts, &span.text);
}
TextLineItem::Glue(_) => x += natural_space,
TextLineItem::Glue(_) if index < last_content => x += natural_space,
TextLineItem::Glue(_) => {}
TextLineItem::Kern(width) => x += *width,
TextLineItem::Rule { width, .. } => x += *width,
TextLineItem::Frame { width, .. } => x += *width,
@@ -373,7 +387,7 @@ impl TextLine {
x += span.style.str_width(fonts, &span.text);
}
TextLineItem::Glue(width) => {
x += if self.alignment == Alignment::Left {
x += if self.alignment == Alignment::Left && !self.ragged {
*width
} else {
natural_space
+28
View File
@@ -896,3 +896,31 @@ Body.
"section numbering changed: {svg}"
);
}
#[test]
fn ragged_alignment_declarations_are_honoured() {
let prefix = r"\documentclass{article}
\usepackage[margin=6.5cm]{geometry}
\begin{document}
";
let ragged_source = format!(
"{prefix}{{\\raggedleft Right}}\n\n{{\\raggedright alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu}}\n\\end{{document}}"
);
let justified_source = format!(
"{prefix}alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu\n\\end{{document}}"
);
let ragged = fresh_preview(&ragged_source, "ragged.tex");
let justified = fresh_preview(&justified_source, "justified.tex");
let ragged_svg = page_svg(&ragged, 0);
let justified_svg = page_svg(&justified, 0);
assert!(
text_x(&ragged_svg, "Right") > 30.0,
"raggedleft did not move to the right margin: {ragged_svg}"
);
let ragged_beta = text_x(&ragged_svg, "beta");
let justified_beta = text_x(&justified_svg, "beta");
assert!(
ragged_beta + 0.2 < justified_beta,
"raggedright still justified the line: ragged={ragged_beta}, justified={justified_beta}\nRAGGED={ragged_svg}\nJUSTIFIED={justified_svg}"
);
}