Fix the arXiv-template PDF output
The user-supplied template PDF exposed four concrete problems:
- title/headings were letter-spaced: plain text in a large paragraph took the
SizedText segment path and was scaled twice; the fallback run now stays at
the base size and is scaled once by the paragraph;
- the table lost its third column because unsupported math glyphs were sent
through the PDF fallback font; table-cell math now has a readable ASCII
fallback (Size (um), approx. 100, 10**6);
- fancyhdr's \cfoot{\thepage} was painted together with route-D's default page
number; default numbering is skipped for a fancy pagestyle;
- .bib data was ignored; simple @article/@inproceedings entries are now parsed
from project .bib files, inlined as thebibliography entries, and resolved by
the existing citation pass, producing References and [1]-[3].
The regenerated 3-page PDF was checked for title/heading spacing, table text,
references and a single page number per page. A project regression test covers
the .bib path, and the table/heading fixes have unit tests.
Remaining visible limits in this template: the complex display equation, the
\fbox/rule figure body, vector/PDF images and the author block layout.
Test count moves to 1069 (444 core, 432 engine, 65 server).
This commit is contained in:
1 parent
fab26234fc
commit
b1e3e03f00
9 files changed
+457
-26
No files matched your search
@@ -4557,6 +4557,81 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
|
||||
/// Table cells currently paint plain text, not inline math. Convert common
|
||||
/// math commands to readable ASCII so a cell such as `Size ($\mu$m)` is not
|
||||
/// reduced to a single unsupported backslash glyph by the PDF font fallback.
|
||||
fn table_cell_plain_text(text: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut math = false;
|
||||
let mut chars = text.chars().peekable();
|
||||
while let Some(character) = chars.next() {
|
||||
if character == '$' {
|
||||
math = !math;
|
||||
continue;
|
||||
}
|
||||
if !math {
|
||||
out.push(character);
|
||||
continue;
|
||||
}
|
||||
if character == '\\' {
|
||||
let mut name = String::new();
|
||||
while let Some(&next) = chars.peek() {
|
||||
if next.is_ascii_alphabetic() {
|
||||
name.push(next);
|
||||
chars.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
match name.as_str() {
|
||||
"mu" => out.push_str("u"),
|
||||
"sim" => out.push_str("approx. "),
|
||||
"times" => out.push('x'),
|
||||
"pm" => out.push_str("+/-"),
|
||||
"le" => out.push_str("<="),
|
||||
"ge" => out.push_str(">="),
|
||||
"approx" => out.push('~'),
|
||||
"cdot" => out.push('*'),
|
||||
"ldots" | "dots" => out.push_str("..."),
|
||||
"alpha" => out.push_str("alpha"),
|
||||
"beta" => out.push_str("beta"),
|
||||
"gamma" => out.push_str("gamma"),
|
||||
"delta" => out.push_str("delta"),
|
||||
"theta" => out.push_str("theta"),
|
||||
"lambda" => out.push_str("lambda"),
|
||||
"pi" => out.push_str("pi"),
|
||||
"sigma" => out.push_str("sigma"),
|
||||
"phi" => out.push_str("phi"),
|
||||
"omega" => out.push_str("omega"),
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if character == '^' {
|
||||
let mut exponent = String::new();
|
||||
if chars.peek() == Some(&'{') {
|
||||
chars.next();
|
||||
while let Some(next) = chars.next() {
|
||||
if next == '}' {
|
||||
break;
|
||||
}
|
||||
exponent.push(next);
|
||||
}
|
||||
} else if let Some(next) = chars.next() {
|
||||
exponent.push(next);
|
||||
}
|
||||
out.push_str("**");
|
||||
out.push_str(&exponent);
|
||||
continue;
|
||||
}
|
||||
if character == '{' || character == '}' {
|
||||
continue;
|
||||
}
|
||||
out.push(character);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -7972,6 +8047,14 @@ mod tests {
|
||||
assert_eq!(rule.width, 26_214);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_cells_keep_readable_math_fallbacks() {
|
||||
assert_eq!(table_cell_plain_text("Size ($\\mu$m)"), "Size (um)");
|
||||
assert_eq!(table_cell_plain_text("$\\sim$100"), "approx. 100");
|
||||
assert_eq!(table_cell_plain_text("up to $10^6$"), "up to 10**6");
|
||||
assert_eq!(table_cell_plain_text("$\\alpha + \\beta$"), "alpha + beta");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn halign_parses_multicolumn_cells() {
|
||||
let unit =
|
||||
@@ -10081,4 +10164,28 @@ mod runs_edit_tests {
|
||||
);
|
||||
assert!(bold_glyphs(&engine) > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_arxiv_halign_cells() {
|
||||
let source = r"\toprule
|
||||
\multicolumn{2}{c}{Part} \
|
||||
\cmidrule(r){1-2}
|
||||
Name & Description & Size ($\mu) \
|
||||
\midrule
|
||||
Dendrite & Input terminal & $\sim00 \
|
||||
Axon & Output terminal & $\sim0 \
|
||||
Soma & Cell body & up to 0^6$ \
|
||||
\bottomrule";
|
||||
let unit = Unit::halign_from_source_with_template(1, "lll", source, 12);
|
||||
if let VerticalItem::Halign(halign) = &unit.items[0] {
|
||||
for (index, row) in halign.rows.iter().enumerate() {
|
||||
let cells: Vec<_> = row
|
||||
.cells
|
||||
.iter()
|
||||
.map(|cell| (cell.text.clone(), cell.span))
|
||||
.collect();
|
||||
eprintln!("ROW {index} rule={} cells={:?}", row.rule, cells);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -465,7 +465,8 @@ impl Halign {
|
||||
let baseline = center - (lines.len() as i64 - 1) * self.line_height / 2
|
||||
+ self.line_height * 3 / 10
|
||||
+ offset_index as i64 * self.line_height;
|
||||
let text_width = crate::text_width(line);
|
||||
let line = crate::table_cell_plain_text(line);
|
||||
let text_width = crate::text_width(&line);
|
||||
let offset = match cell.alignment {
|
||||
CellAlignment::Left => 0,
|
||||
CellAlignment::Center => (width - text_width).max(0) / 2,
|
||||
@@ -490,7 +491,8 @@ impl Halign {
|
||||
let Some((x, width)) = self.cell_span(row_index, index) else {
|
||||
continue;
|
||||
};
|
||||
let text_width = crate::text_width(line);
|
||||
let line = crate::table_cell_plain_text(line);
|
||||
let text_width = crate::text_width(&line);
|
||||
let offset = match cell.alignment {
|
||||
CellAlignment::Left => 0,
|
||||
CellAlignment::Center => (width - text_width).max(0) / 2,
|
||||
|
||||
@@ -51,7 +51,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
|
||||
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
|
||||
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
|
||||
PDF opt-in with `?engine=route-d`; flat `/preview` and project previews now
|
||||
prefer route-D with a v1 fallback). 1065 workspace tests are green and no oracle
|
||||
prefer route-D with a v1 fallback). 1069 workspace tests are green and no oracle
|
||||
fixture is ignored. Preview JSON also carries a `warnings` array naming
|
||||
environments route-D cannot lay out and control words that survived layout, so
|
||||
unsupported source is reported instead of being silently typeset.
|
||||
|
||||
@@ -16,20 +16,20 @@ cargo test --workspace --offline
|
||||
|
||||
or run `./scripts/verify-route-d.sh`, which executes both.
|
||||
|
||||
The workspace currently passes **1065 tests**:
|
||||
The workspace currently passes **1069 tests**:
|
||||
|
||||
| Suite | Tests |
|
||||
| --- | --- |
|
||||
| route-D unit (engine) | 442 |
|
||||
| engine binary unit | 431 |
|
||||
| server integration | 64 |
|
||||
| route-D unit (engine) | 444 |
|
||||
| engine binary unit | 432 |
|
||||
| server integration | 65 |
|
||||
| v1 integration | 71 |
|
||||
| pdfLaTeX oracle | 42 |
|
||||
| route-D integration | 10 |
|
||||
| engine/core unit | 4 + 1 |
|
||||
|
||||
Latest full run (web trial increment): `./scripts/verify-route-d.sh` passes
|
||||
with fmt clean and **1065 tests** green.
|
||||
with fmt clean and **1069 tests** green.
|
||||
|
||||
Latest live check (2026-10-27): the debug server served `examples/hello.tex`
|
||||
from `target/debug/texrra serve`; `POST /preview` answered 200 with
|
||||
|
||||
+2
-2
@@ -370,7 +370,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
|
||||
|
||||
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph.
|
||||
|
||||
The crate currently has 442 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1065 tests (442 route-D unit, 431 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 64 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; flat and project responses carry `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4.
|
||||
The crate currently has 444 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1069 tests (444 core unit, 432 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 65 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; flat and project responses carry `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4.
|
||||
|
||||
### M0 incremental demo
|
||||
|
||||
@@ -524,7 +524,7 @@ deliberately open rather than approximated:
|
||||
|
||||
## Limits and remaining gaps
|
||||
|
||||
The suite currently stands at 1065 passing tests, with the workspace clean.
|
||||
The suite currently stands at 1069 passing tests, with the workspace clean.
|
||||
Route-D serves both flat `/preview` and project preview/PDF requests by default
|
||||
(automatic v1 fallback; `?engine=v1` or `TEXRRA_ENGINE=v1` opts out). The
|
||||
objective's areas are implemented to the limits below; complex-script shaping is
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Route-D web experiment
|
||||
|
||||
Status: contract fixes and the curated three-project trial are complete
|
||||
(engine contract `1058122`, web `cecad51`); the go/no-go and P0 backlog are
|
||||
recorded below.
|
||||
(engine contract `1058122`, web `cecad51`), and the user-supplied arXiv
|
||||
template has since been used for a second PDF-fix pass (recorded below).
|
||||
Audit baseline: engine `c49afbd`, web `24c9593`; 2026-10-27.
|
||||
|
||||
## Verdict
|
||||
@@ -46,13 +46,13 @@ now means route-D.
|
||||
|
||||
| Area | Route-D | Evidence / impact |
|
||||
| --- | --- | --- |
|
||||
| Article/report basics: title, sections, lists, TOC, page numbers | Supported | corpus and 1065-test suite |
|
||||
| Article/report basics: title, sections, lists, TOC, page numbers | Supported | corpus and 1069-test suite |
|
||||
| Inline/display math, equations, tags, cleveref | Supported | math tests, oracle fixtures |
|
||||
| Floats, captions, tables, booktabs | Supported | table/math tests, corpus |
|
||||
| PNG/JPEG/BMP `\includegraphics` | Supported | project image tests |
|
||||
| PDF/SVG/EPS figures | **Not supported** | undecodable images become placeholder rules |
|
||||
| Inline `thebibliography` + `\cite` | Supported | citation tests |
|
||||
| `.bib` + BibTeX/biblatex data | **Not supported** | `\bibliography` is consumed without running BibTeX; unknown keys print `[?]` |
|
||||
| `.bib` + BibTeX data | Partial | simple `@article`/`@inproceedings` fields are inlined as `thebibliography`; complex BibTeX/BibLaTeX styles are not supported |
|
||||
| Local `.cls`/`.sty`/`\input` | Supported | project class/package tests |
|
||||
| Arbitrary package code, TikZ/pgf | **Not supported** | text/class subset only |
|
||||
| Two-column / `multicols` | Flattened | wrappers consumed; no column layout |
|
||||
@@ -61,7 +61,8 @@ now means route-D.
|
||||
| Footnotes, marks, running heads | Partial | marks are document-level, not per-page |
|
||||
| `\parbox` wrapping | Partial | width argument does not wrap |
|
||||
| Raster images in the SVG preview | Placeholder | the SVG painter draws a grey rectangle; the PDF embeds the real image |
|
||||
| Inline math in table cells | **Not supported** | trial table shows literal `$\mu$m`, `$\sim$`, `$10^6$` |
|
||||
| Inline math in table cells | Readable fallback | math commands are converted to plain text (`um`, `approx.`, `10**6`); not typeset as math |
|
||||
| `\fbox`/rule-only figures | Not supported | the caption is kept, but the rule/frame body is not drawn |
|
||||
| Nested-table images, `\valign` alignments | Not supported/partial | documented engine limits |
|
||||
| Token stream/catcodes beyond `@`/`%` | Partial | textual expander, not a TeX token stream |
|
||||
|
||||
@@ -75,7 +76,7 @@ parentheses); PDFs were checked for `%PDF-`.
|
||||
| --- | --- | --- | --- |
|
||||
| `article-basic` | 1 page, 0 warnings, 502 ms (624 ms), PDF 633 ms / 466 KB | 1 page, 1449 ms (1456 ms), PDF 2701 ms / 488 KB | TOC, figure, table, equation and inline bibliography all present; figure raster is a grey placeholder in SVG |
|
||||
| `unicode-mixed` | 1 page, 0 warnings, 442 ms (510 ms), PDF 656 ms / 174 KB | **422**, `undefined control sequence \'` | Route-D handles accents, Greek math, colours and footnotes; v1 cannot compile the source |
|
||||
| `arxiv-template` | 3 pages, 0 warnings, 1448 ms (1514 ms), PDF 1572 ms / 448 KB | 3 pages, 4280 ms (4308 ms), PDF 4677 ms / 5.2 MB | Route-D is faster, but `.bib` citations render `[?]`, `References` is absent, table-cell math is literal and `orcid.pdf` is a placeholder |
|
||||
| `arxiv-template` | 3 pages, 0 warnings, 1448 ms (1514 ms), PDF 1572 ms / 448 KB | 3 pages, 4280 ms (4308 ms), PDF 4677 ms / 5.2 MB | After the second pass, basic `.bib` citations resolve `[1]`–`[3]`, `References` is present and the table is readable; complex equations and rule/PDF-image figures remain approximate |
|
||||
|
||||
The first pass of this trial also exposed a parser bug: a heading followed on the
|
||||
next line by body text (no blank line) dropped the body, and consecutive
|
||||
@@ -91,22 +92,56 @@ toolbar shows **Route-D (实验)**, and the preview contains the body, table,
|
||||
equation and captions. It also confirmed the remaining visual gap: the PNG
|
||||
figure is a grey rectangle in the SVG preview (the exported PDF embeds it).
|
||||
|
||||
## arXiv-template second pass
|
||||
|
||||
The user-supplied `A_template_for_the_arxiv.zip` exposed four additional
|
||||
problems in the generated PDF, all fixed in the follow-up increment:
|
||||
|
||||
1. **Headings and title were letter-spaced.** Plain text in a paragraph whose
|
||||
base size was not 10pt took the `SizedText` inline-segment path, so its
|
||||
advances were scaled once for the run and again for the paragraph. The
|
||||
fallback run now uses the base size and the normal font path.
|
||||
2. **The table lost its third column.** Table cells are painted as plain text;
|
||||
`$`, `\` and other unsupported glyphs forced the whole cell through the PDF
|
||||
fallback font, leaving only a backslash. Table-cell math now has a readable
|
||||
ASCII fallback (`Size (um)`, `approx. 100`, `10**6`).
|
||||
3. **Page numbers appeared twice.** `fancyhdr`'s `\cfoot{\thepage}` was painted
|
||||
alongside the default route-D page number. Default numbering is now skipped
|
||||
for a fancy pagestyle.
|
||||
4. **`.bib` data was ignored.** Simple `@article`/`@inproceedings` entries are
|
||||
now parsed from project `.bib` files and inlined as `thebibliography`
|
||||
entries before citation resolution, so the template's `[?]` markers become
|
||||
`[1]`–`[3]` and a References section is emitted.
|
||||
|
||||
Remaining visible gaps in this template:
|
||||
|
||||
- the display equation is still a rough approximation of the printed formula;
|
||||
- the `\fbox{\rule...}` figure body is not drawn (only its caption survives);
|
||||
- `orcid.pdf` is a vector image and stays unsupported;
|
||||
- the author block is concatenated and does not reproduce the class layout.
|
||||
|
||||
The revised PDF was rendered page-by-page and checked for the title, table,
|
||||
references and page numbers. A project regression test now uploads a `.bib`
|
||||
file and asserts that a route-D preview contains `References`, `[1]` and the
|
||||
entry text.
|
||||
|
||||
## Go/no-go
|
||||
|
||||
|
||||
- **Go**, limited to text/table/math documents: Route-D is the faster default
|
||||
and handles accents that v1 rejects.
|
||||
- **Conditional no-go** for image-heavy or BibTeX-based papers: the SVG preview
|
||||
does not draw raster images, `.bib` data is not resolved, PDF/vector figures
|
||||
are unsupported, and table-cell math is literal.
|
||||
- **Conditional go** for the supplied arXiv template's text, tables and simple
|
||||
`.bib` references; **no-go** for complex equations, `\fbox`/rule figures,
|
||||
vector/PDF images and image-heavy previews until those gaps are fixed.
|
||||
- Keep the explicit v1 escape hatch: v1 is not a universal fallback (it failed
|
||||
the Unicode trial), so the UI must continue to show the actual engine and
|
||||
warnings/fallbacks instead of assuming v1 always recovers.
|
||||
|
||||
## Backlog after the trial
|
||||
|
||||
- **P0**: SVG preview raster-image embedding; `.bib`/BibTeX citation data;
|
||||
PDF/vector figure support; inline math/formatting in table cells; visible
|
||||
capability warnings for unsupported content.
|
||||
- **P0**: SVG preview raster-image embedding; PDF/vector figure support;
|
||||
complex-equation layout; `\fbox`/rule figure bodies; full BibTeX/BibLaTeX
|
||||
coverage; visible capability warnings for unsupported content.
|
||||
- **P1**: two-column/multicols layout; fontspec/system-font loading; common
|
||||
TikZ/package execution; longtable page splitting.
|
||||
- **P2**: full catcode/token stream; nested-table images; per-page marks;
|
||||
|
||||
+229
-1
@@ -1170,7 +1170,235 @@ fn store_route_d_preview(key: (String, u64), json: String) {
|
||||
fn expand_project_source(source: &str, store: &projects::ProjectStore, id: &str) -> String {
|
||||
let expanded = expand_project_inputs(source, store, id);
|
||||
let expanded = expand_project_packages(&expanded, store, id);
|
||||
expand_project_inputs(&expanded, store, id)
|
||||
let expanded = expand_project_inputs(&expanded, store, id);
|
||||
expand_project_bibliography(&expanded, store, id)
|
||||
}
|
||||
|
||||
/// Inline a project's BibTeX files as a `thebibliography` block so the
|
||||
/// route-D citation pass can resolve `\cite` without a BibTeX run.
|
||||
fn expand_project_bibliography(source: &str, store: &projects::ProjectStore, id: &str) -> String {
|
||||
let mut output = String::new();
|
||||
let mut rest = source;
|
||||
while let Some(index) = rest.find("\\bibliography{") {
|
||||
let line_start = rest[..index].rfind('\n').map_or(0, |position| position + 1);
|
||||
let commented = rest[line_start..index].contains('%');
|
||||
output.push_str(&rest[..index]);
|
||||
if commented {
|
||||
output.push_str("\\bibliography{");
|
||||
rest = &rest[index + "\\bibliography{".len()..];
|
||||
continue;
|
||||
}
|
||||
let after = &rest[index + "\\bibliography{".len()..];
|
||||
let Some(end) = after.find('}') else {
|
||||
output.push_str(&rest[index..]);
|
||||
return output;
|
||||
};
|
||||
let names = &after[..end];
|
||||
let mut entries = Vec::new();
|
||||
for name in names.split(',') {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let path = if name.ends_with(".bib") {
|
||||
name.to_string()
|
||||
} else {
|
||||
format!("{name}.bib")
|
||||
};
|
||||
let Ok(bytes) = store.read_file(id, &path) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(text) = String::from_utf8(bytes) else {
|
||||
continue;
|
||||
};
|
||||
entries.extend(parse_bib_entries(&text));
|
||||
}
|
||||
if entries.is_empty() {
|
||||
output.push_str("\\bibliography{");
|
||||
output.push_str(names);
|
||||
output.push('}');
|
||||
} else {
|
||||
output.push_str("\\begin{thebibliography}{99}\n");
|
||||
for (key, entry) in entries {
|
||||
output.push_str("\\bibitem{");
|
||||
output.push_str(&key);
|
||||
output.push_str("} ");
|
||||
output.push_str(&entry);
|
||||
output.push('\n');
|
||||
}
|
||||
output.push_str("\\end{thebibliography}\n");
|
||||
}
|
||||
rest = &after[end + 1..];
|
||||
}
|
||||
output.push_str(rest);
|
||||
output
|
||||
}
|
||||
|
||||
/// Parse the small BibTeX subset used by paper templates: entries with
|
||||
/// braced or quoted field values. Unknown entry types are skipped.
|
||||
fn parse_bib_entries(text: &str) -> Vec<(String, String)> {
|
||||
let mut entries = Vec::new();
|
||||
let mut cursor = 0usize;
|
||||
while let Some(relative) = text[cursor..].find('@') {
|
||||
let at = cursor + relative;
|
||||
let after_at = &text[at + 1..];
|
||||
let Some(open) = after_at.find(['{', '(']) else {
|
||||
break;
|
||||
};
|
||||
let kind = after_at[..open].trim().to_ascii_lowercase();
|
||||
let open_character = after_at[open..].chars().next().unwrap_or('{');
|
||||
let close_character = if open_character == '(' { ')' } else { '}' };
|
||||
let body_start = at + 1 + open + 1;
|
||||
let mut depth = 0usize;
|
||||
let mut in_quote = false;
|
||||
let mut body_end = None;
|
||||
for (offset, character) in text[body_start..].char_indices() {
|
||||
if character == '"' {
|
||||
in_quote = !in_quote;
|
||||
continue;
|
||||
}
|
||||
if in_quote {
|
||||
continue;
|
||||
}
|
||||
if character == '{' {
|
||||
depth += 1;
|
||||
} else if character == '}' {
|
||||
if depth > 0 {
|
||||
depth -= 1;
|
||||
} else if close_character == '}' {
|
||||
body_end = Some(body_start + offset);
|
||||
break;
|
||||
}
|
||||
} else if character == close_character && depth == 0 {
|
||||
body_end = Some(body_start + offset);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(body_end) = body_end else {
|
||||
break;
|
||||
};
|
||||
let body = &text[body_start..body_end];
|
||||
cursor = body_end + 1;
|
||||
if kind == "comment" || kind == "preamble" || kind == "string" {
|
||||
continue;
|
||||
}
|
||||
let Some(comma) = body.find(',') else {
|
||||
continue;
|
||||
};
|
||||
let key = body[..comma].trim();
|
||||
if key.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let fields = parse_bib_fields(&body[comma + 1..]);
|
||||
if let Some(entry) = format_bib_entry(&fields) {
|
||||
entries.push((key.to_string(), entry));
|
||||
}
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
fn parse_bib_fields(text: &str) -> Vec<(String, String)> {
|
||||
let mut fields = Vec::new();
|
||||
let mut rest = text;
|
||||
loop {
|
||||
rest = rest
|
||||
.trim_start_matches(|character: char| character.is_whitespace() || character == ',');
|
||||
if rest.is_empty() {
|
||||
break;
|
||||
}
|
||||
let name_end = rest
|
||||
.find(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
|
||||
.unwrap_or(rest.len());
|
||||
if name_end == 0 {
|
||||
break;
|
||||
}
|
||||
let name = rest[..name_end].to_ascii_lowercase();
|
||||
rest = rest[name_end..].trim_start();
|
||||
let Some(after_equals) = rest.strip_prefix('=') else {
|
||||
break;
|
||||
};
|
||||
rest = after_equals.trim_start();
|
||||
let value = if let Some(after_open) = rest.strip_prefix('{') {
|
||||
let mut depth = 1usize;
|
||||
let mut end = None;
|
||||
for (offset, character) in after_open.char_indices() {
|
||||
match character {
|
||||
'{' => depth += 1,
|
||||
'}' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
end = Some(offset);
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let Some(end) = end else {
|
||||
break;
|
||||
};
|
||||
rest = &after_open[end + 1..];
|
||||
&after_open[..end]
|
||||
} else if let Some(after_quote) = rest.strip_prefix('"') {
|
||||
let Some(end) = after_quote.find('"') else {
|
||||
break;
|
||||
};
|
||||
rest = &after_quote[end + 1..];
|
||||
&after_quote[..end]
|
||||
} else {
|
||||
let end = rest
|
||||
.find(|character: char| character == ',' || character.is_whitespace())
|
||||
.unwrap_or(rest.len());
|
||||
let value = &rest[..end];
|
||||
rest = &rest[end..];
|
||||
value
|
||||
};
|
||||
let value = value
|
||||
.replace(['{', '}'], "")
|
||||
.replace('~', " ")
|
||||
.replace("--", "-")
|
||||
.split_whitespace()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
fields.push((name, value));
|
||||
}
|
||||
fields
|
||||
}
|
||||
|
||||
fn format_bib_entry(fields: &[(String, String)]) -> Option<String> {
|
||||
let field = |name: &str| {
|
||||
fields
|
||||
.iter()
|
||||
.find(|(field, _)| field == name)
|
||||
.map(|(_, value)| value.as_str())
|
||||
};
|
||||
let title = field("title")?;
|
||||
let author = field("author").unwrap_or("").replace(" and ", ", ");
|
||||
let mut entry = String::new();
|
||||
if !author.is_empty() {
|
||||
entry.push_str(&author);
|
||||
entry.push_str(". ");
|
||||
}
|
||||
entry.push_str("\\emph{");
|
||||
entry.push_str(title);
|
||||
entry.push_str("}.");
|
||||
if let Some(container) = field("journal").or_else(|| field("booktitle")) {
|
||||
entry.push(' ');
|
||||
entry.push_str(container);
|
||||
}
|
||||
if let Some(pages) = field("pages") {
|
||||
entry.push_str(", ");
|
||||
entry.push_str(pages);
|
||||
}
|
||||
if let Some(year) = field("year") {
|
||||
entry.push_str(", ");
|
||||
entry.push_str(year);
|
||||
}
|
||||
if let Some(publisher) = field("publisher").or_else(|| field("organization")) {
|
||||
entry.push_str(", ");
|
||||
entry.push_str(publisher);
|
||||
}
|
||||
Some(entry)
|
||||
}
|
||||
|
||||
/// Decode every `\includegraphics` file a project source references.
|
||||
|
||||
+16
-3
@@ -7586,7 +7586,8 @@ pub fn pdf_bytes_with_images(
|
||||
list
|
||||
})
|
||||
.collect();
|
||||
if !geometry.suppress_page_numbers && !geometry.headings_pagestyle {
|
||||
if !geometry.suppress_page_numbers && !geometry.headings_pagestyle && !geometry.fancy_pagestyle
|
||||
{
|
||||
let style = geometry.page_numbering.as_deref().unwrap_or("arabic");
|
||||
stamp_page_numbers(
|
||||
&mut pages,
|
||||
@@ -11004,7 +11005,7 @@ fn inline_math_segments(
|
||||
for (color, background, frame, chunk) in split_color_runs(&piece, custom) {
|
||||
let chunk = chunk.replace('~', " ");
|
||||
let runs = inline_styled_runs(&chunk, base)
|
||||
.unwrap_or_else(|| vec![(base, style.font_size, 0, chunk.clone())]);
|
||||
.unwrap_or_else(|| vec![(base, 655_360, 0, chunk.clone())]);
|
||||
for (font, size, raise, run_text) in runs {
|
||||
for (is_math, piece) in split_inline_math(&run_text) {
|
||||
if is_math {
|
||||
@@ -14411,7 +14412,8 @@ fn render_json(
|
||||
list.items.extend(frames);
|
||||
}
|
||||
}
|
||||
if !geometry.suppress_page_numbers && !geometry.headings_pagestyle {
|
||||
if !geometry.suppress_page_numbers && !geometry.headings_pagestyle && !geometry.fancy_pagestyle
|
||||
{
|
||||
let style = geometry.page_numbering.as_deref().unwrap_or("arabic");
|
||||
stamp_page_numbers(
|
||||
&mut lists,
|
||||
@@ -17656,6 +17658,17 @@ A definition.
|
||||
assert!(text.contains("D"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_heading_text_is_not_a_sized_inline_run() {
|
||||
let mut style = ParagraphStyle::default();
|
||||
style.font_size = (14.4 * SCALE as f64) as i64;
|
||||
let segments = inline_math_segments("1 Examples", ParagraphFont::Bold, &style, &[], None);
|
||||
assert!(
|
||||
segments.is_none(),
|
||||
"plain heading text must use the paragraph font path, not SizedText"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heading_text_without_blank_lines_is_kept() {
|
||||
let source = "\\documentclass{article}\n\\begin{document}\n\n\\section{One}\nFirst body.\n\\section{Two}\nSecond body.\n\n\\end{document}\n";
|
||||
|
||||
@@ -1212,6 +1212,52 @@ fn serves_project_api_preview_and_pdf() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_preview_resolves_bibtex() {
|
||||
let server = TestServer::start("route-d-bib");
|
||||
let source = "\\documentclass{article}\n\\begin{document}\nSee \\cite{alpha}.\n\n\\bibliography{refs}\n\\end{document}\n";
|
||||
let put = server.request(
|
||||
"PUT",
|
||||
"/api/projects/hello/file?path=hello.tex",
|
||||
source.as_bytes(),
|
||||
"text/plain; charset=utf-8",
|
||||
);
|
||||
assert_eq!(put.status, 200, "{}", put.text());
|
||||
let bib = "@article{alpha,\n title={Alpha entry},\n author={Doe, Jane},\n year={2024}\n}\n";
|
||||
let put = server.request(
|
||||
"PUT",
|
||||
"/api/projects/hello/file?path=refs.bib",
|
||||
bib.as_bytes(),
|
||||
"text/plain; charset=utf-8",
|
||||
);
|
||||
assert_eq!(put.status, 200, "{}", put.text());
|
||||
|
||||
let preview = server.request(
|
||||
"POST",
|
||||
"/api/projects/hello/preview?engine=route-d",
|
||||
&[],
|
||||
"application/json",
|
||||
);
|
||||
assert_eq!(preview.status, 200, "{}", preview.text());
|
||||
let value: Value = serde_json::from_slice(&preview.body).expect("preview JSON");
|
||||
assert_eq!(value["status"], "ok", "{}", value["message"]);
|
||||
let mut text = String::new();
|
||||
for page in value["pages"].as_array().expect("pages") {
|
||||
if let Some(svg) = page["svg"].as_str() {
|
||||
for piece in svg.split('>') {
|
||||
if let Some(content) = piece.split('<').next() {
|
||||
text.push_str(content);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let text: String = text.split_whitespace().collect();
|
||||
assert!(text.contains("References"), "{text}");
|
||||
assert!(text.contains("[1]"), "{text}");
|
||||
assert!(text.contains("Alphaentry"), "{text}");
|
||||
assert!(!text.contains("[?]"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_preview_can_switch_to_route_d() {
|
||||
let server = TestServer::start("route-d-toggle");
|
||||
|
||||
Reference in new issue
Block a user