Add abstract quotations, unnumbered paragraphs, and author-year citations

This commit is contained in:
gloamxun committed 2026-10-19 15:39:02 +08:00
1 parent 3406f84e86
commit 7f1f202de1
11 files changed
+366 -60

No files matched your search

+8 -5
View File
@@ -125,8 +125,8 @@ numbered and starred heading levels, paragraph indentation (`\parindent`),
`\hfill`, serif/sans/monospaced text, true small caps, itemize/enumerate lists, `\hfill`, serif/sans/monospaced text, true small caps, itemize/enumerate lists,
page page
breaks, basic display and inline math, figures, simple tables, breaks, basic display and inline math, figures, simple tables,
section/figure/table references, and numeric citations from a manual bibliography section/figure/table references, numeric citations from a manual bibliography or a
or a local `.bib` file. A4 pages use 25 mm margins unless local `.bib` file, and natbib-style author-year citations for the arXiv template. A4 pages use 25 mm margins unless
`geometry` sets them. Liberation Serif is embedded in the PDF for Latin and math `geometry` sets them. Liberation Serif is embedded in the PDF for Latin and math
glyphs; CJK text uses an installed fallback font. glyphs; CJK text uses an installed fallback font.
@@ -150,6 +150,8 @@ parameterization commands:
`\newgeometry`. `\newgeometry`.
- Package files are read with `@` as a letter, so `\@title`-style internals - Package files are read with `@` as a letter, so `\@title`-style internals
tokenize correctly. tokenize correctly.
- The `abstract` environment indents its body as a quotation, and `\paragraph`
produces an unnumbered bold run-in heading.
`\documentclass[options]{class}` parses class options, accepts the built-in `\documentclass[options]{class}` parses class options, accepts the built-in
`article`, `report`, `book`, `letter`, `minimal`, and `standalone` classes, and `article`, `report`, `book`, `letter`, `minimal`, and `standalone` classes, and
@@ -374,9 +376,10 @@ reads a local `.bib` file (the `.bib` extension is optional) and formats common
author/editor, title, journal, booktitle, volume, number, pages, publisher, author/editor, title, journal, booktitle, volume, number, pages, publisher,
institution, school, organization, edition, address, month, note, and year fields. institution, school, organization, edition, address, month, note, and year fields.
BibTeX `@string` macros and single-level `crossref` inheritance are supported. BibTeX `@string` macros and single-level `crossref` inheritance are supported.
Manual `thebibliography` entries also work. Custom `.bst` sorting and formatting, Manual `thebibliography` entries also work. Documents loading `natbib` or
author-year citation styles and page-number references (`\pageref`) are not `arxiv.sty` render `\citet`/`\citep` as author-year citations and omit numeric
implemented. bibliography labels; other documents keep numeric citations. Custom `.bst`
sorting/formatting and page-number references (`\pageref`) are not implemented.
A paragraph starts with the current `\parindent` (17pt by default); the A paragraph starts with the current `\parindent` (17pt by default); the
indent is recorded per paragraph and follows group scoping, `\setlength`, indent is recorded per paragraph and follows group scoping, `\setlength`,
+14
View File
@@ -65,6 +65,12 @@ pub enum TitleStyle {
Preprint, Preprint,
} }
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CitationMetadata {
pub author: String,
pub year: String,
}
#[derive(Clone)] #[derive(Clone)]
pub struct Footnote { pub struct Footnote {
pub number: u32, pub number: u32,
@@ -90,6 +96,8 @@ pub struct DocumentModel {
pub block_sources: Vec<Option<SourceLocation>>, pub block_sources: Vec<Option<SourceLocation>>,
pub labels: HashMap<String, String>, pub labels: HashMap<String, String>,
pub citations: HashMap<String, usize>, pub citations: HashMap<String, usize>,
pub citation_metadata: HashMap<String, CitationMetadata>,
pub author_year_citations: bool,
pub footnotes: Vec<Footnote>, pub footnotes: Vec<Footnote>,
pub page_style: PageStyle, pub page_style: PageStyle,
pub page_style_overrides: Vec<PageStyleOverride>, pub page_style_overrides: Vec<PageStyleOverride>,
@@ -113,6 +121,8 @@ impl Default for DocumentModel {
block_sources: Vec::new(), block_sources: Vec::new(),
labels: HashMap::new(), labels: HashMap::new(),
citations: HashMap::new(), citations: HashMap::new(),
citation_metadata: HashMap::new(),
author_year_citations: false,
footnotes: Vec::new(), footnotes: Vec::new(),
page_style: PageStyle::default(), page_style: PageStyle::default(),
page_style_overrides: Vec::new(), page_style_overrides: Vec::new(),
@@ -292,6 +302,9 @@ pub struct ListItem {
pub enum UnresolvedReference { pub enum UnresolvedReference {
Label(String), Label(String),
Citation(Vec<String>), Citation(Vec<String>),
/// A textual citation such as natbib's `\citet`, rendered as
/// `Author (year)` instead of a parenthetical citation.
TextualCitation(Vec<String>),
/// A table-of-contents/list page number for the block with this index. /// A table-of-contents/list page number for the block with this index.
/// The target is resolved to a page number during page layout. /// The target is resolved to a page number during page layout.
TocPage(usize), TocPage(usize),
@@ -341,6 +354,7 @@ pub enum ParagraphAlignment {
RaggedRight, RaggedRight,
RaggedLeft, RaggedLeft,
Centered, Centered,
Quote,
} }
#[derive(Clone, PartialEq, Eq, Hash)] #[derive(Clone, PartialEq, Eq, Hash)]
+32 -4
View File
@@ -501,6 +501,7 @@ struct Parser {
suppress_indent: bool, suppress_indent: bool,
paragraph_alignment: ParagraphAlignment, paragraph_alignment: ParagraphAlignment,
alignment_saves: Vec<ParagraphAlignment>, alignment_saves: Vec<ParagraphAlignment>,
in_abstract: bool,
} }
impl Parser { impl Parser {
@@ -551,6 +552,7 @@ impl Parser {
suppress_indent: false, suppress_indent: false,
paragraph_alignment: ParagraphAlignment::Justified, paragraph_alignment: ParagraphAlignment::Justified,
alignment_saves: Vec::new(), alignment_saves: Vec::new(),
in_abstract: false,
} }
} }
@@ -945,6 +947,7 @@ impl Parser {
expanded::FrontendEventKind::PackageLoaded(package) => { expanded::FrontendEventKind::PackageLoaded(package) => {
if package == "arxiv" { if package == "arxiv" {
self.document.title_style = TitleStyle::Preprint; self.document.title_style = TitleStyle::Preprint;
self.document.author_year_citations = true;
if self.document.undertitle.is_none() { if self.document.undertitle.is_none() {
self.document.undertitle = Some("A Preprint".to_string()); self.document.undertitle = Some("A Preprint".to_string());
} }
@@ -1263,13 +1266,29 @@ impl Parser {
self.append_reference(UnresolvedReference::Label(key.clone())) self.append_reference(UnresolvedReference::Label(key.clone()))
} }
expanded::FrontendEventKind::Citation(keys) => { expanded::FrontendEventKind::Citation(keys) => {
self.append_reference(UnresolvedReference::Citation( let (keys, textual) = match keys.strip_prefix("@text:") {
keys.split(',').map(str::trim).map(str::to_string).collect(), Some(keys) => (keys, true),
)) None => (keys.as_str(), false),
};
let keys = keys.split(',').map(str::trim).map(str::to_string).collect();
self.append_reference(if textual {
UnresolvedReference::TextualCitation(keys)
} else {
UnresolvedReference::Citation(keys)
})
} }
expanded::FrontendEventKind::BibliographyItem(key) => { expanded::FrontendEventKind::BibliographyItem(key) => {
self.start_bibliography_item(key.clone()) self.start_bibliography_item(key.clone())
} }
expanded::FrontendEventKind::BibliographyMetadata { key, author, year } => {
self.document.citation_metadata.insert(
key.clone(),
crate::document::CitationMetadata {
author: author.clone(),
year: year.clone(),
},
);
}
expanded::FrontendEventKind::IncludeGraphics { options, path } => { expanded::FrontendEventKind::IncludeGraphics { options, path } => {
self.add_image(path.clone(), options.clone()) self.add_image(path.clone(), options.clone())
} }
@@ -1864,6 +1883,11 @@ impl Parser {
&& let Some(first) = runs.first_mut() && let Some(first) = runs.first_mut()
{ {
first.alignment = Some(self.paragraph_alignment); first.alignment = Some(self.paragraph_alignment);
} else if self.in_abstract
&& runs.first().is_some_and(|run| run.alignment.is_none())
&& let Some(first) = runs.first_mut()
{
first.alignment = Some(ParagraphAlignment::Quote);
} }
prepend_paragraph_indent(&mut runs, indent); prepend_paragraph_indent(&mut runs, indent);
let source = self.paragraph_source.take(); let source = self.paragraph_source.take();
@@ -1962,8 +1986,12 @@ impl Parser {
self.push_block(Block::Centered { self.push_block(Block::Centered {
runs: vec![heading], runs: vec![heading],
}); });
self.in_abstract = true;
}
(false, "abstract") => {
self.flush_paragraph();
self.in_abstract = false;
} }
(false, "abstract") => self.flush_paragraph(),
(true, "raggedright") => { (true, "raggedright") => {
self.flush_paragraph(); self.flush_paragraph();
self.alignment_saves.push(self.paragraph_alignment); self.alignment_saves.push(self.paragraph_alignment);
+5
View File
@@ -237,6 +237,11 @@ pub enum FrontendEventKind {
Reference(String), Reference(String),
Citation(String), Citation(String),
BibliographyItem(String), BibliographyItem(String),
BibliographyMetadata {
key: String,
author: String,
year: String,
},
PageStyle(crate::document::PageStyleKind), PageStyle(crate::document::PageStyleKind),
ThisPageStyle(crate::document::PageStyleKind), ThisPageStyle(crate::document::PageStyleKind),
PageDecorationStart { PageDecorationStart {
+74 -21
View File
@@ -1,14 +1,38 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::document::{Block, DocumentModel, ListBlock, ParsedDocument, Run, UnresolvedReference}; use crate::document::{
Block, CitationMetadata, DocumentModel, ListBlock, ParsedDocument, Run, UnresolvedReference,
};
/// Resolves document references after parsing has collected all labels and citations. /// Resolves document references after parsing has collected all labels and citations.
pub fn resolve(parsed: ParsedDocument) -> DocumentModel { pub fn resolve(parsed: ParsedDocument) -> DocumentModel {
let mut document = parsed.0; let mut document = parsed.0;
fn citation_label(
key: &str,
citations: &HashMap<String, usize>,
metadata: &HashMap<String, CitationMetadata>,
author_year: bool,
) -> String {
if author_year && let Some(entry) = metadata.get(key) {
match (entry.author.is_empty(), entry.year.is_empty()) {
(false, false) => return format!("{}, {}", entry.author, entry.year),
(false, true) => return entry.author.clone(),
(true, false) => return entry.year.clone(),
(true, true) => {}
}
}
citations
.get(key)
.map(usize::to_string)
.unwrap_or_else(|| key.to_string())
}
fn resolve_runs( fn resolve_runs(
runs: &mut [Run], runs: &mut [Run],
labels: &HashMap<String, String>, labels: &HashMap<String, String>,
citations: &HashMap<String, usize>, citations: &HashMap<String, usize>,
metadata: &HashMap<String, CitationMetadata>,
author_year: bool,
) { ) {
for run in runs { for run in runs {
let Some(reference) = run.unresolved_reference.take() else { let Some(reference) = run.unresolved_reference.take() else {
@@ -24,17 +48,42 @@ pub fn resolve(parsed: ParsedDocument) -> DocumentModel {
.cloned() .cloned()
.unwrap_or_else(|| "??".to_string()), .unwrap_or_else(|| "??".to_string()),
UnresolvedReference::Citation(keys) => { UnresolvedReference::Citation(keys) => {
let formatted = keys if author_year {
.iter() let formatted = keys
.map(|key| { .iter()
citations .map(|key| citation_label(key, citations, metadata, true))
.get(key) .collect::<Vec<_>>()
.map(usize::to_string) .join("; ");
.unwrap_or_else(|| key.clone()) format!("({formatted})")
}) } else {
.collect::<Vec<_>>() let formatted = keys
.join(", "); .iter()
format!("[{formatted}]") .map(|key| citation_label(key, citations, metadata, false))
.collect::<Vec<_>>()
.join(", ");
format!("[{formatted}]")
}
}
UnresolvedReference::TextualCitation(keys) => {
if author_year {
keys.iter()
.map(|key| {
let label = citation_label(key, citations, metadata, true);
match label.rsplit_once(", ") {
Some((author, year)) => format!("{author} ({year})"),
None => label,
}
})
.collect::<Vec<_>>()
.join("; ")
} else {
let formatted = keys
.iter()
.map(|key| citation_label(key, citations, metadata, false))
.collect::<Vec<_>>()
.join(", ");
format!("[{formatted}]")
}
} }
}; };
run.text = text; run.text = text;
@@ -45,42 +94,46 @@ pub fn resolve(parsed: ParsedDocument) -> DocumentModel {
list: &mut ListBlock, list: &mut ListBlock,
labels: &HashMap<String, String>, labels: &HashMap<String, String>,
citations: &HashMap<String, usize>, citations: &HashMap<String, usize>,
metadata: &HashMap<String, CitationMetadata>,
author_year: bool,
) { ) {
for item in &mut list.items { for item in &mut list.items {
resolve_runs(&mut item.runs, labels, citations); resolve_runs(&mut item.runs, labels, citations, metadata, author_year);
for nested in &mut item.nested { for nested in &mut item.nested {
resolve_list(nested, labels, citations); resolve_list(nested, labels, citations, metadata, author_year);
} }
} }
} }
let labels = &document.labels; let labels = &document.labels;
let citations = &document.citations; let citations = &document.citations;
let metadata = &document.citation_metadata;
let author_year = document.author_year_citations;
for block in &mut document.blocks { for block in &mut document.blocks {
match block { match block {
Block::Paragraph(runs) | Block::Heading { runs, .. } => { Block::Paragraph(runs) | Block::Heading { runs, .. } => {
resolve_runs(runs, labels, citations) resolve_runs(runs, labels, citations, metadata, author_year)
} }
Block::List(list) => resolve_list(list, labels, citations), Block::List(list) => resolve_list(list, labels, citations, metadata, author_year),
Block::Table { rows, caption, .. } => { Block::Table { rows, caption, .. } => {
for cell in rows.iter_mut().flatten() { for cell in rows.iter_mut().flatten() {
resolve_runs(cell, labels, citations); resolve_runs(cell, labels, citations, metadata, author_year);
} }
if let Some(caption) = caption { if let Some(caption) = caption {
resolve_runs(caption, labels, citations); resolve_runs(caption, labels, citations, metadata, author_year);
} }
} }
Block::Image { caption, .. } => { Block::Image { caption, .. } => {
if let Some(caption) = caption { if let Some(caption) = caption {
resolve_runs(caption, labels, citations); resolve_runs(caption, labels, citations, metadata, author_year);
} }
} }
Block::FramedBox { runs, .. } | Block::Centered { runs } => { Block::FramedBox { runs, .. } | Block::Centered { runs } => {
resolve_runs(runs, labels, citations) resolve_runs(runs, labels, citations, metadata, author_year)
} }
Block::Bibliography(items) => { Block::Bibliography(items) => {
for (_, runs) in items { for (_, runs) in items {
resolve_runs(runs, labels, citations); resolve_runs(runs, labels, citations, metadata, author_year);
} }
} }
Block::HorizontalRule { .. } Block::HorizontalRule { .. }
+2
View File
@@ -13,6 +13,8 @@ contents and figure/table lists with dotted leaders; native PDF rectangles; unif
`\centering`/`\raggedright`/`\raggedleft` declarations and environments; `\centering`/`\raggedright`/`\raggedleft` declarations and environments;
chapter headings with chapter-prefixed section numbering and page breaks; chapter headings with chapter-prefixed section numbering and page breaks;
deferred top-float queue for figures; document-level custom `\maketitle`; deferred top-float queue for figures; document-level custom `\maketitle`;
abstract quotation formatting, unnumbered `\paragraph` headings, natbib-style
author-year citations;
`\vbox`/`\vtop` vertical-material capture with inline splicing `\vbox`/`\vtop` vertical-material capture with inline splicing
(`build_positioned_pages` is the only page builder and no separate break (`build_positioned_pages` is the only page builder and no separate break
planner remains). planner remains).
+6 -2
View File
@@ -46,6 +46,8 @@ the source changes; the SVG preview is refreshed per page.
- Chapters: `\chapter` is a level-0 heading; chapter numbers prefix section - Chapters: `\chapter` is a level-0 heading; chapter numbers prefix section
numbers (`1.1`, `1.1.1`) and reset lower counters. Chapters after the first numbers (`1.1`, `1.1.1`) and reset lower counters. Chapters after the first
block start on a new page. block start on a new page.
- Abstract: the `abstract` environment is a 20mm inset quotation with a bold
heading, matching the class styles used by the arXiv template.
- Class sizes: 10pt/11pt/12pt set the body size (article defaults to 10pt) - Class sizes: 10pt/11pt/12pt set the body size (article defaults to 10pt)
and propagate through and propagate through
headings, title material, lists, tables, block boxes, footnotes, and the headings, title material, lists, tables, block boxes, footnotes, and the
@@ -62,7 +64,9 @@ the source changes; the SVG preview is refreshed per page.
`\DeclareOption`/`\ProcessOptions`/`\ExecuteOptions`/option passing. `\DeclareOption`/`\ProcessOptions`/`\ExecuteOptions`/option passing.
- Compatibility: spacing macros (quad/qquad/thin/en/med/thick, `\vspace*`, - Compatibility: spacing macros (quad/qquad/thin/en/med/thick, `\vspace*`,
`\hspace*`, skips), text symbols/letters/punctuation, break advisories, `\hspace*`, skips), text symbols/letters/punctuation, break advisories,
metadata, citations/references, tables/lists/images. metadata, `\paragraph` run-in headings, citations/references, tables/lists/images.
- Citations: numeric citations by default; `natbib`/`arxiv.sty` selects author-year
`\citet`/`\citep` from `.bib` metadata and drops numeric bibliography labels.
- Live preview: paragraph cache, page-hash diffing, warm rebuilds in the low - Live preview: paragraph cache, page-hash diffing, warm rebuilds in the low
milliseconds for small edits. milliseconds for small edits.
@@ -91,7 +95,7 @@ See `docs/ROADMAP.md` for concrete implementation plans.
- `examples/hello.tex`, `examples/boxes.tex`, `examples/compat.tex` compile to - `examples/hello.tex`, `examples/boxes.tex`, `examples/compat.tex` compile to
one A4 page each; the arXiv template project compiles to 3 Letter pages. one A4 page each; the arXiv template project compiles to 3 Letter pages.
- `cargo fmt --check` passes; `cargo test --offline` (42 tests: 38 compiler - `cargo fmt --check` passes; `cargo test --offline` (45 tests: 41 compiler
integration tests + 4 server tests) covers the three examples, the arXiv integration tests + 4 server tests) covers the three examples, the arXiv
fixture, figure/table floats (top and bottom), newpage, page styles and `\thispagestyle`, SVG/PDF output, fixture, figure/table floats (top and bottom), newpage, page styles and `\thispagestyle`, SVG/PDF output,
project API, static frontend assets, path traversal, the legacy project API, static frontend assets, path traversal, the legacy
+3 -3
View File
@@ -70,7 +70,7 @@ const PRELUDE: &str = r#"
\def\tag{\texrratag} \def\tag{\texrratag}
\def\cite#1{\texrracite{#1}} \def\cite#1{\texrracite{#1}}
\def\citep#1{\texrracite{#1}} \def\citep#1{\texrracite{#1}}
\def\citet#1{\texrracite{#1}} \def\citet#1{\texrratextualcite{#1}}
\def\nocite#1{} \def\nocite#1{}
\def\newblock{ } \def\newblock{ }
\def\caption#1{\texrracaptionstart#1\texrracaptionend} \def\caption#1{\texrracaptionstart#1\texrracaptionend}
@@ -453,8 +453,8 @@ const PRELUDE: &str = r#"
\def\And{\texrraauthorseparator} \def\And{\texrraauthorseparator}
\def\AND{\texrraauthorseparator} \def\AND{\texrraauthorseparator}
\def\ifhmode{\iftrue} \def\ifhmode{\iftrue}
\def\paragraph#1{\par\texrraheadingstart{3}#1\texrraheadingend\par} \def\paragraph#1{\par\texrraunnumberedheadingstart{3}#1\texrraheadingend\par}
\def\subparagraph#1{\par\texrraheadingstart{3}#1\texrraheadingend\par} \def\subparagraph#1{\par\texrraunnumberedheadingstart{3}#1\texrraheadingend\par}
\def\@startsection#1#2#3#4#5#6#7{\par\texrraheadingstart{#2}#7\texrraheadingend\par} \def\@startsection#1#2#3#4#5#6#7{\par\texrraheadingstart{#2}#7\texrraheadingend\par}
\def\setlength#1#2{#1=#2\relax} \def\setlength#1#2{#1=#2\relax}
\def\addtolength#1#2{\advance#1#2\relax} \def\addtolength#1#2{\advance#1#2\relax}
+44 -24
View File
@@ -1787,10 +1787,17 @@ pub(super) fn build_positioned_pages(
run.bold = true; run.bold = true;
} }
} }
let paragraph_alignment = runs.iter().find_map(|run| run.alignment);
let quote = paragraph_alignment == Some(ParagraphAlignment::Quote);
let paragraph_width_mm = if quote {
(content_width_mm - 20.0).max(20.0)
} else {
content_width_mm
};
let lines = measure_positioned_lines( let lines = measure_positioned_lines(
&styled_runs, &styled_runs,
font_size, font_size,
content_width_mm, paragraph_width_mm,
metrics, metrics,
font_cache, font_cache,
cjk_family, cjk_family,
@@ -1832,28 +1839,36 @@ pub(super) fn build_positioned_pages(
max_depth, max_depth,
); );
let paragraph_alignment = runs.iter().find_map(|run| run.alignment); let ragged = matches!(
let ragged = paragraph_alignment.is_some(); paragraph_alignment,
Some(
ParagraphAlignment::RaggedRight
| ParagraphAlignment::RaggedLeft
| ParagraphAlignment::Centered
)
);
let quote_inset = if quote { 10.0 } else { 0.0 };
let centered = paragraph_alignment == Some(ParagraphAlignment::Centered); let centered = paragraph_alignment == Some(ParagraphAlignment::Centered);
let x = match (paragraph_alignment, &line.content) { let x = millimeters_to_scaled(quote_inset)
( + match (paragraph_alignment, &line.content) {
Some(ParagraphAlignment::RaggedLeft), (
PositionedLineContent::Text { line, font_size }, Some(ParagraphAlignment::RaggedLeft),
) => { PositionedLineContent::Text { line, font_size },
let text_line = text_layout::TextLine::new( ) => {
line, let text_line = text_layout::TextLine::new(
cjk_family, line,
mono_family, cjk_family,
sans_family, mono_family,
*font_size, sans_family,
); *font_size,
millimeters_to_scaled( );
(content_width_mm - text_line.natural_width_mm(font_cache)) millimeters_to_scaled(
.max(0.0), (paragraph_width_mm - text_line.natural_width_mm(font_cache))
) .max(0.0),
} )
_ => 0, }
}; _ => 0,
};
pages pages
.last_mut() .last_mut()
.expect("the page list starts with one page") .expect("the page list starts with one page")
@@ -2661,8 +2676,13 @@ pub(super) fn build_positioned_pages(
cursor = cursor.saturating_add((normal_line_height as f64 * 0.25).round() as i64); cursor = cursor.saturating_add((normal_line_height as f64 * 0.25).round() as i64);
let entry_gap = (normal_line_height as f64 * 0.2).round() as i64; let entry_gap = (normal_line_height as f64 * 0.2).round() as i64;
for (index, (_key, runs)) in items.iter().enumerate() { for (index, (_key, runs)) in items.iter().enumerate() {
let mut numbered = vec![Run::plain(format!("[{}] ", index + 1))]; let numbered = if model.author_year_citations {
numbered.extend(runs.clone()); runs.clone()
} else {
let mut numbered = vec![Run::plain(format!("[{}] ", index + 1))];
numbered.extend(runs.clone());
numbered
};
for line in measure_positioned_lines( for line in measure_positioned_lines(
&numbered, &numbered,
10, 10,
+128 -1
View File
@@ -5973,6 +5973,31 @@ fn heading_start_primitive(
Ok(()) Ok(())
} }
fn unnumbered_heading_start_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
let value = read_scanned_token_list(input)?
.into_iter()
.filter_map(|token| token.char())
.collect::<String>();
let level = value.trim().parse::<u8>().map_err(|_| {
input.fatal_error(error::SimpleTokenError::new(
token,
format!("heading level must be an integer, found `{value}`"),
))
})?;
write_event(
input,
token,
FrontendEventKind::HeadingStart {
level,
numbered: false,
},
);
Ok(())
}
fn chapter_primitive( fn chapter_primitive(
token: token::Token, token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>, input: &mut vm::ExecutionInput<CompilerState>,
@@ -6075,6 +6100,90 @@ fn citation_primitive(
argument_event_primitive(token, input, FrontendEventKind::Citation) argument_event_primitive(token, input, FrontendEventKind::Citation)
} }
fn textual_citation_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
let keys = read_scanned_token_list(input)?
.into_iter()
.filter_map(|token| token.char())
.collect::<String>();
write_event(
input,
token,
FrontendEventKind::Citation(format!("@text:{}", keys.trim())),
);
Ok(())
}
fn bibliography_metadata_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
let key = read_unexpanded_argument(input, token, "expects a bibliography key")?
.into_iter()
.filter_map(|token| token.char())
.collect::<String>();
let author = read_unexpanded_argument(input, token, "expects an author")?
.into_iter()
.filter_map(|token| token.char())
.collect::<String>();
let year = read_unexpanded_argument(input, token, "expects a year")?
.into_iter()
.filter_map(|token| token.char())
.collect::<String>();
write_event(
input,
token,
FrontendEventKind::BibliographyMetadata {
key: key.trim().trim_matches(['{', '}']).to_string(),
author: author.trim().trim_matches(['{', '}']).to_string(),
year: year.trim().trim_matches(['{', '}']).to_string(),
},
);
Ok(())
}
fn bib_metadata_author(fields: &std::collections::HashMap<String, String>) -> String {
let raw = fields
.get("author")
.or_else(|| fields.get("editor"))
.map(String::as_str)
.unwrap_or("");
let raw = raw.replace(['{', '}'], "");
let surname = |author: &str| {
author
.split_once(',')
.map(|(last, _)| last.trim().to_string())
.unwrap_or_else(|| {
author
.split_whitespace()
.last()
.unwrap_or(author)
.to_string()
})
};
let authors: Vec<String> = raw
.split(" and ")
.map(str::trim)
.filter(|author| !author.is_empty())
.map(surname)
.collect();
match authors.as_slice() {
[] => String::new(),
[one] => one.clone(),
[one, two] => format!("{one} and {two}"),
[one, ..] => format!("{one} et al."),
}
}
fn bib_metadata_year(fields: &std::collections::HashMap<String, String>) -> String {
fields
.get("year")
.map(|year| year.replace(['{', '}'], ""))
.unwrap_or_default()
}
fn bibliography_item_primitive( fn bibliography_item_primitive(
token: token::Token, token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>, input: &mut vm::ExecutionInput<CompilerState>,
@@ -6108,7 +6217,13 @@ fn bibliography_primitive(
let mut source = String::from("\\begin{thebibliography}{9}"); let mut source = String::from("\\begin{thebibliography}{9}");
for entry in entries { for entry in entries {
source.push_str("\\bibitem{"); source.push_str("\\texrrabibmeta{");
source.push_str(&entry.key);
source.push_str("}{");
source.push_str(&bib_metadata_author(&entry.fields));
source.push_str("}{");
source.push_str(&bib_metadata_year(&entry.fields));
source.push_str("}\\bibitem{");
source.push_str(&entry.key); source.push_str(&entry.key);
source.push('}'); source.push('}');
source.push_str(&entry.to_latex()); source.push_str(&entry.to_latex());
@@ -7409,6 +7524,10 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn<Compil
"texrraheadingstart", "texrraheadingstart",
texlang::command::BuiltIn::new_execution(heading_start_primitive), texlang::command::BuiltIn::new_execution(heading_start_primitive),
); );
built_ins.insert(
"texrraunnumberedheadingstart",
texlang::command::BuiltIn::new_execution(unnumbered_heading_start_primitive),
);
built_ins.insert( built_ins.insert(
"texrraheadingend", "texrraheadingend",
texlang::command::BuiltIn::new_execution(heading_end_primitive), texlang::command::BuiltIn::new_execution(heading_end_primitive),
@@ -7429,6 +7548,14 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn<Compil
"texrracite", "texrracite",
texlang::command::BuiltIn::new_execution(citation_primitive), texlang::command::BuiltIn::new_execution(citation_primitive),
); );
built_ins.insert(
"texrratextualcite",
texlang::command::BuiltIn::new_execution(textual_citation_primitive),
);
built_ins.insert(
"texrrabibmeta",
texlang::command::BuiltIn::new_execution(bibliography_metadata_primitive),
);
built_ins.insert( built_ins.insert(
"bibitem", "bibitem",
texlang::command::BuiltIn::new_execution(bibliography_item_primitive), texlang::command::BuiltIn::new_execution(bibliography_item_primitive),
+50
View File
@@ -1173,3 +1173,53 @@ Second page.
"header was expanded too early: {second}" "header was expanded too early: {second}"
); );
} }
#[test]
fn abstract_body_is_indented_like_a_quote() {
let source = r#"\documentclass{article}
\begin{document}
\begin{abstract}
Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu.
\end{abstract}
Body text after the abstract.
\end{document}
"#;
let value = fresh_preview(source, "abstract-quote.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let abstract_x = text_x(&svg, "Alpha");
let body_x = text_x(&svg, "Body");
assert!(
abstract_x > 9.0,
"abstract body was not inset: x={abstract_x}"
);
assert!(
body_x + 3.0 < abstract_x,
"abstract inset did not differ from body: abstract={abstract_x}, body={body_x}"
);
}
#[test]
fn natbib_citations_use_author_year() {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("fixtures")
.join("arxiv-template")
.join("template.tex");
let source = std::fs::read_to_string(&path).expect("read arXiv fixture");
let value = fresh_preview(&source, &path.to_string_lossy());
assert_eq!(value["status"], "ok", "{}", value["message"]);
let second = page_svg(&value, 1);
assert!(
second.contains(">Kour</text>") && second.contains(">Saabne,</text>"),
"author-year citation missing: {second}"
);
assert!(
!second.contains(">[1, 3]</text>"),
"numeric citation was not replaced: {second}"
);
let third = page_svg(&value, 2);
assert!(
third.contains(">Kour</text>"),
"bibliography entry missing: {third}"
);
}