diff --git a/README.md b/README.md index 899d7c4..f9e7d46 100644 --- a/README.md +++ b/README.md @@ -121,8 +121,9 @@ the `.tex` file passed to `serve`. It handles document metadata, `\maketitle`, and `\today` (UTC), A4 pages, `geometry` margins (`margin`, `top`, `right`, `bottom`, `left`, `hmargin`, and `vmargin` with `mm`, `cm`, `in`, `pt`, or `bp` units), paragraphs, -numbered and starred heading levels, bold, italic and monospaced text, itemize/enumerate -lists, page breaks, basic display and inline math, figures, simple tables, +numbered and starred heading levels, paragraph indentation (`\parindent`), +`\hfill`, bold, italic and monospaced text, itemize/enumerate lists, page +breaks, basic display and inline math, figures, simple tables, section/figure/table references, and numeric citations from a manual bibliography or a local `.bib` file. A4 pages use 25 mm margins unless `geometry` sets them. Liberation Serif is embedded in the PDF for Latin and math @@ -205,8 +206,9 @@ current line overflow like an overfull TeX hbox rather than wrapping. `\checkmark`, `\textdagger`, `\textdaggerdbl`, `\textperiodcentered`, `\textsection`, `\textparagraph`, `\textbrokenbar`, and `\textvisiblespace` -expand to `✓ † ‡ · § ¶ ¦ ␣`. `\hfill` is still unsupported (the line breaker -does not stretch infinite glue on the last line). +expand to `✓ † ‡ · § ¶ ¦ ␣`. `\hfill` and `\hfil` are infinite horizontal +glue: they stretch the current line to the right margin, including the last +line of a paragraph. Numeric/unit symbols `\textperthousand`, `\textonehalf`, `\textonequarter`, `\textthreequarters`, `\textonesuperior`, `\texttwosuperior`, @@ -324,6 +326,11 @@ Manual `thebibliography` entries also work. Custom `.bst` sorting and formatting author-year citation styles, page-number references, and automatic table of contents are not implemented. +A paragraph starts with the current `\parindent` (17pt by default); the +indent is recorded per paragraph and follows group scoping, `\setlength`, +`\addtolength`, and `\noindent`. Headings and `\maketitle` suppress the +next paragraph's indent. + Boxworks' Knuth–Plass line breaker lays out ordinary text paragraphs with the same Latin, CJK, and monospaced font faces used by the PDF renderer, including bold and italic variants, and applies font pair kerning to line-break widths. @@ -445,7 +452,7 @@ advisory breaks, starred `\vspace`/`\hspace`, `center`, `\hrule`, `\fbox`, | --- | --- | --- | | Boxes | `\rule`, `\fbox`, `\parbox`, inline `\mbox`/`\makebox`, `center`, `\hrule` | inline framed `\fbox`, `\raisebox`, `\minipage`, VBox | | Fonts | serif/mono faces, bold/italic/mono declarations, group scoping, uppercase small caps | `\sffamily` (sans face), real small-cap glyphs | -| Paragraphs | Knuth-Plass breaking, TeX hyphenation, justification, centering | explicit indentation (`\parindent`) | +| Paragraphs | Knuth-Plass breaking, TeX hyphenation, justification, centering, `\parindent` (17pt default), `\hfill`/`\hfil` | `\raggedright`/`\raggedleft` | | Notes/floats | — | footnote insertion area, figure/table floats | | Pages | A4/Letter/... page sizes, margins/geometry, automatic pagination, `\newpage`, `\pagebreak` | headers/footers (`fancyhdr`), unified planner/renderer | | Classes/packages | built-in + local classes, option protocol, local package options | base font-size options (10/11/12pt) | diff --git a/crates/texrra-core/src/document.rs b/crates/texrra-core/src/document.rs index a621f82..1551ab8 100644 --- a/crates/texrra-core/src/document.rs +++ b/crates/texrra-core/src/document.rs @@ -55,12 +55,13 @@ impl Default for PageSize { } } -#[derive(Clone, Default)] +#[derive(Clone)] pub struct DocumentModel { pub title: String, pub author: String, pub date: String, pub page: PageSize, + pub parindent: common::Scaled, pub margins: PageMargins, pub show_title: bool, pub blocks: Vec, @@ -69,6 +70,25 @@ pub struct DocumentModel { pub citations: HashMap, } +impl Default for DocumentModel { + fn default() -> Self { + Self { + title: String::new(), + author: String::new(), + date: String::new(), + page: PageSize::default(), + // article's default \parindent for 10/11pt text. + parindent: common::Scaled(17 * 65_536), + margins: PageMargins::default(), + show_title: false, + blocks: Vec::new(), + block_sources: Vec::new(), + labels: HashMap::new(), + citations: HashMap::new(), + } + } +} + pub struct ParsedDocument(pub DocumentModel); #[derive(Clone)] @@ -199,6 +219,8 @@ pub struct Run { pub bold: bool, pub italic: bool, pub monospace: bool, + /// True for the synthetic kern that carries paragraph indentation. + pub paragraph_indent: bool, } impl Run { @@ -215,6 +237,7 @@ impl Run { bold: false, italic: false, monospace: false, + paragraph_indent: false, } } } diff --git a/crates/texrra-core/src/document_parser.rs b/crates/texrra-core/src/document_parser.rs index 838392c..535c000 100644 --- a/crates/texrra-core/src/document_parser.rs +++ b/crates/texrra-core/src/document_parser.rs @@ -407,6 +407,8 @@ struct Parser { centered: Option>, current_source: Option, paragraph_source: Option, + paragraph_indent: Option, + suppress_indent: bool, } impl Parser { @@ -444,6 +446,8 @@ impl Parser { centered: None, current_source: None, paragraph_source: None, + paragraph_indent: None, + suppress_indent: false, } } @@ -467,9 +471,12 @@ impl Parser { if let Some(candidate) = rich_paragraph_candidate(expanded, item_index, self.document.blocks.len()) { - if let Some(runs) = + if let Some(mut runs) = paragraph_cache.get_rich(&candidate.key, &candidate.math_expressions) { + self.begin_paragraph_if_needed(); + let indent = self.paragraph_indent.take().unwrap_or(common::Scaled::ZERO); + prepend_paragraph_indent(&mut runs, indent); self.push_block_at(Block::Paragraph(runs), Some(candidate.source)); self.current_source = Some(candidate.end_source); item_index = candidate.end_index; @@ -494,8 +501,12 @@ impl Parser { if !pending_text.is_empty() { self.current_source = pending_source.take(); if paragraph_break && self.can_reuse_plain_paragraph() { - let runs = paragraph_cache.parse(&pending_text); + let mut runs = paragraph_cache.parse(&pending_text); if !runs.is_empty() { + self.begin_paragraph_if_needed(); + let indent = + self.paragraph_indent.take().unwrap_or(common::Scaled::ZERO); + prepend_paragraph_indent(&mut runs, indent); self.push_block_at( Block::Paragraph(runs), self.current_source.clone(), @@ -535,7 +546,9 @@ impl Parser { if let Some(Block::Paragraph(runs)) = self.document.blocks.get(candidate.block_index) { - paragraph_cache.insert_rich(candidate.key, runs.clone()); + let mut cached = runs.clone(); + strip_paragraph_indent(&mut cached); + paragraph_cache.insert_rich(candidate.key, cached); } } cache_scan_pending = true; @@ -555,7 +568,9 @@ impl Parser { && candidate.end_index == expanded.items.len() && let Some(Block::Paragraph(runs)) = self.document.blocks.get(candidate.block_index) { - paragraph_cache.insert_rich(candidate.key, runs.clone()); + let mut cached = runs.clone(); + strip_paragraph_indent(&mut cached); + paragraph_cache.insert_rich(candidate.key, cached); } while !self.lists.is_empty() { self.finish_list(); @@ -656,6 +671,7 @@ impl Parser { expanded::FrontendEventKind::MakeTitle => { self.flush_paragraph(); self.document.show_title = true; + self.suppress_indent = true; } expanded::FrontendEventKind::InlineBoxStart => { self.inline_boxes.push(Vec::new()); @@ -675,6 +691,8 @@ impl Parser { bold: false, italic: false, monospace: false, + + paragraph_indent: false, }; self.target_runs().push(run); } @@ -872,6 +890,14 @@ impl Parser { self.start_heading(*level, *numbered) } expanded::FrontendEventKind::HeadingEnd => self.finish_heading(), + expanded::FrontendEventKind::Parindent(width) => { + self.document.parindent = *width; + } + expanded::FrontendEventKind::NoIndent => { + if self.paragraph.is_empty() { + self.suppress_indent = true; + } + } expanded::FrontendEventKind::CaptionStart => { self.flush_paragraph(); self.caption_capture = Some(Vec::new()); @@ -931,6 +957,8 @@ impl Parser { bold, italic: true, monospace: false, + + paragraph_indent: false, }); } @@ -963,10 +991,14 @@ impl Parser { }, heading.source, ); + self.suppress_indent = true; } } fn append_text(&mut self, text: &str) { + if normalize_whitespace(text).is_empty() { + return; + } if !text.is_empty() && self.paragraph.is_empty() && self.heading.is_none() @@ -1043,6 +1075,8 @@ impl Parser { bold, italic, monospace, + + paragraph_indent: false, }); } @@ -1071,6 +1105,8 @@ impl Parser { bold, italic, monospace, + + paragraph_indent: false, }); } @@ -1104,6 +1140,8 @@ impl Parser { bold, italic, monospace, + + paragraph_indent: false, }); } @@ -1147,10 +1185,27 @@ impl Parser { bold, italic, monospace, + + paragraph_indent: false, }); } fn target_runs(&mut self) -> &mut Vec { + let paragraph_target = self.inline_boxes.is_empty() + && self.centered.is_none() + && self.framed_box.is_none() + && self.metadata_capture.is_none() + && self.caption_capture.is_none() + && self.heading.is_none() + && self.table.is_none() + && self.lists.is_empty() + && !self + .bibliography + .as_ref() + .is_some_and(|bibliography| bibliography.current.is_some()); + if paragraph_target { + self.begin_paragraph_if_needed(); + } if let Some(runs) = self.inline_boxes.last_mut() { runs } else if let Some(runs) = &mut self.centered { @@ -1178,6 +1233,23 @@ impl Parser { } } + fn begin_paragraph_if_needed(&mut self) { + if !self.paragraph.is_empty() { + return; + } + // Empty appends (for example whitespace-only tokens or macro-definition + // text in the prelude) must not freeze the indentation of the paragraph + // that eventually receives the first real run. Re-evaluate until a run + // actually lands in the paragraph. + self.paragraph_indent = Some(if self.suppress_indent { + common::Scaled::ZERO + } else { + self.document.parindent + }); + self.suppress_indent = false; + self.paragraph_source = self.current_source.clone(); + } + fn append_literal_ampersand(&mut self) { let bold = self.bold; let italic = self.italic; @@ -1214,6 +1286,8 @@ impl Parser { bold, italic, monospace, + + paragraph_indent: false, }); } @@ -1227,8 +1301,10 @@ impl Parser { fn flush_paragraph(&mut self) { trim_run_end(&mut self.paragraph); + let indent = self.paragraph_indent.take().unwrap_or(common::Scaled::ZERO); if !self.paragraph.is_empty() { - let runs = std::mem::take(&mut self.paragraph); + let mut runs = std::mem::take(&mut self.paragraph); + prepend_paragraph_indent(&mut runs, indent); let source = self.paragraph_source.take(); self.push_block_at(Block::Paragraph(runs), source); } else { @@ -1523,6 +1599,35 @@ pub fn parse_document( Parser::new().parse(source, paragraph_cache) } +fn indent_run(indent: common::Scaled) -> Run { + Run { + text: String::new(), + math: None, + kern: Some(indent), + glue: None, + penalty: None, + rule: None, + box_run: None, + unresolved_reference: None, + bold: false, + italic: false, + monospace: false, + paragraph_indent: true, + } +} + +fn prepend_paragraph_indent(runs: &mut Vec, indent: common::Scaled) { + if indent.0 > 0 { + runs.insert(0, indent_run(indent)); + } +} + +fn strip_paragraph_indent(runs: &mut Vec) { + if runs.first().is_some_and(|run| run.paragraph_indent) { + runs.remove(0); + } +} + fn append_run(runs: &mut Vec, mut text: String, bold: bool, italic: bool, monospace: bool) { if text.is_empty() { return; @@ -1560,6 +1665,8 @@ fn append_run(runs: &mut Vec, mut text: String, bold: bool, italic: bool, m bold, italic, monospace, + + paragraph_indent: false, }); } diff --git a/crates/texrra-core/src/expanded.rs b/crates/texrra-core/src/expanded.rs index 2e46e13..aea741d 100644 --- a/crates/texrra-core/src/expanded.rs +++ b/crates/texrra-core/src/expanded.rs @@ -213,6 +213,8 @@ pub enum FrontendEventKind { level: u8, numbered: bool, }, + Parindent(common::Scaled), + NoIndent, HeadingEnd, CaptionStart, CaptionEnd, diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index df57d92..fe2b919 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -3,23 +3,10 @@ This file lists the concrete implementation plans for the foundational items that are still missing. Each item names the files/functions to touch. -## 1. Paragraph indentation (`\parindent`) +Completed: paragraph indentation (`\parindent`) and `\hfill`/`\hfil` (see +`docs/STATUS.md`). -- Add `parindent: Scaled` to `DocumentModel` (with the 11pt article default 17pt) - and a `Parindent` frontend event. -- Feed `\setlength{\parindent}{...}` through an **engine-side named length - register** (the adapter already stores named lengths); when the register is - written, emit the event. Do not use a prelude `\ifx` conditional: it broke - preamble loading when tried. -- Apply indentation inside the paragraph breaker: the first line's available - width is `line_width - parindent` and its start x is `parindent`. - `boxworks_line_break` / `cached_paragraph_lines` currently take only a width; - extend the signature with a first-line indent and carry the per-line x offset - into `text_layout::LineBox`/`PositionedLine.x`. -- Suppress after headings, after `\maketitle`, and for `\noindent`; track a - `suppress_indent` flag in the parser. - -## 2. Sans family (`\sffamily`) +## 1. Sans family (`\sffamily`) - Load Liberation Sans in `latin_dir` alongside serif/mono (see `font_inputs`/`register_box_font_family` in `src/rust_typeset/pdf.rs`). @@ -30,7 +17,7 @@ are still missing. Each item names the files/functions to touch. - `\sffamily`/`\textsf{...}` become declaration primitives like `\ttfamily`. -## 3. Inline framed boxes / `\raisebox` +## 2. Inline framed boxes / `\raisebox` - Add `y_offset: Mm` to `PositionedSpan` and `PositionedRule`; PDF/SVG painters add it to the baseline. @@ -41,7 +28,7 @@ are still missing. Each item names the files/functions to touch. box rectangle when `frame` is set. - `\raisebox{lift}{...}` reuses the same nested item with `raise = lift`. -## 4. Footnotes +## 3. Footnotes - Parser: capture `\footnote{...}`/`\thanks{...}` into a per-paragraph list with a number marker run (superscript approximation via smaller raised text @@ -50,7 +37,7 @@ are still missing. Each item names the files/functions to touch. text height and place footnotes with a separator rule at the bottom. - Paint footnotes as normal positioned lines after the page's content. -## 5. Floats +## 4. Floats - Classify figure/table blocks as floats with `[htbp]` placement hints. - Planner: maintain pending floats and try top/bottom/page placements; keep @@ -58,13 +45,13 @@ are still missing. Each item names the files/functions to touch. - Renderer: place deferred floats at the saved slots; page keys must include float placement decisions. -## 6. Page styles / headers-footers +## 5. Page styles / headers-footers - `DocumentModel` fields for header/footer runs and `\pagestyle`/`\thispagestyle`. - Paint headers/footers in the page margins in both PDF and SVG; page numbers need a page index placeholder resolved at paint time. -## 7. Unified pagination +## 6. Unified pagination - Extract the current duplicated planner (`build_page_break_plan`) and renderer (`build_positioned_pages`) vertical logic into one page builder returning an diff --git a/docs/STATUS.md b/docs/STATUS.md index d62dc66..c86b00c 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -17,7 +17,8 @@ the source changes; the SVG preview is refreshed per page. - Fonts: Liberation Serif/Mono faces, bold/italic/monospace declarations with group scoping, grouped text-style commands, uppercase small-caps approximation. - Paragraphs: Knuth-Plass breaking, TeX hyphenation patterns, justification, - centering. + centering, 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, automatic pagination, `\newpage`/`\pagebreak`. - Classes/packages: built-in classes, local `.cls`/`.sty`, paper options, @@ -34,9 +35,6 @@ See `docs/ROADMAP.md` for concrete implementation plans. ## Known approximations / gaps -- Paragraphs: no `\parindent` indentation (a parse-side kern experiment did not - take effect and a `\setlength` conditional broke the preamble, so it was - reverted) and no `\hfill` (last-line infinite glue is not stretched). - Fonts: no sans family (`\sffamily` is a no-op); small caps are uppercase-only. - Boxes: `\fbox`/`\parbox` are block-level (an inline `\fbox` starts a block); `\raisebox`, `\minipage`, and VBox material are missing. @@ -52,7 +50,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` (12 tests) covers the three +- `cargo fmt --check` passes; `cargo test --workspace` (15 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/frontend.rs b/src/rust_typeset/frontend.rs index af35807..fda0166 100644 --- a/src/rust_typeset/frontend.rs +++ b/src/rust_typeset/frontend.rs @@ -25,7 +25,9 @@ const PRELUDE: &str = r#" \def\today{__TEXRRA_TODAY__} \def\maketitle{\texrramaketitle} \def\tableofcontents{} -\def\noindent{} +\def\noindent{\texrranoindent} +\def\hfill{\hskip0pt plus 1fil\relax} +\def\hfil{\hskip0pt plus 1fil\relax} \def\allowbreak{\penalty0} \def\nobreak{\penalty10000} \def\centering{} @@ -484,6 +486,7 @@ const PRELUDE: &str = r#" \def\hbox#1{#1} \def\rule{\texrrarule} \skipdef\parindent=100 +\parindent=17pt\relax \skipdef\parskip=101 \skipdef\baselineskip=102 \skipdef\lineskip=103 diff --git a/src/rust_typeset/pdf.rs b/src/rust_typeset/pdf.rs index 80e1526..b6f0fb2 100644 --- a/src/rust_typeset/pdf.rs +++ b/src/rust_typeset/pdf.rs @@ -1247,6 +1247,16 @@ fn boxworks_line_break( let mut params = Params::plain_tex_defaults(); params.emergency_stretch = scaled_points(2.0); + // boxworks always appends a 1fil parfillskip. When the paragraph contains + // explicit infinite glue (\hfill), that trailing glue is excluded from the + // line but still counted in the stretch denominator, which halves every + // \hfill. Drop it so explicit fill glue can claim the full line. + if runs.iter().any(|run| { + run.glue + .is_some_and(|glue| !matches!(glue.stretch_order, texrra_core::TeXGlueOrder::Normal)) + }) { + params.par_fill_skip = common::Glue::ZERO; + } let widths = [scaled_points(width_mm * PDF_POINTS_PER_INCH / 25.4)]; let indents = [Scaled::ZERO]; let hyphenator = TeXHyphenator::get(); @@ -2147,6 +2157,8 @@ pub(super) fn render_pdf( bold: true, italic: false, monospace: false, + + paragraph_indent: false, }]; document.push(paragraph( &heading, diff --git a/src/rust_typeset/texlang_adapter.rs b/src/rust_typeset/texlang_adapter.rs index 095855d..166f082 100644 --- a/src/rust_typeset/texlang_adapter.rs +++ b/src/rust_typeset/texlang_adapter.rs @@ -54,6 +54,9 @@ pub(super) use texrra_core::source::{SourceLocation, SourceOrigin}; const DEFAULT_JOT: common::Scaled = common::Scaled(3 * 65_536); +/// Index of the `\parindent` skip register defined by the compatibility prelude. +const PARINDENT_REGISTER_INDEX: usize = 100; + static PARAGRAPH_BREAK_TAG: texlang::command::StaticTag = texlang::command::StaticTag::new(); static LINE_BREAK_TAG: texlang::command::StaticTag = texlang::command::StaticTag::new(); static PAGE_BREAK_TAG: texlang::command::StaticTag = texlang::command::StaticTag::new(); @@ -1441,17 +1444,17 @@ impl vm::Handlers for OutputHandlers { NativePrimitive::VerticalSkip => { execute_layout_primitive(LayoutPrimitive::VerticalSkip, token, input) } - NativePrimitive::Advance => engine_arithmetic::execute( + NativePrimitive::Advance => arithmetic_with_parindent( engine_arithmetic::ArithmeticOperation::Advance, token, input, ), - NativePrimitive::Multiply => engine_arithmetic::execute( + NativePrimitive::Multiply => arithmetic_with_parindent( engine_arithmetic::ArithmeticOperation::Multiply, token, input, ), - NativePrimitive::Divide => engine_arithmetic::execute( + NativePrimitive::Divide => arithmetic_with_parindent( engine_arithmetic::ArithmeticOperation::Divide, token, input, @@ -1469,7 +1472,13 @@ impl vm::Handlers for OutputHandlers { command: &texlang::variable::Command, scope: texcraft_stdext::collections::groupingmap::Scope, ) -> Option> { - engine_variable::assign_arithmetic(command, token, input, scope) + let parindent = + command.is_glue() && command.static_index() == Some(PARINDENT_REGISTER_INDEX); + let result = engine_variable::assign_arithmetic(command, token, input, scope); + if parindent && matches!(&result, Some(Ok(()))) { + emit_parindent(input, token); + } + result } fn begin_group_hook(input: &mut vm::ExecutionInput, token: token::Token) { @@ -1481,7 +1490,9 @@ impl vm::Handlers for OutputHandlers { fn end_group_hook(input: &mut vm::ExecutionInput, token: token::Token) { let state = input.state_mut(); state.end_engine_group(); + let parindent = current_parindent(input.state()); write_event(input, token, FrontendEventKind::GroupEnd); + write_event(input, token, FrontendEventKind::Parindent(parindent)); } fn character_handler( @@ -1828,6 +1839,57 @@ fn layout_primitive_tag(primitive: LayoutPrimitive) -> texlang::command::Tag { } } +fn current_parindent(state: &CompilerState) -> common::Scaled { + state + .engine + .skip_registers + .get_index_ref(PARINDENT_REGISTER_INDEX) + .width +} + +fn emit_parindent(input: &mut vm::ExecutionInput, token: token::Token) { + let value = current_parindent(input.state()); + write_event(input, token, FrontendEventKind::Parindent(value)); +} + +fn next_token_is_parindent( + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result { + let Some(next) = read_next_non_space_unexpanded(input)? else { + return Ok(false); + }; + let is_parindent = match next.value() { + token::Value::CommandRef(command_ref) => matches!( + engine_command_name(command_ref, input.vm().cs_name_interner()), + EngineCommandName::ControlSequence(name) if name == "parindent" + ), + _ => false, + }; + input.unexpanded().back(next); + Ok(is_parindent) +} + +fn arithmetic_with_parindent( + operation: engine_arithmetic::ArithmeticOperation, + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + let parindent = next_token_is_parindent(input)?; + let result = engine_arithmetic::execute(operation, token, input); + if parindent && result.is_ok() { + emit_parindent(input, token); + } + result +} + +fn no_indent_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + write_event(input, token, FrontendEventKind::NoIndent); + Ok(()) +} + fn make_title_primitive( token: token::Token, input: &mut vm::ExecutionInput, @@ -6735,6 +6797,10 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn 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 x coordinate")) +} + +#[test] +fn paragraph_indent_tracks_setlength_groups_and_noindent() { + let source = r#"\documentclass{article} +\begin{document} +\parindent=0pt +First paragraph. + +\setlength{\parindent}{10mm} +Second paragraph. + +{\setlength{\parindent}{0pt} +Third paragraph. + +} +Fourth paragraph. + +\addtolength{\parindent}{5mm} +Fifth paragraph. + +\noindent +Noindent paragraph. +\end{document} +"#; + let value = fresh_preview(source, "parindent.tex"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + let svg = page_svg(&value, 0); + let first = text_x(&svg, "First"); + let second = text_x(&svg, "Second"); + let third = text_x(&svg, "Third"); + let fourth = text_x(&svg, "Fourth"); + let fifth = text_x(&svg, "Fifth"); + let noindent = text_x(&svg, "Noindent"); + assert!( + first.abs() < 0.1, + "first paragraph should not be indented: {first}" + ); + assert!((second - 10.0).abs() < 0.25, "second indent: {second}"); + assert!(third.abs() < 0.1, "grouped zero indent leaked: {third}"); + assert!( + (fourth - 10.0).abs() < 0.25, + "group restore failed: {fourth}" + ); + assert!((fifth - 15.0).abs() < 0.25, "addtolength failed: {fifth}"); + assert!(noindent.abs() < 0.1, "noindent ignored: {noindent}"); +} + +#[test] +fn default_parindent_is_seventeen_points() { + let source = r#"\documentclass{article} +\begin{document} +Default indent. +\end{document} +"#; + let value = fresh_preview(source, "default-parindent.tex"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + let svg = page_svg(&value, 0); + let x = text_x(&svg, "Default"); + // 17pt is 5.98mm. + assert!((x - 5.98).abs() < 0.15, "default parindent: {x}"); +} + +#[test] +fn hfill_fills_the_remaining_line() { + let source = r#"\documentclass{article} +\begin{document} +\setlength{\parindent}{0pt} +A\hfill B + +C\hfill D\hfill E +\end{document} +"#; + let value = fresh_preview(source, "hfill.tex"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + let svg = page_svg(&value, 0); + let a = text_x(&svg, "A"); + let b = text_x(&svg, "B"); + let c = text_x(&svg, "C"); + let d = text_x(&svg, "D"); + let e = text_x(&svg, "E"); + assert!(a.abs() < 0.1, "A should stay at the left margin: {a}"); + assert!(b > 150.0, "single hfill did not reach the right edge: {b}"); + assert!(c.abs() < 0.1, "C should stay at the left margin: {c}"); + assert!(d > 70.0 && d < 100.0, "middle hfill is not centered: {d}"); + assert!(e > 150.0, "last hfill did not reach the right edge: {e}"); +} diff --git a/vendor/texlang/src/variable.rs b/vendor/texlang/src/variable.rs index 68f9f85..6005d86 100644 --- a/vendor/texlang/src/variable.rs +++ b/vendor/texlang/src/variable.rs @@ -194,6 +194,19 @@ impl Command { | Getters::Font(_, _) => false, } } + + /// Returns the static register index when this command points at one. + pub fn static_index(&self) -> Option { + match &self.index_resolver { + Some(IndexResolver::Static(index)) => Some(index.0), + _ => None, + } + } + + /// Returns true when this command reads and writes glue. + pub fn is_glue(&self) -> bool { + matches!(self.getters, Getters::Glue(_, _)) + } } impl Command {