Add abstract quotations, unnumbered paragraphs, and author-year citations
This commit is contained in:
1 parent
3406f84e86
commit
7f1f202de1
11 files changed
+366
-60
No files matched your search
@@ -125,8 +125,8 @@ numbered and starred heading levels, paragraph indentation (`\parindent`),
|
||||
`\hfill`, serif/sans/monospaced text, true small caps, 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
|
||||
section/figure/table references, numeric citations from a manual bibliography or a
|
||||
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
|
||||
glyphs; CJK text uses an installed fallback font.
|
||||
|
||||
@@ -150,6 +150,8 @@ parameterization commands:
|
||||
`\newgeometry`.
|
||||
- Package files are read with `@` as a letter, so `\@title`-style internals
|
||||
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
|
||||
`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,
|
||||
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 and page-number references (`\pageref`) are not
|
||||
implemented.
|
||||
Manual `thebibliography` entries also work. Documents loading `natbib` or
|
||||
`arxiv.sty` render `\citet`/`\citep` as author-year citations and omit numeric
|
||||
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
|
||||
indent is recorded per paragraph and follows group scoping, `\setlength`,
|
||||
|
||||
@@ -65,6 +65,12 @@ pub enum TitleStyle {
|
||||
Preprint,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct CitationMetadata {
|
||||
pub author: String,
|
||||
pub year: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Footnote {
|
||||
pub number: u32,
|
||||
@@ -90,6 +96,8 @@ pub struct DocumentModel {
|
||||
pub block_sources: Vec<Option<SourceLocation>>,
|
||||
pub labels: HashMap<String, String>,
|
||||
pub citations: HashMap<String, usize>,
|
||||
pub citation_metadata: HashMap<String, CitationMetadata>,
|
||||
pub author_year_citations: bool,
|
||||
pub footnotes: Vec<Footnote>,
|
||||
pub page_style: PageStyle,
|
||||
pub page_style_overrides: Vec<PageStyleOverride>,
|
||||
@@ -113,6 +121,8 @@ impl Default for DocumentModel {
|
||||
block_sources: Vec::new(),
|
||||
labels: HashMap::new(),
|
||||
citations: HashMap::new(),
|
||||
citation_metadata: HashMap::new(),
|
||||
author_year_citations: false,
|
||||
footnotes: Vec::new(),
|
||||
page_style: PageStyle::default(),
|
||||
page_style_overrides: Vec::new(),
|
||||
@@ -292,6 +302,9 @@ pub struct ListItem {
|
||||
pub enum UnresolvedReference {
|
||||
Label(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.
|
||||
/// The target is resolved to a page number during page layout.
|
||||
TocPage(usize),
|
||||
@@ -341,6 +354,7 @@ pub enum ParagraphAlignment {
|
||||
RaggedRight,
|
||||
RaggedLeft,
|
||||
Centered,
|
||||
Quote,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
|
||||
@@ -501,6 +501,7 @@ struct Parser {
|
||||
suppress_indent: bool,
|
||||
paragraph_alignment: ParagraphAlignment,
|
||||
alignment_saves: Vec<ParagraphAlignment>,
|
||||
in_abstract: bool,
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
@@ -551,6 +552,7 @@ impl Parser {
|
||||
suppress_indent: false,
|
||||
paragraph_alignment: ParagraphAlignment::Justified,
|
||||
alignment_saves: Vec::new(),
|
||||
in_abstract: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -945,6 +947,7 @@ impl Parser {
|
||||
expanded::FrontendEventKind::PackageLoaded(package) => {
|
||||
if package == "arxiv" {
|
||||
self.document.title_style = TitleStyle::Preprint;
|
||||
self.document.author_year_citations = true;
|
||||
if self.document.undertitle.is_none() {
|
||||
self.document.undertitle = Some("A Preprint".to_string());
|
||||
}
|
||||
@@ -1263,13 +1266,29 @@ impl Parser {
|
||||
self.append_reference(UnresolvedReference::Label(key.clone()))
|
||||
}
|
||||
expanded::FrontendEventKind::Citation(keys) => {
|
||||
self.append_reference(UnresolvedReference::Citation(
|
||||
keys.split(',').map(str::trim).map(str::to_string).collect(),
|
||||
))
|
||||
let (keys, textual) = match keys.strip_prefix("@text:") {
|
||||
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) => {
|
||||
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 } => {
|
||||
self.add_image(path.clone(), options.clone())
|
||||
}
|
||||
@@ -1864,6 +1883,11 @@ impl Parser {
|
||||
&& let Some(first) = runs.first_mut()
|
||||
{
|
||||
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);
|
||||
let source = self.paragraph_source.take();
|
||||
@@ -1962,8 +1986,12 @@ impl Parser {
|
||||
self.push_block(Block::Centered {
|
||||
runs: vec![heading],
|
||||
});
|
||||
self.in_abstract = true;
|
||||
}
|
||||
(false, "abstract") => {
|
||||
self.flush_paragraph();
|
||||
self.in_abstract = false;
|
||||
}
|
||||
(false, "abstract") => self.flush_paragraph(),
|
||||
(true, "raggedright") => {
|
||||
self.flush_paragraph();
|
||||
self.alignment_saves.push(self.paragraph_alignment);
|
||||
|
||||
@@ -237,6 +237,11 @@ pub enum FrontendEventKind {
|
||||
Reference(String),
|
||||
Citation(String),
|
||||
BibliographyItem(String),
|
||||
BibliographyMetadata {
|
||||
key: String,
|
||||
author: String,
|
||||
year: String,
|
||||
},
|
||||
PageStyle(crate::document::PageStyleKind),
|
||||
ThisPageStyle(crate::document::PageStyleKind),
|
||||
PageDecorationStart {
|
||||
|
||||
@@ -1,14 +1,38 @@
|
||||
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.
|
||||
pub fn resolve(parsed: ParsedDocument) -> DocumentModel {
|
||||
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(
|
||||
runs: &mut [Run],
|
||||
labels: &HashMap<String, String>,
|
||||
citations: &HashMap<String, usize>,
|
||||
metadata: &HashMap<String, CitationMetadata>,
|
||||
author_year: bool,
|
||||
) {
|
||||
for run in runs {
|
||||
let Some(reference) = run.unresolved_reference.take() else {
|
||||
@@ -24,17 +48,42 @@ pub fn resolve(parsed: ParsedDocument) -> DocumentModel {
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "??".to_string()),
|
||||
UnresolvedReference::Citation(keys) => {
|
||||
let formatted = keys
|
||||
.iter()
|
||||
.map(|key| {
|
||||
citations
|
||||
.get(key)
|
||||
.map(usize::to_string)
|
||||
.unwrap_or_else(|| key.clone())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
format!("[{formatted}]")
|
||||
if author_year {
|
||||
let formatted = keys
|
||||
.iter()
|
||||
.map(|key| citation_label(key, citations, metadata, true))
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ");
|
||||
format!("({formatted})")
|
||||
} else {
|
||||
let formatted = keys
|
||||
.iter()
|
||||
.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;
|
||||
@@ -45,42 +94,46 @@ pub fn resolve(parsed: ParsedDocument) -> DocumentModel {
|
||||
list: &mut ListBlock,
|
||||
labels: &HashMap<String, String>,
|
||||
citations: &HashMap<String, usize>,
|
||||
metadata: &HashMap<String, CitationMetadata>,
|
||||
author_year: bool,
|
||||
) {
|
||||
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 {
|
||||
resolve_list(nested, labels, citations);
|
||||
resolve_list(nested, labels, citations, metadata, author_year);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let labels = &document.labels;
|
||||
let citations = &document.citations;
|
||||
let metadata = &document.citation_metadata;
|
||||
let author_year = document.author_year_citations;
|
||||
for block in &mut document.blocks {
|
||||
match block {
|
||||
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, .. } => {
|
||||
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 {
|
||||
resolve_runs(caption, labels, citations);
|
||||
resolve_runs(caption, labels, citations, metadata, author_year);
|
||||
}
|
||||
}
|
||||
Block::Image { 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 } => {
|
||||
resolve_runs(runs, labels, citations)
|
||||
resolve_runs(runs, labels, citations, metadata, author_year)
|
||||
}
|
||||
Block::Bibliography(items) => {
|
||||
for (_, runs) in items {
|
||||
resolve_runs(runs, labels, citations);
|
||||
resolve_runs(runs, labels, citations, metadata, author_year);
|
||||
}
|
||||
}
|
||||
Block::HorizontalRule { .. }
|
||||
|
||||
@@ -13,6 +13,8 @@ contents and figure/table lists with dotted leaders; native PDF rectangles; unif
|
||||
`\centering`/`\raggedright`/`\raggedleft` declarations and environments;
|
||||
chapter headings with chapter-prefixed section numbering and page breaks;
|
||||
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
|
||||
(`build_positioned_pages` is the only page builder and no separate break
|
||||
planner remains).
|
||||
|
||||
+6
-2
@@ -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
|
||||
numbers (`1.1`, `1.1.1`) and reset lower counters. Chapters after the first
|
||||
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)
|
||||
and propagate through
|
||||
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.
|
||||
- Compatibility: spacing macros (quad/qquad/thin/en/med/thick, `\vspace*`,
|
||||
`\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
|
||||
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
|
||||
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
|
||||
fixture, figure/table floats (top and bottom), newpage, page styles and `\thispagestyle`, SVG/PDF output,
|
||||
project API, static frontend assets, path traversal, the legacy
|
||||
|
||||
@@ -70,7 +70,7 @@ const PRELUDE: &str = r#"
|
||||
\def\tag{\texrratag}
|
||||
\def\cite#1{\texrracite{#1}}
|
||||
\def\citep#1{\texrracite{#1}}
|
||||
\def\citet#1{\texrracite{#1}}
|
||||
\def\citet#1{\texrratextualcite{#1}}
|
||||
\def\nocite#1{}
|
||||
\def\newblock{ }
|
||||
\def\caption#1{\texrracaptionstart#1\texrracaptionend}
|
||||
@@ -453,8 +453,8 @@ const PRELUDE: &str = r#"
|
||||
\def\And{\texrraauthorseparator}
|
||||
\def\AND{\texrraauthorseparator}
|
||||
\def\ifhmode{\iftrue}
|
||||
\def\paragraph#1{\par\texrraheadingstart{3}#1\texrraheadingend\par}
|
||||
\def\subparagraph#1{\par\texrraheadingstart{3}#1\texrraheadingend\par}
|
||||
\def\paragraph#1{\par\texrraunnumberedheadingstart{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\setlength#1#2{#1=#2\relax}
|
||||
\def\addtolength#1#2{\advance#1#2\relax}
|
||||
|
||||
@@ -1787,10 +1787,17 @@ pub(super) fn build_positioned_pages(
|
||||
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(
|
||||
&styled_runs,
|
||||
font_size,
|
||||
content_width_mm,
|
||||
paragraph_width_mm,
|
||||
metrics,
|
||||
font_cache,
|
||||
cjk_family,
|
||||
@@ -1832,28 +1839,36 @@ 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 ragged = matches!(
|
||||
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 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,
|
||||
};
|
||||
let x = millimeters_to_scaled(quote_inset)
|
||||
+ 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(
|
||||
(paragraph_width_mm - text_line.natural_width_mm(font_cache))
|
||||
.max(0.0),
|
||||
)
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
pages
|
||||
.last_mut()
|
||||
.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);
|
||||
let entry_gap = (normal_line_height as f64 * 0.2).round() as i64;
|
||||
for (index, (_key, runs)) in items.iter().enumerate() {
|
||||
let mut numbered = vec![Run::plain(format!("[{}] ", index + 1))];
|
||||
numbered.extend(runs.clone());
|
||||
let numbered = if model.author_year_citations {
|
||||
runs.clone()
|
||||
} else {
|
||||
let mut numbered = vec![Run::plain(format!("[{}] ", index + 1))];
|
||||
numbered.extend(runs.clone());
|
||||
numbered
|
||||
};
|
||||
for line in measure_positioned_lines(
|
||||
&numbered,
|
||||
10,
|
||||
|
||||
@@ -5973,6 +5973,31 @@ fn heading_start_primitive(
|
||||
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(
|
||||
token: token::Token,
|
||||
input: &mut vm::ExecutionInput<CompilerState>,
|
||||
@@ -6075,6 +6100,90 @@ fn citation_primitive(
|
||||
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(
|
||||
token: token::Token,
|
||||
input: &mut vm::ExecutionInput<CompilerState>,
|
||||
@@ -6108,7 +6217,13 @@ fn bibliography_primitive(
|
||||
|
||||
let mut source = String::from("\\begin{thebibliography}{9}");
|
||||
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('}');
|
||||
source.push_str(&entry.to_latex());
|
||||
@@ -7409,6 +7524,10 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn<Compil
|
||||
"texrraheadingstart",
|
||||
texlang::command::BuiltIn::new_execution(heading_start_primitive),
|
||||
);
|
||||
built_ins.insert(
|
||||
"texrraunnumberedheadingstart",
|
||||
texlang::command::BuiltIn::new_execution(unnumbered_heading_start_primitive),
|
||||
);
|
||||
built_ins.insert(
|
||||
"texrraheadingend",
|
||||
texlang::command::BuiltIn::new_execution(heading_end_primitive),
|
||||
@@ -7429,6 +7548,14 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn<Compil
|
||||
"texrracite",
|
||||
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(
|
||||
"bibitem",
|
||||
texlang::command::BuiltIn::new_execution(bibliography_item_primitive),
|
||||
|
||||
@@ -1173,3 +1173,53 @@ Second page.
|
||||
"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}"
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user