Carry figure environments as floats
This commit is contained in:
1 parent
ea06e299d6
commit
5c04fa83ab
4 files changed
+277
-6
No files matched your search
+273
-2
@@ -13,7 +13,8 @@ use texrra_tex_core::cmr10::Cmr10Metrics;
|
||||
use texrra_tex_core::math::{AlignedRow, MathAtom, parse_math, split_math_lines};
|
||||
use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_cm_type1};
|
||||
use texrra_tex_core::{
|
||||
Document, Engine, InsertionClass, ParagraphFont, ParagraphStyle, Unit, VerticalItem,
|
||||
Document, Engine, FloatPlacement, InsertionClass, ParagraphFont, ParagraphStyle, Unit,
|
||||
VerticalItem,
|
||||
};
|
||||
|
||||
const SCALE: i64 = 65_536;
|
||||
@@ -945,6 +946,17 @@ struct SourceParagraph {
|
||||
/// Footnote bodies extracted from this paragraph, with their numbers.
|
||||
footnotes: Vec<(u32, String)>,
|
||||
font_size: Option<i64>,
|
||||
/// A `figure` environment carried as a float unit.
|
||||
float: Option<FloatSpec>,
|
||||
}
|
||||
|
||||
/// A `figure` environment: placement, graphics size and caption.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
struct FloatSpec {
|
||||
placement: FloatPlacement,
|
||||
width: Option<i64>,
|
||||
height: Option<i64>,
|
||||
caption: Option<String>,
|
||||
}
|
||||
|
||||
/// One row of an `align`/`gather` environment.
|
||||
@@ -1025,6 +1037,7 @@ fn paragraphs(source: &str) -> Result<Vec<SourceParagraph>, String> {
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: None,
|
||||
});
|
||||
pending = (0, 0, 0);
|
||||
@@ -1145,7 +1158,129 @@ fn take_labels(text: &mut String) -> Vec<String> {
|
||||
labels
|
||||
}
|
||||
|
||||
/// 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();
|
||||
let (placement, inner) = match inner.strip_prefix('[') {
|
||||
Some(rest) => {
|
||||
let end = rest.find(']')?;
|
||||
(figure_placement(&rest[..end]), rest[end + 1..].trim_start())
|
||||
}
|
||||
None => (FloatPlacement::Top, inner),
|
||||
};
|
||||
let mut caption = figure_caption(inner);
|
||||
let labels = figure_labels(inner);
|
||||
if !labels.is_empty() {
|
||||
let mut text = caption.unwrap_or_default();
|
||||
for label in labels {
|
||||
let _ = write!(text, "\\label{{{label}}}");
|
||||
}
|
||||
caption = Some(text);
|
||||
}
|
||||
let (width, height) = figure_graphic(inner).unwrap_or((None, None));
|
||||
Some(SourceParagraph {
|
||||
text: String::new(),
|
||||
font: ParagraphFont::Roman,
|
||||
line_height: 12,
|
||||
math: false,
|
||||
left_skip: 0,
|
||||
centered: false,
|
||||
right_aligned: false,
|
||||
space_before: 8 * SCALE,
|
||||
space_stretch: 2 * SCALE,
|
||||
space_shrink: 0,
|
||||
page_break: false,
|
||||
equation_number: None,
|
||||
equation_tag: None,
|
||||
equation_rows: Vec::new(),
|
||||
align_centered: false,
|
||||
heading_level: None,
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
font_size: None,
|
||||
float: Some(FloatSpec {
|
||||
placement,
|
||||
width,
|
||||
height,
|
||||
caption,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
fn figure_placement(spec: &str) -> FloatPlacement {
|
||||
for option in spec.chars() {
|
||||
match option {
|
||||
'b' => return FloatPlacement::Bottom,
|
||||
'h' => return FloatPlacement::Here,
|
||||
't' => return FloatPlacement::Top,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
FloatPlacement::Top
|
||||
}
|
||||
|
||||
fn figure_caption(inner: &str) -> Option<String> {
|
||||
let index = inner.find("\\caption")?;
|
||||
let after = inner[index + "\\caption".len()..].trim_start();
|
||||
let after = match after.strip_prefix('[') {
|
||||
Some(short) => match short.find(']') {
|
||||
Some(end) => short[end + 1..].trim_start(),
|
||||
None => after,
|
||||
},
|
||||
None => after,
|
||||
};
|
||||
let (body, _) = braced_group(after)?;
|
||||
Some(body.trim().to_string())
|
||||
}
|
||||
|
||||
fn figure_labels(inner: &str) -> Vec<String> {
|
||||
let mut labels = Vec::new();
|
||||
let mut rest = inner;
|
||||
while let Some(index) = rest.find("\\label") {
|
||||
let after = rest[index + "\\label".len()..].trim_start();
|
||||
let Some((label, consumed)) = braced_group(after) else {
|
||||
break;
|
||||
};
|
||||
labels.push(label.trim().to_string());
|
||||
rest = &after[consumed..];
|
||||
}
|
||||
labels
|
||||
}
|
||||
|
||||
/// Read the placeholder dimensions from an `\includegraphics` option list.
|
||||
fn figure_graphic(inner: &str) -> Option<(Option<i64>, Option<i64>)> {
|
||||
let index = inner.find("\\includegraphics")?;
|
||||
let after = inner[index + "\\includegraphics".len()..].trim_start();
|
||||
let (options, after) = match after.strip_prefix('[') {
|
||||
Some(rest) => {
|
||||
let end = rest.find(']')?;
|
||||
(&rest[..end], rest[end + 1..].trim_start())
|
||||
}
|
||||
None => ("", after),
|
||||
};
|
||||
let (_, _) = braced_group(after)?;
|
||||
let mut width = None;
|
||||
let mut height = None;
|
||||
for part in options.split(',') {
|
||||
let part = part.trim();
|
||||
if let Some(value) = part.strip_prefix("width=") {
|
||||
width = parse_dimension(value.trim());
|
||||
} else if let Some(value) = part.strip_prefix("height=") {
|
||||
height = parse_dimension(value.trim());
|
||||
}
|
||||
}
|
||||
Some((width, height))
|
||||
}
|
||||
|
||||
fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
|
||||
if let Some(block) = figure_block(raw) {
|
||||
return vec![block];
|
||||
}
|
||||
if let Some(body) = raw
|
||||
.trim()
|
||||
.strip_prefix("\\begin{abstract}")
|
||||
@@ -1171,6 +1306,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: Some((12.0 * SCALE as f64) as i64),
|
||||
};
|
||||
let body = SourceParagraph {
|
||||
@@ -1193,6 +1329,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: Some((9.0 * SCALE as f64) as i64),
|
||||
};
|
||||
if body.text.is_empty() {
|
||||
@@ -1263,6 +1400,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: None,
|
||||
}
|
||||
})
|
||||
@@ -1297,6 +1435,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: None,
|
||||
}];
|
||||
}
|
||||
@@ -1340,6 +1479,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: None,
|
||||
}
|
||||
})
|
||||
@@ -1863,6 +2003,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: None,
|
||||
};
|
||||
}
|
||||
@@ -1889,6 +2030,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
};
|
||||
}
|
||||
if let Some(inner) = raw
|
||||
@@ -1915,6 +2057,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: None,
|
||||
};
|
||||
}
|
||||
@@ -1942,6 +2085,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: None,
|
||||
};
|
||||
}
|
||||
@@ -1973,6 +2117,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: None,
|
||||
};
|
||||
}
|
||||
@@ -2001,6 +2146,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
|
||||
heading_starred: starred,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: None,
|
||||
};
|
||||
}
|
||||
@@ -2033,6 +2179,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: None,
|
||||
};
|
||||
}
|
||||
@@ -2057,6 +2204,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: None,
|
||||
}
|
||||
}
|
||||
@@ -2156,6 +2304,7 @@ fn title_block(text: String, size: f64, space_before: i64) -> SourceParagraph {
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: Some((size * SCALE as f64) as i64),
|
||||
}
|
||||
}
|
||||
@@ -2345,6 +2494,27 @@ 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;
|
||||
let mut labels = Vec::new();
|
||||
for paragraph in paragraphs {
|
||||
let Some(spec) = paragraph.float.as_mut() else {
|
||||
continue;
|
||||
};
|
||||
let Some(caption) = spec.caption.as_mut() else {
|
||||
continue;
|
||||
};
|
||||
number += 1;
|
||||
let found = take_labels(caption);
|
||||
*caption = format!("Figure {number}: {}", caption.trim());
|
||||
for label in found {
|
||||
labels.push((label, number.to_string()));
|
||||
}
|
||||
}
|
||||
labels
|
||||
}
|
||||
|
||||
/// Append `thebibliography` entries as numbered paragraphs.
|
||||
fn append_bibliography(paragraphs: &mut Vec<SourceParagraph>, bibliography: &[(String, String)]) {
|
||||
for (index, (_, entry)) in bibliography.iter().enumerate() {
|
||||
@@ -2368,6 +2538,7 @@ fn append_bibliography(paragraphs: &mut Vec<SourceParagraph>, bibliography: &[(S
|
||||
heading_starred: false,
|
||||
heading_number: None,
|
||||
footnotes: Vec::new(),
|
||||
float: None,
|
||||
font_size: None,
|
||||
});
|
||||
}
|
||||
@@ -2376,7 +2547,9 @@ fn append_bibliography(paragraphs: &mut Vec<SourceParagraph>, bibliography: &[(S
|
||||
fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document {
|
||||
let mut paragraphs = expand_maketitle(paragraphs, geometry);
|
||||
let section_labels = number_sections(&mut paragraphs);
|
||||
resolve_section_refs(&mut paragraphs, §ion_labels);
|
||||
let mut references = section_labels;
|
||||
references.extend(number_figures(&mut paragraphs));
|
||||
resolve_section_refs(&mut paragraphs, &references);
|
||||
number_footnotes(&mut paragraphs);
|
||||
resolve_citations(&mut paragraphs, &geometry.bibliography);
|
||||
append_bibliography(&mut paragraphs, &geometry.bibliography);
|
||||
@@ -2385,6 +2558,42 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, paragraph)| {
|
||||
if let Some(spec) = ¶graph.float {
|
||||
let width = line_width;
|
||||
let mut content = Vec::new();
|
||||
if spec.height.is_some() || spec.width.is_some() {
|
||||
let rule_width = spec.width.unwrap_or(width).min(width);
|
||||
let rule_height = spec.height.unwrap_or(rule_width / 2);
|
||||
content.push(VerticalItem::Rule {
|
||||
width: rule_width,
|
||||
height: rule_height,
|
||||
});
|
||||
}
|
||||
if let Some(caption) = &spec.caption {
|
||||
let style = ParagraphStyle {
|
||||
line_width: width,
|
||||
centered: true,
|
||||
par_indent: 0,
|
||||
font_size: 9 * SCALE,
|
||||
baselineskip: 11 * SCALE,
|
||||
line_height: 11 * SCALE,
|
||||
..ParagraphStyle::default()
|
||||
};
|
||||
let caption_unit = Unit::paragraph_with_style_and_face(
|
||||
index as u64,
|
||||
caption.clone(),
|
||||
style,
|
||||
ParagraphFont::Roman,
|
||||
);
|
||||
content.extend(caption_unit.items);
|
||||
}
|
||||
let mut unit =
|
||||
Unit::float_with_content(index as u64, spec.placement, width, 0, content);
|
||||
unit.space_before = paragraph.space_before;
|
||||
unit.space_stretch = paragraph.space_stretch;
|
||||
unit.space_shrink = paragraph.space_shrink;
|
||||
return unit;
|
||||
}
|
||||
if let Some(table) = table_reference(¶graph.text) {
|
||||
if let Some((template, source)) = geometry.tabular.get(table) {
|
||||
let mut unit = Unit::halign_from_source_with_template_and_tabskips(
|
||||
@@ -2827,6 +3036,68 @@ mod source_tests {
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn figures_become_float_units() {
|
||||
let source = "\\begin{figure}[h]\n\\caption{A caption}\\label{fig:a}\n\\end{figure}";
|
||||
let (body, geometry) = geometry_and_body(source);
|
||||
let blocks = paragraphs(&body).unwrap();
|
||||
let document = build_document(&blocks, &geometry);
|
||||
assert_eq!(document.units.len(), 1);
|
||||
let Some(VerticalItem::Float(float)) = document.units[0].items.first() else {
|
||||
panic!("expected a float unit");
|
||||
};
|
||||
assert_eq!(float.placement, FloatPlacement::Here);
|
||||
let mut caption = String::new();
|
||||
for item in &float.content {
|
||||
if let VerticalItem::Paragraph(paragraph) = item {
|
||||
for line in ¶graph.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, "Figure 1: A caption");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn figure_labels_resolve_references() {
|
||||
let source = "See \\ref{fig:a}.\n\n\\begin{figure}\n\\caption{Caption}\n\\label{fig:a}\n\\end{figure}";
|
||||
let (body, geometry) = geometry_and_body(source);
|
||||
let blocks = paragraphs(&body).unwrap();
|
||||
let document = build_document(&blocks, &geometry);
|
||||
assert_eq!(document.units[0].source, "See 1.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn figure_graphics_reserve_a_placeholder() {
|
||||
let source = "\\begin{figure}[b]\n\\includegraphics[width=200pt]{plot.pdf}\\caption{Plot}\n\\end{figure}";
|
||||
let (body, geometry) = geometry_and_body(source);
|
||||
let blocks = paragraphs(&body).unwrap();
|
||||
let document = build_document(&blocks, &geometry);
|
||||
let Some(VerticalItem::Float(float)) = document.units[0].items.first() else {
|
||||
panic!("expected a float unit");
|
||||
};
|
||||
assert_eq!(float.placement, FloatPlacement::Bottom);
|
||||
let Some(VerticalItem::Rule { width, height }) = float.content.first() else {
|
||||
panic!("expected a graphics rule");
|
||||
};
|
||||
assert_eq!(*width, 200 * SCALE);
|
||||
assert_eq!(*height, 100 * SCALE);
|
||||
}
|
||||
|
||||
#[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}";
|
||||
|
||||
Reference in new issue
Block a user