diff --git a/README.md b/README.md index 79266bd..cbb5cf0 100644 --- a/README.md +++ b/README.md @@ -272,15 +272,17 @@ collapsed to an ordinary space in text). the starred form (`\vspace*{12pt}`, `\hspace*{1cm}`); the star is consumed and the dimension is passed to `\vskip`/`\hskip`. -`\textwidth` (160mm), `\textheight` (247mm), `\linewidth`, and -`\columnwidth` are provided as fixed defaults for the A4 content box, so -`\parbox{\textwidth}` and `\rule{\textwidth}{1pt}` work; they are not -geometry-aware yet (a changed page size or margin keeps these defaults). +`\textwidth`, `\textheight`, `\linewidth`, and `\columnwidth` are live +named length registers updated from the page size and geometry, so +`\parbox{\textwidth}` and `\rule{\textwidth}{1pt}` follow the current text +block. The mm-to-TeX-point conversion differs from TeX by about 0.4%. `\smallbreak`, `\medbreak`, `\bigbreak` add the corresponding skip (the encouraged page break itself is not inserted yet). `\tableofcontents`, -`\listoffigures`, and `\listoftables` are accepted as no-ops because contents -lists are not generated yet. +`\listoffigures`, and `\listoftables` generate a heading followed by one +entry per numbered section or captioned figure/table; page numbers are filled +in after pagination. Entries use infinite glue for right-aligned page numbers +rather than dotted leaders. Vertical skips are active: `\smallskip`, `\medskip`, and `\bigskip` map to 3pt/6pt/12pt `\vskip` glue, and `\addvspace{...}` forwards its argument to @@ -349,8 +351,8 @@ author/editor, title, journal, booktitle, volume, number, pages, publisher, institution, school, organization, edition, address, month, note, and year fields. BibTeX `@string` macros and single-level `crossref` inheritance are supported. 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. +author-year citation styles and page-number references (`\pageref`) are not +implemented. A paragraph starts with the current `\parindent` (17pt by default); the indent is recorded per paragraph and follows group scoping, `\setlength`, @@ -481,6 +483,7 @@ advisory breaks, starred `\vspace`/`\hspace`, `center`, `\hrule`, `\fbox`, | 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 | 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 | unified planner/renderer | | Classes/packages | built-in + local classes, option protocol, local package options, base font sizes 10/11/12pt | class-specific section formatting | | Live preview | incremental paragraph/page caches, page-hash diffing, SVG refresh | — | diff --git a/crates/texrra-core/src/document.rs b/crates/texrra-core/src/document.rs index 261e07c..801cd99 100644 --- a/crates/texrra-core/src/document.rs +++ b/crates/texrra-core/src/document.rs @@ -273,6 +273,9 @@ pub struct ListItem { pub enum UnresolvedReference { Label(String), Citation(Vec), + /// A table-of-contents/list page number for the block with this index. + /// The target is resolved to a page number during page layout. + TocPage(usize), } /// Horizontal alignment of a fixed-width inline box. diff --git a/crates/texrra-core/src/document_parser.rs b/crates/texrra-core/src/document_parser.rs index 1cbcb64..2366614 100644 --- a/crates/texrra-core/src/document_parser.rs +++ b/crates/texrra-core/src/document_parser.rs @@ -1,7 +1,7 @@ use std::collections::{HashMap, VecDeque}; use crate::{ - TeXGlue, + TeXGlue, TeXGlueOrder, document::{ Block, ColumnAlignment, DocumentModel, EquationNumber, InlineBox, InlineBoxAlign, ListBlock, ListItem, PageMargins, PageSize, PageStyleOverride, ParsedDocument, RuleBox, @@ -382,6 +382,23 @@ struct MinipageBuilder { width: Option, } +/// Marker characters used by placeholders for generated contents lists. +const CONTENTS_TOC_MARKER: char = '\u{F6200}'; +const CONTENTS_FIGURES_MARKER: char = '\u{F6201}'; +const CONTENTS_TABLES_MARKER: char = '\u{F6202}'; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum ContentsKind { + TableOfContents, + ListOfFigures, + ListOfTables, +} + +struct ContentsEntry { + runs: Vec, + target: usize, +} + struct InlineBoxSpec { runs: Vec, width: Option, @@ -390,6 +407,41 @@ struct InlineBoxSpec { frame: bool, } +fn contents_kind(block: &Block) -> Option { + let Block::Paragraph(runs) = block else { + return None; + }; + if runs.len() != 1 { + return None; + } + match runs[0].text.chars().next() { + Some(character) if character == CONTENTS_TOC_MARKER => Some(ContentsKind::TableOfContents), + Some(character) if character == CONTENTS_FIGURES_MARKER => { + Some(ContentsKind::ListOfFigures) + } + Some(character) if character == CONTENTS_TABLES_MARKER => Some(ContentsKind::ListOfTables), + _ => None, + } +} + +fn contents_line_runs(title: &[Run], target: usize) -> Vec { + let mut runs = title.to_vec(); + trim_run_end(&mut runs); + let mut filler = Run::plain(String::new()); + filler.glue = Some(TeXGlue { + width: common::Scaled::ZERO, + stretch: common::Scaled(65536), + stretch_order: TeXGlueOrder::Fil, + shrink: common::Scaled::ZERO, + shrink_order: TeXGlueOrder::Normal, + }); + runs.push(filler); + let mut page = Run::plain("00".to_string()); + page.unresolved_reference = Some(UnresolvedReference::TocPage(target)); + runs.push(page); + runs +} + struct Parser { document: DocumentModel, paragraph: Vec, @@ -626,6 +678,7 @@ impl Parser { } self.finish_table(); self.finish_bibliography(); + self.finalize_contents(); ParsedDocument(self.document) } @@ -939,6 +992,15 @@ impl Parser { run.small_caps = self.small_caps; self.target_runs().push(run); } + expanded::FrontendEventKind::TableOfContents => { + self.push_contents_placeholder(CONTENTS_TOC_MARKER); + } + expanded::FrontendEventKind::ListOfFigures => { + self.push_contents_placeholder(CONTENTS_FIGURES_MARKER); + } + expanded::FrontendEventKind::ListOfTables => { + self.push_contents_placeholder(CONTENTS_TABLES_MARKER); + } expanded::FrontendEventKind::GroupStart => self.group_depth += 1, expanded::FrontendEventKind::GroupEnd => { let depth = self.group_depth; @@ -1594,6 +1656,97 @@ impl Parser { } } + fn push_contents_placeholder(&mut self, marker: char) { + self.flush_paragraph(); + self.push_block(Block::Paragraph(vec![Run::plain(marker.to_string())])); + } + + fn finalize_contents(&mut self) { + let mut toc_entries = Vec::new(); + let mut figure_entries = Vec::new(); + let mut table_entries = Vec::new(); + for (index, block) in self.document.blocks.iter().enumerate() { + match block { + Block::Heading { level, runs } if *level <= 3 => { + let numbered = runs.first().is_some_and(|run| { + run.text + .chars() + .next() + .is_some_and(|character| character.is_ascii_digit()) + }); + if numbered { + toc_entries.push(ContentsEntry { + runs: runs.clone(), + target: index, + }); + } + } + Block::Image { + caption: Some(caption), + .. + } => figure_entries.push(ContentsEntry { + runs: caption.clone(), + target: index, + }), + Block::Table { + caption: Some(caption), + .. + } => table_entries.push(ContentsEntry { + runs: caption.clone(), + target: index, + }), + _ => {} + } + } + let has_placeholders = self + .document + .blocks + .iter() + .any(|block| contents_kind(block).is_some()); + if !has_placeholders { + return; + } + let blocks = std::mem::take(&mut self.document.blocks); + let sources = std::mem::take(&mut self.document.block_sources); + let mut output_index = Vec::with_capacity(blocks.len()); + let mut next = 0; + for block in &blocks { + output_index.push(next); + next += match contents_kind(block) { + Some(ContentsKind::TableOfContents) => 1 + toc_entries.len(), + Some(ContentsKind::ListOfFigures) => 1 + figure_entries.len(), + Some(ContentsKind::ListOfTables) => 1 + table_entries.len(), + None => 1, + }; + } + let mut expanded_blocks = Vec::with_capacity(next); + let mut expanded_sources = Vec::with_capacity(next); + for (index, block) in blocks.into_iter().enumerate() { + if let Some(kind) = contents_kind(&block) { + let source = sources.get(index).cloned().flatten(); + let (title, entries) = match kind { + ContentsKind::TableOfContents => ("Contents", &toc_entries), + ContentsKind::ListOfFigures => ("List of Figures", &figure_entries), + ContentsKind::ListOfTables => ("List of Tables", &table_entries), + }; + let mut title_runs = vec![Run::plain(title.to_string())]; + title_runs[0].bold = true; + expanded_blocks.push(Block::Paragraph(title_runs)); + expanded_sources.push(source.clone()); + for entry in entries { + let target = output_index[entry.target]; + expanded_blocks.push(Block::Paragraph(contents_line_runs(&entry.runs, target))); + expanded_sources.push(source.clone()); + } + } else { + expanded_blocks.push(block); + expanded_sources.push(sources.get(index).cloned().flatten()); + } + } + self.document.blocks = expanded_blocks; + self.document.block_sources = expanded_sources; + } + fn flush_paragraph(&mut self) { trim_run_end(&mut self.paragraph); let indent = self.paragraph_indent.take().unwrap_or(common::Scaled::ZERO); diff --git a/crates/texrra-core/src/expanded.rs b/crates/texrra-core/src/expanded.rs index 23d8fcb..141a004 100644 --- a/crates/texrra-core/src/expanded.rs +++ b/crates/texrra-core/src/expanded.rs @@ -245,6 +245,9 @@ pub enum FrontendEventKind { header: bool, }, PageNumber, + TableOfContents, + ListOfFigures, + ListOfTables, GroupStart, GroupEnd, } diff --git a/crates/texrra-core/src/references.rs b/crates/texrra-core/src/references.rs index 817636f..f5bd6b2 100644 --- a/crates/texrra-core/src/references.rs +++ b/crates/texrra-core/src/references.rs @@ -14,7 +14,11 @@ pub fn resolve(parsed: ParsedDocument) -> DocumentModel { let Some(reference) = run.unresolved_reference.take() else { continue; }; - run.text = match reference { + let text = match reference { + UnresolvedReference::TocPage(index) => { + run.unresolved_reference = Some(UnresolvedReference::TocPage(index)); + continue; + } UnresolvedReference::Label(key) => labels .get(&key) .cloned() @@ -33,6 +37,7 @@ pub fn resolve(parsed: ParsedDocument) -> DocumentModel { format!("[{formatted}]") } }; + run.text = text; } } diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 986cb3e..c472bd6 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -25,13 +25,14 @@ and geometry-aware `\textwidth`/`\textheight` named length registers. tables, block boxes, footnotes, and the default `\parindent` (15pt for 10/12pt, 17pt for 11pt). -## 3. Table of contents and lists +## 3. Table of contents and lists (implemented) -- Record section/figure/table entries while parsing, then generate - `\tableofcontents`, `\listoffigures`, and `\listoftables` blocks with - resolved page numbers after pagination. +- Parser placeholders are expanded after parsing into headings plus entries + from numbered sections and captions; entry runs carry a `TocPage` reference + that is resolved by re-laying out once page numbers are known. Dotted + leaders are not implemented. -## 4. PDF painting and title blocks +## 4. PDF painting and title blocks (remaining) - Paint rules and frames as native PDF rectangles (`printpdf` operators) instead of 1x1 image XObjects. diff --git a/docs/STATUS.md b/docs/STATUS.md index 9038ad5..710b7df 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -32,6 +32,12 @@ the source changes; the SVG preview is refreshed per page. resolved at paint time. - Notes: `\footnote{...}` page-bottom insertion area with separator rule, superscript markers, and title/author `\thanks`. +- Contents: `\tableofcontents`, `\listoffigures`, and `\listoftables` + generate headings plus entries from numbered sections and captioned + figures/tables; page numbers are resolved after pagination. +- Class sizes: 10pt/11pt/12pt set the body size and propagate through + headings, title material, lists, tables, block boxes, footnotes, and the + default paragraph indent (10/12pt use 15pt; 11pt uses 17pt). - Classes/packages: built-in classes, local `.cls`/`.sty`, paper options, `\DeclareOption`/`\ProcessOptions`/`\ExecuteOptions`/option passing. - Compatibility: spacing macros (quad/qquad/thin/en/med/thick, `\vspace*`, @@ -54,18 +60,17 @@ See `docs/ROADMAP.md` for concrete implementation plans. - Notes: footnotes inside captions, floats, or arbitrary boxes are not collected; the insertion area currently follows the page where the paragraph ends rather than the exact reference line. -- Class sizes: 10pt/11pt/12pt set the body size and propagate through - headings, title material, lists, tables, block boxes, footnotes, and the - default paragraph indent (10/12pt use 15pt; 11pt uses 17pt). -- Miscellaneous: \tableofcontents/list commands are no-ops; rules are - painted with 1x1 images in PDF; a document-level \renewcommand{\maketitle} - is ignored in favor of the engine title block. +- Contents: entries use infinite glue instead of dotted leaders and only + numbered headings plus captions are listed; per-chapter contents in + book/report are not distinguished. +- Miscellaneous: rules are painted with 1x1 images in PDF; a document-level + \renewcommand{\maketitle} is ignored in favor of the engine title block. ## Verification - `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` (28 tests: 24 compiler +- `cargo fmt --check` passes; `cargo test --offline` (32 tests: 28 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 diff --git a/src/rust_typeset/frontend.rs b/src/rust_typeset/frontend.rs index 0760041..41586ca 100644 --- a/src/rust_typeset/frontend.rs +++ b/src/rust_typeset/frontend.rs @@ -24,7 +24,6 @@ const PRELUDE: &str = r#" \def\date#1{\texrrametadatastart{date}#1\texrrametadataend{date}} \def\today{__TEXRRA_TODAY__} \def\maketitle{\texrramaketitle} -\def\tableofcontents{} \def\noindent{\texrranoindent} \def\vbox#1{\parbox{\textwidth}{#1}} \def\vtop#1{\parbox{\textwidth}{#1}} @@ -336,9 +335,6 @@ const PRELUDE: &str = r#" \def\smallbreak{\smallskip} \def\medbreak{\medskip} \def\bigbreak{\bigskip} -\def\tableofcontents{} -\def\listoffigures{} -\def\listoftables{} \def\enspace{\hskip0.5em\relax} \def\thinspace{\hskip0.16667em\relax} \def\negthinspace{\hskip-0.16667em\relax} @@ -472,8 +468,6 @@ const PRELUDE: &str = r#" \def\value#1{0} \def\enlargethispage#1{} \def\appendix{} -\def\listoffigures{} -\def\listoftables{} \def\abstractname{Abstract} \def\refname{References} \def\bibname{References} diff --git a/src/rust_typeset/pdf/layout.rs b/src/rust_typeset/pdf/layout.rs index 9e1fcf4..b61215f 100644 --- a/src/rust_typeset/pdf/layout.rs +++ b/src/rust_typeset/pdf/layout.rs @@ -1,4 +1,5 @@ use super::*; +use texrra_core::document::UnresolvedReference; const ARTICLE_11PT_LIST_TOPSEP_PT: f64 = 9.0; const ARTICLE_11PT_LIST_TOPSEP_STRETCH_PT: f64 = 3.0; @@ -62,7 +63,7 @@ pub(super) fn layout_document( snapshot: None, }; }; - let Some(pages) = build_positioned_pages( + let Some(first_pages) = build_positioned_pages( model, source_dir, &plan.breaks, @@ -83,6 +84,25 @@ pub(super) fn layout_document( snapshot: None, }; }; + let pages = match resolve_toc_page_numbers(model, &block_page_numbers(&first_pages)) { + Some(resolved) => build_positioned_pages( + &resolved, + source_dir, + &plan.breaks, + content_width_mm, + content_height_mm, + metrics, + font_cache, + cjk_family, + mono_family, + sans_family, + math_metrics, + math_layout, + paragraph_cache, + ) + .unwrap_or(first_pages), + None => first_pages, + }; let snapshot = (!model.show_title).then(|| { PageLayoutCache::snapshot( plan.config.clone(), @@ -1963,6 +1983,44 @@ fn append_page_footnotes( } } +fn block_page_numbers(pages: &[PositionedPage]) -> HashMap { + let mut starts = HashMap::new(); + for (page_index, page) in pages.iter().enumerate() { + for item in &page.items { + if let PositionedPageItem::Line(line) = item + && line.anchor.block != usize::MAX + { + starts.entry(line.anchor.block).or_insert(page_index); + } + } + } + starts +} + +fn resolve_toc_page_numbers( + model: &DocumentModel, + starts: &HashMap, +) -> Option { + let mut resolved = model.clone(); + let mut changed = false; + for block in &mut resolved.blocks { + let Block::Paragraph(runs) = block else { + continue; + }; + for run in runs { + if let Some(UnresolvedReference::TocPage(target)) = run.unresolved_reference { + run.text = starts + .get(&target) + .map(|page| (page + 1).to_string()) + .unwrap_or_else(|| "??".to_string()); + run.unresolved_reference = None; + changed = true; + } + } + } + changed.then_some(resolved) +} + pub(super) fn build_positioned_pages( model: &DocumentModel, source_dir: &Path, diff --git a/src/rust_typeset/texlang_adapter.rs b/src/rust_typeset/texlang_adapter.rs index 35a6f3e..418c6d5 100644 --- a/src/rust_typeset/texlang_adapter.rs +++ b/src/rust_typeset/texlang_adapter.rs @@ -1710,6 +1710,30 @@ fn page_style_primitive( Ok(()) } +fn table_of_contents_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + write_event(input, token, FrontendEventKind::TableOfContents); + Ok(()) +} + +fn list_of_figures_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + write_event(input, token, FrontendEventKind::ListOfFigures); + Ok(()) +} + +fn list_of_tables_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + write_event(input, token, FrontendEventKind::ListOfTables); + Ok(()) +} + fn this_page_style_primitive( token: token::Token, input: &mut vm::ExecutionInput, @@ -6749,6 +6773,18 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltInContents"), "missing contents heading"); + assert!(svg.contains(">Alpha"), "missing first entry"); + assert!(svg.contains(">Beta"), "missing second entry"); + assert!(svg.contains(">1"), "missing first page number"); + assert!(svg.contains(">2"), "missing second page number"); +} + +#[test] +fn list_of_tables_lists_captions_and_pages() { + let source = r"\documentclass{article} +\begin{document} +\listoftables +\begin{table}[h] +\caption{First table} +\begin{tabular}{ll} +A & B \\ +\end{tabular} +\end{table} +\end{document}"; + let value = fresh_preview(source, "lot.tex"); + assert_eq!(value["status"], "ok", "{value}"); + let svg = page_svg(&value, 0); + assert!(svg.contains(">List"), "missing list heading"); + assert!(svg.contains(">of"), "missing tables heading word"); + assert!(svg.contains(">ables"), "missing tables word"); + assert!(svg.contains(">First"), "missing caption entry"); + assert!(svg.contains(">1"), "missing page number"); +} + +#[test] +fn list_of_figures_lists_captions_and_pages() { + let source = r"\documentclass{article} +\begin{document} +\listoffigures +\begin{figure}[h] +\includegraphics[width=20mm]{examples/plot.png} +\caption{First figure} +\end{figure} +\end{document}"; + let value = fresh_preview(source, "lof.tex"); + assert_eq!(value["status"], "ok", "{value}"); + let svg = page_svg(&value, 0); + assert!(svg.contains(">List"), "missing list heading"); + assert!(svg.contains(">of"), "missing figures heading word"); + assert!(svg.contains(">First"), "missing caption entry"); +}