Carry table environments as floats with their tabular body

This commit is contained in:
gloamxun committed 2026-10-24 20:48:29 +08:00
1 parent 5c04fa83ab
commit a9fbc9b850
4 files changed
+155 -22

No files matched your search

+151 -18
View File
@@ -292,10 +292,10 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
}
if let Some(rest) = trimmed.strip_prefix("\\begin{tabular}") {
if let Some((template, _)) = braced(rest.trim_start()) {
body.push_str(&format!(
"\n\n\\texrratable{{{}}}\n\n",
geometry.tabular.len()
));
if !body.ends_with('\n') {
body.push('\n');
}
body.push_str(&format!("\\texrratable{{{}}}\n", geometry.tabular.len()));
tabular = Some((template.to_string(), String::new()));
}
continue;
@@ -950,13 +950,32 @@ struct SourceParagraph {
float: Option<FloatSpec>,
}
/// A `figure` environment: placement, graphics size and caption.
/// The kind of a LaTeX float environment.
#[derive(Clone, Copy, PartialEq, Eq)]
enum FloatKind {
Figure,
Table,
}
impl FloatKind {
fn caption_prefix(self) -> &'static str {
match self {
FloatKind::Figure => "Figure",
FloatKind::Table => "Table",
}
}
}
/// A `figure` or `table` environment: placement, graphics size and caption.
#[derive(Clone, PartialEq, Eq)]
struct FloatSpec {
kind: FloatKind,
placement: FloatPlacement,
width: Option<i64>,
height: Option<i64>,
caption: Option<String>,
/// Index into `PageGeometry::tabular` for a captured table body.
table: Option<usize>,
}
/// One row of an `align`/`gather` environment.
@@ -1159,12 +1178,22 @@ fn take_labels(text: &mut String) -> Vec<String> {
}
/// Parse a `figure` environment into a single float block.
fn figure_block(raw: &str) -> Option<SourceParagraph> {
let inner = raw
.trim()
.strip_prefix("\\begin{figure}")?
.strip_suffix("\\end{figure}")?
.trim();
fn float_block(raw: &str) -> Option<SourceParagraph> {
let trimmed = raw.trim();
let (kind, inner) = if let Some(inner) = trimmed
.strip_prefix("\\begin{figure}")
.and_then(|rest| rest.strip_suffix("\\end{figure}"))
{
(FloatKind::Figure, inner)
} else if let Some(inner) = trimmed
.strip_prefix("\\begin{table}")
.and_then(|rest| rest.strip_suffix("\\end{table}"))
{
(FloatKind::Table, inner)
} else {
return None;
};
let inner = inner.trim();
let (placement, inner) = match inner.strip_prefix('[') {
Some(rest) => {
let end = rest.find(']')?;
@@ -1182,6 +1211,7 @@ fn figure_block(raw: &str) -> Option<SourceParagraph> {
caption = Some(text);
}
let (width, height) = figure_graphic(inner).unwrap_or((None, None));
let table = embedded_table(inner);
Some(SourceParagraph {
text: String::new(),
font: ParagraphFont::Roman,
@@ -1204,14 +1234,24 @@ fn figure_block(raw: &str) -> Option<SourceParagraph> {
footnotes: Vec::new(),
font_size: None,
float: Some(FloatSpec {
kind,
placement,
width,
height,
caption,
table,
}),
})
}
/// Find the index of a captured `tabular` placeholder inside a table float.
fn embedded_table(inner: &str) -> Option<usize> {
let index = inner.find("\\texrratable{")?;
let after = &inner[index + "\\texrratable{".len()..];
let end = after.find('}')?;
after[..end].trim().parse().ok()
}
fn figure_placement(spec: &str) -> FloatPlacement {
for option in spec.chars() {
match option {
@@ -1278,7 +1318,7 @@ fn figure_graphic(inner: &str) -> Option<(Option<i64>, Option<i64>)> {
}
fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
if let Some(block) = figure_block(raw) {
if let Some(block) = float_block(raw) {
return vec![block];
}
if let Some(body) = raw
@@ -2494,9 +2534,10 @@ fn number_footnotes(paragraphs: &mut [SourceParagraph]) {
}
}
/// Number figure captions and return their label targets.
fn number_figures(paragraphs: &mut [SourceParagraph]) -> Vec<(String, String)> {
let mut number = 0u32;
/// Number float captions and return their label targets.
fn number_floats(paragraphs: &mut [SourceParagraph]) -> Vec<(String, String)> {
let mut figures = 0u32;
let mut tables = 0u32;
let mut labels = Vec::new();
for paragraph in paragraphs {
let Some(spec) = paragraph.float.as_mut() else {
@@ -2505,9 +2546,22 @@ fn number_figures(paragraphs: &mut [SourceParagraph]) -> Vec<(String, String)> {
let Some(caption) = spec.caption.as_mut() else {
continue;
};
number += 1;
let number = match spec.kind {
FloatKind::Figure => {
figures += 1;
figures
}
FloatKind::Table => {
tables += 1;
tables
}
};
let found = take_labels(caption);
*caption = format!("Figure {number}: {}", caption.trim());
*caption = format!(
"{} {number}: {}",
spec.kind.caption_prefix(),
caption.trim()
);
for label in found {
labels.push((label, number.to_string()));
}
@@ -2548,7 +2602,7 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do
let mut paragraphs = expand_maketitle(paragraphs, geometry);
let section_labels = number_sections(&mut paragraphs);
let mut references = section_labels;
references.extend(number_figures(&mut paragraphs));
references.extend(number_floats(&mut paragraphs));
resolve_section_refs(&mut paragraphs, &references);
number_footnotes(&mut paragraphs);
resolve_citations(&mut paragraphs, &geometry.bibliography);
@@ -2569,6 +2623,18 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do
height: rule_height,
});
}
if let Some(table) = spec.table {
if let Some((template, source)) = geometry.tabular.get(table) {
let table_unit = Unit::halign_from_source_with_template_and_tabskips(
index as u64,
&engine_template(template),
source,
6 * SCALE,
Vec::new(),
);
content.extend(table_unit.items);
}
}
if let Some(caption) = &spec.caption {
let style = ParagraphStyle {
line_width: width,
@@ -3098,6 +3164,73 @@ mod source_tests {
assert_eq!(*height, 100 * SCALE);
}
#[test]
fn table_floats_carry_their_tabular() {
let source = r"\begin{table}[t]
\caption{Numbers}\label{tab:a}
\begin{tabular}{|l|c|}
A & 1 \\
B & 2 \\
\end{tabular}
\end{table}
See \ref{tab:a}.";
let (body, geometry) = geometry_and_body(source);
let blocks = paragraphs(&body).unwrap();
let document = build_document(&blocks, &geometry);
assert_eq!(document.units.len(), 2);
let Some(VerticalItem::Float(float)) = document.units[0].items.first() else {
panic!("expected a table float");
};
assert!(
float
.content
.iter()
.any(|item| matches!(item, VerticalItem::Halign(_)))
);
let mut caption = String::new();
for item in &float.content {
if let VerticalItem::Paragraph(paragraph) = item {
for line in &paragraph.lines {
for item in line {
match item {
texrra_tex_core::paragraph::HorizontalItem::Box(box_) => {
if let Some(character) = box_.character {
caption.push(character);
}
}
texrra_tex_core::paragraph::HorizontalItem::Glue { width, .. } => {
if *width > 0 {
caption.push(' ');
}
}
_ => {}
}
}
}
}
}
assert_eq!(caption, "Table 1: Numbers");
assert_eq!(document.units[1].source, "See 1.");
}
#[test]
fn figure_and_table_labels_count_independently() {
let source = r"\begin{figure}[h]
\caption{Shape}\label{fig:a}
\end{figure}
\begin{table}[h]
\caption{Data}\label{tab:b}
\end{table}
See \ref{fig:a} and \ref{tab:b}.";
let (body, geometry) = geometry_and_body(source);
let blocks = paragraphs(&body).unwrap();
let document = build_document(&blocks, &geometry);
assert_eq!(document.units[2].source, "See 1 and 1.");
}
#[test]
fn bibliography_entries_resolve_citations() {
let source = "See \\cite{alpha} and \\cite{alpha,beta}.\n\n\\begin{thebibliography}{9}\n\\bibitem{alpha} Alpha entry.\n\\bibitem{beta} Beta entry.\n\\end{thebibliography}";