Support multicolumn spans and partial table rules
This commit is contained in:
1 parent
ca5cb0b8af
commit
d4e52dc225
13 files changed
+698
-187
No files matched your search
@@ -366,11 +366,13 @@ parameter with a default value. Unknown packages fail with a clear error.
|
||||
`\includegraphics` embeds PNG, JPEG, or BMP files relative to the `.tex` file.
|
||||
It supports `width`, `height`, and `scale`; width and height accept physical
|
||||
units or fractions of `\linewidth`. Images with transparency are not supported
|
||||
by the current PDF dependency. Basic `tabular` rows use natural column widths
|
||||
by the current PDF dependency. `tabular` rows use natural column widths
|
||||
(content width plus 6pt `\tabcolsep`), are centered in the text block, and draw
|
||||
`\hline`/`booktabs` rules exactly over the table columns; `l`, `c`, `r`, and
|
||||
paragraph (`p{...}`) columns are supported. Spanning cells, partial `\cline`
|
||||
rules, and multi-page table headers are not implemented. Figures honor `[htbp]`
|
||||
`\hline`/`\booktabs` rules exactly over the table columns; `l`, `c`, `r`, and
|
||||
paragraph (`p{...}`) columns are supported. `\multicolumn{n}{align}{...}`
|
||||
spans columns, `\cmidrule(r){a-b}` and `\cline{a-b}` draw partial rules over
|
||||
a column range, and spanning cells distribute their width over the covered
|
||||
natural columns. Multi-page table headers are not implemented. Figures honor `[htbp]`
|
||||
placement hints (`[t]` is deferred to the top of the next page, `[b]` to the
|
||||
page bottom, `[p]` to a float page, `[h]` stays in the flow); tables honor
|
||||
`[t]` by deferring the caption and rows to the next page, `[b]` at the page
|
||||
|
||||
@@ -244,7 +244,9 @@ pub enum Block {
|
||||
rows: Vec<Vec<Vec<Run>>>,
|
||||
caption: Option<Vec<Run>>,
|
||||
alignments: Vec<ColumnAlignment>,
|
||||
rules: Vec<usize>,
|
||||
rules: Vec<TableRule>,
|
||||
/// Per-cell span and alignment metadata, parallel to `rows`.
|
||||
cell_styles: Vec<Vec<TableCellStyle>>,
|
||||
/// Float placement hints from `[htbp]`.
|
||||
placement: String,
|
||||
},
|
||||
@@ -281,13 +283,43 @@ pub enum Block {
|
||||
PageBreak,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ColumnAlignment {
|
||||
Left,
|
||||
Center,
|
||||
Right,
|
||||
}
|
||||
|
||||
/// Per-cell table metadata: a multicolumn span and an optional local alignment.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct TableCellStyle {
|
||||
pub colspan: usize,
|
||||
pub alignment: Option<ColumnAlignment>,
|
||||
}
|
||||
|
||||
/// A horizontal table rule. `end_column` is exclusive; `usize::MAX` means the
|
||||
/// rule spans every column.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct TableRule {
|
||||
pub row: usize,
|
||||
pub start_column: usize,
|
||||
pub end_column: usize,
|
||||
pub trim_left: bool,
|
||||
pub trim_right: bool,
|
||||
}
|
||||
|
||||
impl TableRule {
|
||||
pub fn full(row: usize) -> Self {
|
||||
Self {
|
||||
row,
|
||||
start_column: 0,
|
||||
end_column: usize::MAX,
|
||||
trim_left: false,
|
||||
trim_right: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
pub struct ListBlock {
|
||||
pub ordered: bool,
|
||||
|
||||
@@ -5,7 +5,8 @@ use crate::{
|
||||
document::{
|
||||
Block, ColumnAlignment, DocumentModel, EquationNumber, InlineBox, InlineBoxAlign,
|
||||
ListBlock, ListItem, PageMargins, PageSize, PageStyleKind, PageStyleOverride,
|
||||
ParagraphAlignment, ParsedDocument, RuleBox, Run, TitleStyle, UnresolvedReference,
|
||||
ParagraphAlignment, ParsedDocument, RuleBox, Run, TableCellStyle, TableRule, TitleStyle,
|
||||
UnresolvedReference,
|
||||
},
|
||||
expanded,
|
||||
math_expr::*,
|
||||
@@ -47,7 +48,10 @@ struct TableBuilder {
|
||||
cell: Vec<Run>,
|
||||
caption: Option<Vec<Run>>,
|
||||
alignments: Vec<ColumnAlignment>,
|
||||
rules: Vec<usize>,
|
||||
rules: Vec<TableRule>,
|
||||
cell_styles: Vec<Vec<TableCellStyle>>,
|
||||
row_styles: Vec<TableCellStyle>,
|
||||
pending_cell_style: Option<TableCellStyle>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -1115,9 +1119,33 @@ impl Parser {
|
||||
}
|
||||
expanded::FrontendEventKind::ListItem => self.start_list_item(),
|
||||
expanded::FrontendEventKind::TableCell => self.finish_table_cell(),
|
||||
expanded::FrontendEventKind::TableCellSpan { colspan, alignment } => {
|
||||
if let Some(table) = &mut self.table {
|
||||
table.pending_cell_style = Some(TableCellStyle {
|
||||
colspan: (*colspan).max(1),
|
||||
alignment: *alignment,
|
||||
});
|
||||
}
|
||||
}
|
||||
expanded::FrontendEventKind::TableRule => {
|
||||
if let Some(table) = &mut self.table {
|
||||
table.rules.push(table.rows.len());
|
||||
table.rules.push(TableRule::full(table.rows.len()));
|
||||
}
|
||||
}
|
||||
expanded::FrontendEventKind::TableRuleRange {
|
||||
start_column,
|
||||
end_column,
|
||||
trim_left,
|
||||
trim_right,
|
||||
} => {
|
||||
if let Some(table) = &mut self.table {
|
||||
table.rules.push(TableRule {
|
||||
row: table.rows.len(),
|
||||
start_column: *start_column,
|
||||
end_column: *end_column,
|
||||
trim_left: *trim_left,
|
||||
trim_right: *trim_right,
|
||||
});
|
||||
}
|
||||
}
|
||||
expanded::FrontendEventKind::DisplayMath {
|
||||
@@ -2141,6 +2169,8 @@ impl Parser {
|
||||
fn finish_table_cell(&mut self) {
|
||||
if let Some(table) = &mut self.table {
|
||||
trim_run_end(&mut table.cell);
|
||||
let style = table.pending_cell_style.take().unwrap_or_default();
|
||||
table.row_styles.push(style);
|
||||
table.row.push(std::mem::take(&mut table.cell));
|
||||
}
|
||||
}
|
||||
@@ -2151,6 +2181,9 @@ impl Parser {
|
||||
&& !table.row.is_empty()
|
||||
{
|
||||
table.rows.push(std::mem::take(&mut table.row));
|
||||
table
|
||||
.cell_styles
|
||||
.push(std::mem::take(&mut table.row_styles));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2172,6 +2205,7 @@ impl Parser {
|
||||
caption,
|
||||
alignments: table.alignments,
|
||||
rules: table.rules,
|
||||
cell_styles: table.cell_styles,
|
||||
placement: self.table_placement.clone(),
|
||||
});
|
||||
if self.table_active {
|
||||
|
||||
@@ -2,6 +2,7 @@ use std::{ops::Range, sync::Arc};
|
||||
|
||||
use crate::{
|
||||
MathClass, MathStyleCommand, TeXGlue,
|
||||
document::ColumnAlignment,
|
||||
math_code::UnicodeMathCode,
|
||||
math_expr::{
|
||||
MathAccent, MathDelimiterGlyph, MathDelimiterSettings, MathExpr, MathFontFamilies,
|
||||
@@ -219,7 +220,17 @@ pub enum FrontendEventKind {
|
||||
RowBreak,
|
||||
ListItem,
|
||||
TableCell,
|
||||
TableCellSpan {
|
||||
colspan: usize,
|
||||
alignment: Option<ColumnAlignment>,
|
||||
},
|
||||
TableRule,
|
||||
TableRuleRange {
|
||||
start_column: usize,
|
||||
end_column: usize,
|
||||
trim_left: bool,
|
||||
trim_right: bool,
|
||||
},
|
||||
HeadingStart {
|
||||
level: u8,
|
||||
numbered: bool,
|
||||
|
||||
+2
-1
@@ -18,7 +18,8 @@ author-year citations and plainnat bibliography formatting;
|
||||
`\vbox`/`\vtop` vertical-material capture with inline splicing
|
||||
(`build_positioned_pages` is the only page builder and no separate break
|
||||
planner remains); conditional Base-14 font embedding and natural-width centered
|
||||
table layout.
|
||||
table layout; `\multicolumn` column spans with alignment and partial
|
||||
`\cmidrule(r){a-b}`/`\cline{a-b}` rules.
|
||||
|
||||
## 1. Float tuning and table queue
|
||||
|
||||
|
||||
+3
-1
@@ -65,6 +65,8 @@ the source changes; the SVG preview is refreshed per page.
|
||||
- Compatibility: spacing macros (quad/qquad/thin/en/med/thick, `\vspace*`,
|
||||
`\hspace*`, skips), text symbols/letters/punctuation, break advisories,
|
||||
metadata, `\paragraph` run-in headings, citations/references, tables/lists/images.
|
||||
- Tables: natural column widths, centered tables, `\multicolumn` spans with
|
||||
per-span alignment, and partial `\cmidrule`/`\cline` rules over a column range.
|
||||
- Citations: numeric citations by default; `natbib`/`arxiv.sty` selects author-year
|
||||
`\citet`/`\citep` from `.bib` metadata, formats bibliography entries in
|
||||
plainnat order (`First Last`, `In ...`, `pages`, publisher/year), and drops
|
||||
@@ -104,7 +106,7 @@ See `docs/ROADMAP.md` for concrete implementation plans.
|
||||
- ASCII-only documents use non-embedded Base-14 Times/Courier (arXiv PDF is
|
||||
about 0.7 MB); documents with accented/non-WinAnsi text embed Liberation
|
||||
faces. Tables use natural column widths and centered rules.
|
||||
- `cargo fmt --check` passes; `cargo test --offline` (47 tests: 43 compiler
|
||||
- `cargo fmt --check` passes; `cargo test --offline` (48 tests: 44 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
|
||||
|
||||
+25
-5
@@ -441,6 +441,7 @@ fn render_html_document(
|
||||
caption,
|
||||
alignments,
|
||||
rules,
|
||||
cell_styles,
|
||||
..
|
||||
} => {
|
||||
html.push_str(&format!(
|
||||
@@ -453,25 +454,44 @@ fn render_html_document(
|
||||
}
|
||||
html.push_str("<tbody>");
|
||||
for (row_index, row) in rows.iter().enumerate() {
|
||||
let rule_class = if rules.contains(&row_index) {
|
||||
let rule_class = if rules.iter().any(|rule| {
|
||||
rule.row == row_index
|
||||
&& rule.start_column == 0
|
||||
&& rule.end_column == usize::MAX
|
||||
}) {
|
||||
" class=\"rule-before\""
|
||||
} else {
|
||||
""
|
||||
};
|
||||
html.push_str(&format!("<tr{rule_class}>"));
|
||||
for (column_index, cell) in row.iter().enumerate() {
|
||||
let alignment = match alignments.get(column_index).copied() {
|
||||
let mut column_index = 0;
|
||||
for (cell_index, cell) in row.iter().enumerate() {
|
||||
let style = cell_styles
|
||||
.get(row_index)
|
||||
.and_then(|styles| styles.get(cell_index));
|
||||
let colspan = style.map(|style| style.colspan.max(1)).unwrap_or(1);
|
||||
let alignment = match style
|
||||
.and_then(|style| style.alignment)
|
||||
.or_else(|| alignments.get(column_index).copied())
|
||||
{
|
||||
Some(ColumnAlignment::Center) => "center",
|
||||
Some(ColumnAlignment::Right) => "right",
|
||||
_ => "left",
|
||||
};
|
||||
html.push_str(&format!("<td style=\"text-align:{alignment}\">"));
|
||||
html.push_str(&format!(
|
||||
"<td colspan=\"{colspan}\" style=\"text-align:{alignment}\">"
|
||||
));
|
||||
html.push_str(&render_html_runs(cell, math_preview.as_ref(), 10));
|
||||
html.push_str("</td>");
|
||||
column_index += colspan;
|
||||
}
|
||||
html.push_str("</tr>");
|
||||
}
|
||||
if rules.contains(&rows.len()) {
|
||||
if rules.iter().any(|rule| {
|
||||
rule.row == rows.len()
|
||||
&& rule.start_column == 0
|
||||
&& rule.end_column == usize::MAX
|
||||
}) {
|
||||
html.push_str("<tr class=\"rule-after\"><td colspan=\"99\"></td></tr>");
|
||||
}
|
||||
html.push_str("</tbody></table>");
|
||||
|
||||
@@ -79,8 +79,6 @@ const PRELUDE: &str = r#"
|
||||
\def\toprule{\texrratablerule}
|
||||
\def\midrule{\texrratablerule}
|
||||
\def\bottomrule{\texrratablerule}
|
||||
\def\cline#1{\texrratablerule}
|
||||
\def\multicolumn#1#2#3{#3}
|
||||
\def\&{\texrraampersand}
|
||||
\def\LaTeX{LaTeX}
|
||||
\def\TeX{TeX}
|
||||
|
||||
+169
-101
@@ -26,6 +26,7 @@ use super::{
|
||||
box_font::{BoxFont, TeXHyphenator, scaled_points},
|
||||
is_cjk, math_font, math_layout, parse_dimension, prohibits_cjk_line_break, text_layout,
|
||||
};
|
||||
use texrra_core::document::TableRule;
|
||||
|
||||
mod layout;
|
||||
pub(super) mod preview;
|
||||
@@ -98,19 +99,173 @@ struct PositionedTableLine {
|
||||
alignment: Alignment,
|
||||
}
|
||||
|
||||
struct PositionedTableCell {
|
||||
start_column: usize,
|
||||
colspan: usize,
|
||||
lines: Vec<PositionedTableLine>,
|
||||
}
|
||||
|
||||
struct PositionedTableRow {
|
||||
cells: Vec<Vec<PositionedTableLine>>,
|
||||
cells: Vec<PositionedTableCell>,
|
||||
height: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PositionedTableRule {
|
||||
row: usize,
|
||||
start_column: usize,
|
||||
end_column: usize,
|
||||
trim_left: bool,
|
||||
trim_right: bool,
|
||||
}
|
||||
|
||||
struct PositionedTable {
|
||||
rows: Vec<PositionedTableRow>,
|
||||
column_widths: Vec<i64>,
|
||||
rules: HashSet<usize>,
|
||||
rules: Vec<PositionedTableRule>,
|
||||
height: i64,
|
||||
table_width: i64,
|
||||
}
|
||||
|
||||
/// Draw a table rule at the supplied vertical position. `end_column` is
|
||||
/// exclusive and `usize::MAX` means the rule covers every column.
|
||||
fn draw_table_rule(
|
||||
table_area: &genpdf::render::Area<'_>,
|
||||
column_offsets: &[f64],
|
||||
rule: &PositionedTableRule,
|
||||
y: i64,
|
||||
trim_mm: f64,
|
||||
) {
|
||||
let columns = column_offsets.len().saturating_sub(1);
|
||||
if columns == 0 {
|
||||
return;
|
||||
}
|
||||
let start = rule.start_column.min(columns);
|
||||
let end = if rule.end_column == usize::MAX {
|
||||
columns
|
||||
} else {
|
||||
rule.end_column.min(columns)
|
||||
};
|
||||
if end <= start {
|
||||
return;
|
||||
}
|
||||
let left = column_offsets[start] + if rule.trim_left { trim_mm } else { 0.0 };
|
||||
let right = column_offsets[end] - if rule.trim_right { trim_mm } else { 0.0 };
|
||||
if right <= left {
|
||||
return;
|
||||
}
|
||||
let mut rule_area = table_area.clone();
|
||||
rule_area.add_offset(Position::new(left, scaled_units_to_mm(y)));
|
||||
rule_area.draw_line(
|
||||
vec![
|
||||
Position::default(),
|
||||
Position::new(Mm::from(right - left), 0.0),
|
||||
],
|
||||
Style::new(),
|
||||
);
|
||||
}
|
||||
|
||||
impl PositionedTable {
|
||||
fn render(
|
||||
&mut self,
|
||||
context: &Context,
|
||||
area: genpdf::render::Area<'_>,
|
||||
inherited_style: Style,
|
||||
cjk_family: Option<FontFamily<fonts::Font>>,
|
||||
mono_family: Option<FontFamily<fonts::Font>>,
|
||||
sans_family: Option<FontFamily<fonts::Font>>,
|
||||
) -> Result<RenderResult, genpdf::error::Error> {
|
||||
if scaled_units_to_mm(self.height) > f64::from(area.size().height) {
|
||||
return Ok(RenderResult {
|
||||
size: Size::new(0.0, Mm::from(0.0)),
|
||||
has_more: true,
|
||||
});
|
||||
}
|
||||
|
||||
let table_width_mm = scaled_units_to_mm(self.table_width);
|
||||
let offset = ((f64::from(area.size().width) - table_width_mm) / 2.0).max(0.0);
|
||||
let mut table_area = area.clone();
|
||||
table_area.add_offset(Position::new(offset, 0.0));
|
||||
table_area.set_width(Mm::from(table_width_mm));
|
||||
|
||||
let mut column_offsets = Vec::with_capacity(self.column_widths.len() + 1);
|
||||
let mut column_x = 0.0;
|
||||
column_offsets.push(column_x);
|
||||
for width in &self.column_widths {
|
||||
column_x += scaled_units_to_mm(*width);
|
||||
column_offsets.push(column_x);
|
||||
}
|
||||
// Booktabs trims about half an em from each end of a `(r)`/`(l)` rule.
|
||||
let trim_mm = 0.5 * 10.0 * 25.4 / 72.27;
|
||||
|
||||
let mut y = 0_i64;
|
||||
for row_index in 0..self.rows.len() {
|
||||
for rule in self.rules.iter().filter(|rule| rule.row == row_index) {
|
||||
draw_table_rule(&table_area, &column_offsets, rule, y, trim_mm);
|
||||
}
|
||||
let row_height = self.rows[row_index].height;
|
||||
let row = &mut self.rows[row_index];
|
||||
let mut row_area = table_area.clone();
|
||||
row_area.add_offset(Position::new(0.0, scaled_units_to_mm(y)));
|
||||
for cell in &mut row.cells {
|
||||
let start = cell.start_column.min(self.column_widths.len());
|
||||
let end = (start + cell.colspan.max(1)).min(self.column_widths.len());
|
||||
if end <= start {
|
||||
continue;
|
||||
}
|
||||
let cell_x = column_offsets[start];
|
||||
let cell_width = column_offsets[end] - cell_x;
|
||||
let mut cell_area = row_area.clone();
|
||||
cell_area.add_offset(Position::new(cell_x, 0.0));
|
||||
cell_area.set_width(Mm::from(cell_width));
|
||||
let mut cell_y = 0_i64;
|
||||
for line in &mut cell.lines {
|
||||
let alignment = line.alignment;
|
||||
let mut line_area = cell_area.clone();
|
||||
line_area.add_offset(Position::new(0.0, scaled_units_to_mm(cell_y)));
|
||||
line_area.set_height(Mm::from(scaled_units_to_mm(line.height)));
|
||||
let result = match &mut line.content {
|
||||
PositionedLineContent::Text { line, font_size } => {
|
||||
text_layout::TextLine::new(
|
||||
line,
|
||||
cjk_family,
|
||||
mono_family,
|
||||
sans_family,
|
||||
*font_size,
|
||||
)
|
||||
.aligned(alignment)
|
||||
.render(
|
||||
context,
|
||||
line_area,
|
||||
inherited_style,
|
||||
)?
|
||||
}
|
||||
PositionedLineContent::InlineMath(element) => {
|
||||
element.set_alignment(alignment);
|
||||
element.render(context, line_area, inherited_style)?
|
||||
}
|
||||
};
|
||||
if result.has_more {
|
||||
return Ok(RenderResult {
|
||||
size: Size::new(0.0, Mm::from(0.0)),
|
||||
has_more: true,
|
||||
});
|
||||
}
|
||||
cell_y = cell_y.saturating_add(line.height);
|
||||
}
|
||||
}
|
||||
y = y.saturating_add(row_height);
|
||||
}
|
||||
for rule in self.rules.iter().filter(|rule| rule.row == self.rows.len()) {
|
||||
draw_table_rule(&table_area, &column_offsets, rule, y, trim_mm);
|
||||
}
|
||||
Ok(RenderResult {
|
||||
size: Size::new(area.size().width, Mm::from(scaled_units_to_mm(y))),
|
||||
has_more: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct PositionedFigure {
|
||||
image: elements::Image,
|
||||
image_height: i64,
|
||||
@@ -181,101 +336,6 @@ impl PositionedFigure {
|
||||
}
|
||||
}
|
||||
|
||||
impl PositionedTable {
|
||||
fn render(
|
||||
&mut self,
|
||||
context: &Context,
|
||||
area: genpdf::render::Area<'_>,
|
||||
inherited_style: Style,
|
||||
cjk_family: Option<FontFamily<fonts::Font>>,
|
||||
mono_family: Option<FontFamily<fonts::Font>>,
|
||||
sans_family: Option<FontFamily<fonts::Font>>,
|
||||
) -> Result<RenderResult, genpdf::error::Error> {
|
||||
if scaled_units_to_mm(self.height) > f64::from(area.size().height) {
|
||||
return Ok(RenderResult {
|
||||
size: Size::new(0.0, Mm::from(0.0)),
|
||||
has_more: true,
|
||||
});
|
||||
}
|
||||
|
||||
let table_width_mm = scaled_units_to_mm(self.table_width);
|
||||
let offset = ((f64::from(area.size().width) - table_width_mm) / 2.0).max(0.0);
|
||||
let mut table_area = area.clone();
|
||||
table_area.add_offset(Position::new(offset, 0.0));
|
||||
table_area.set_width(Mm::from(table_width_mm));
|
||||
let total: i64 = self.column_widths.iter().sum();
|
||||
let weights: Vec<usize> = self
|
||||
.column_widths
|
||||
.iter()
|
||||
.map(|width| (((*width).max(1) * 255) / total.max(1)).clamp(1, 255) as usize)
|
||||
.collect();
|
||||
let mut y = 0_i64;
|
||||
for (row_index, row) in self.rows.iter_mut().enumerate() {
|
||||
let mut row_area = table_area.clone();
|
||||
row_area.add_offset(Position::new(0.0, scaled_units_to_mm(y)));
|
||||
if self.rules.contains(&row_index) {
|
||||
let width = table_area.size().width;
|
||||
row_area.draw_line(
|
||||
vec![Position::default(), Position::new(width, 0.0)],
|
||||
Style::new(),
|
||||
);
|
||||
}
|
||||
let cell_areas = row_area.split_horizontally(&weights);
|
||||
for (cell_area, lines) in cell_areas.into_iter().zip(&mut row.cells) {
|
||||
let mut cell_y = 0_i64;
|
||||
for line in lines {
|
||||
let alignment = line.alignment;
|
||||
let mut line_area = cell_area.clone();
|
||||
line_area.add_offset(Position::new(0.0, scaled_units_to_mm(cell_y)));
|
||||
line_area.set_height(Mm::from(scaled_units_to_mm(line.height)));
|
||||
let result = match &mut line.content {
|
||||
PositionedLineContent::Text { line, font_size } => {
|
||||
text_layout::TextLine::new(
|
||||
line,
|
||||
cjk_family,
|
||||
mono_family,
|
||||
sans_family,
|
||||
*font_size,
|
||||
)
|
||||
.aligned(alignment)
|
||||
.render(
|
||||
context,
|
||||
line_area,
|
||||
inherited_style,
|
||||
)?
|
||||
}
|
||||
PositionedLineContent::InlineMath(element) => {
|
||||
element.set_alignment(alignment);
|
||||
element.render(context, line_area, inherited_style)?
|
||||
}
|
||||
};
|
||||
if result.has_more {
|
||||
return Ok(RenderResult {
|
||||
size: Size::new(0.0, Mm::from(0.0)),
|
||||
has_more: true,
|
||||
});
|
||||
}
|
||||
cell_y = cell_y.saturating_add(line.height);
|
||||
}
|
||||
}
|
||||
y = y.saturating_add(row.height);
|
||||
}
|
||||
if self.rules.contains(&self.rows.len()) {
|
||||
let mut rule_area = table_area.clone();
|
||||
rule_area.add_offset(Position::new(0.0, scaled_units_to_mm(y)));
|
||||
let width = table_area.size().width;
|
||||
rule_area.draw_line(
|
||||
vec![Position::default(), Position::new(width, 0.0)],
|
||||
Style::new(),
|
||||
);
|
||||
}
|
||||
Ok(RenderResult {
|
||||
size: Size::new(area.size().width, Mm::from(scaled_units_to_mm(y))),
|
||||
has_more: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)] // anchors remain useful for diagnostics and future page queries
|
||||
enum PositionedPageItem {
|
||||
Line(PositionedLine),
|
||||
@@ -1583,7 +1643,7 @@ impl elements::CellDecorator for TableRuleDecorator {
|
||||
pub(super) fn build_table_element(
|
||||
rows: &[Vec<Vec<Run>>],
|
||||
alignments: &[ColumnAlignment],
|
||||
rules: &[usize],
|
||||
rules: &[TableRule],
|
||||
cjk_family: Option<FontFamily<fonts::Font>>,
|
||||
mono_family: Option<FontFamily<fonts::Font>>,
|
||||
math_metrics: &math_font::MathFontMetrics,
|
||||
@@ -1597,7 +1657,16 @@ pub(super) fn build_table_element(
|
||||
let mut table = elements::TableLayout::new(vec![1; columns]);
|
||||
if !rules.is_empty() {
|
||||
table.set_cell_decorator(TableRuleDecorator {
|
||||
rules: rules.iter().copied().collect(),
|
||||
rules: rules
|
||||
.iter()
|
||||
.filter(|rule| {
|
||||
rule.start_column == 0
|
||||
&& rule.end_column == usize::MAX
|
||||
&& !rule.trim_left
|
||||
&& !rule.trim_right
|
||||
})
|
||||
.map(|rule| rule.row)
|
||||
.collect(),
|
||||
num_rows: rows.len(),
|
||||
});
|
||||
}
|
||||
@@ -2774,8 +2843,7 @@ fn builtin_safe_char(ch: char) -> bool {
|
||||
ch.is_ascii()
|
||||
|| matches!(
|
||||
ch,
|
||||
'µ' | '¹'
|
||||
| '²'
|
||||
'µ' | '²'
|
||||
| '³'
|
||||
| '–'
|
||||
| '—'
|
||||
|
||||
+144
-43
@@ -1,5 +1,7 @@
|
||||
use super::*;
|
||||
use texrra_core::document::{ParagraphAlignment, TitleStyle, UnresolvedReference};
|
||||
use texrra_core::document::{
|
||||
ParagraphAlignment, TableCellStyle, TableRule, TitleStyle, UnresolvedReference,
|
||||
};
|
||||
|
||||
const ARTICLE_11PT_LIST_TOPSEP_PT: f64 = 9.0;
|
||||
const ARTICLE_11PT_LIST_TOPSEP_STRETCH_PT: f64 = 3.0;
|
||||
@@ -533,7 +535,8 @@ fn append_list_layout_tokens(
|
||||
fn layout_table(
|
||||
rows: &[Vec<Vec<Run>>],
|
||||
alignments: &[ColumnAlignment],
|
||||
rules: &[usize],
|
||||
rules: &[TableRule],
|
||||
cell_styles: &[Vec<TableCellStyle>],
|
||||
content_width_mm: f64,
|
||||
metrics: &BoxFontMetrics,
|
||||
font_cache: &fonts::FontCache,
|
||||
@@ -545,7 +548,23 @@ fn layout_table(
|
||||
cache: &mut ParagraphLayoutCache,
|
||||
font_size: u8,
|
||||
) -> Option<PositionedTable> {
|
||||
let column_count = rows.iter().map(Vec::len).max().unwrap_or(0);
|
||||
let row_column_count = |row: &Vec<Vec<Run>>, styles: Option<&Vec<TableCellStyle>>| {
|
||||
let mut columns = 0;
|
||||
for index in 0..row.len() {
|
||||
let span = styles
|
||||
.and_then(|styles| styles.get(index))
|
||||
.map(|style| style.colspan.max(1))
|
||||
.unwrap_or(1);
|
||||
columns += span;
|
||||
}
|
||||
columns.max(row.len())
|
||||
};
|
||||
let column_count = rows
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, row)| row_column_count(row, cell_styles.get(index)))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
if column_count == 0 {
|
||||
return None;
|
||||
}
|
||||
@@ -567,15 +586,26 @@ fn layout_table(
|
||||
PositionedLineContent::InlineMath(_) => 0.0,
|
||||
}
|
||||
};
|
||||
let style_at = |row: usize, cell: usize| -> TableCellStyle {
|
||||
cell_styles
|
||||
.get(row)
|
||||
.and_then(|styles| styles.get(cell))
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
};
|
||||
|
||||
// First pass: measure each cell without imposed column widths and record the
|
||||
// widest line. This gives the table its natural width instead of stretching
|
||||
// every column across the whole text block.
|
||||
// First pass: measure each cell without imposed column widths. Single-column
|
||||
// cells establish their column; spanning cells are satisfied afterwards by
|
||||
// growing the columns they cover.
|
||||
let mut natural_widths = vec![0.0_f64; column_count];
|
||||
for row in rows {
|
||||
for column in 0..column_count {
|
||||
let runs = row.get(column).map(Vec::as_slice).unwrap_or_default();
|
||||
if runs.is_empty() {
|
||||
let mut spanning_cells: Vec<(usize, usize, usize, usize, f64)> = Vec::new();
|
||||
for (row_index, row) in rows.iter().enumerate() {
|
||||
let mut column = 0;
|
||||
for (cell_index, runs) in row.iter().enumerate() {
|
||||
let style = style_at(row_index, cell_index);
|
||||
let span = style.colspan.max(1).min(column_count - column);
|
||||
if span == 0 || runs.is_empty() {
|
||||
column += span;
|
||||
continue;
|
||||
}
|
||||
let lines = measure_positioned_lines(
|
||||
@@ -599,13 +629,19 @@ fn layout_table(
|
||||
* 0.6
|
||||
* 25.4
|
||||
/ 72.27;
|
||||
let mut width = 0.0_f64;
|
||||
for line in &lines {
|
||||
let width = match &line.content {
|
||||
width = width.max(match &line.content {
|
||||
PositionedLineContent::InlineMath(_) => estimated,
|
||||
_ => natural_line_width(&line.content),
|
||||
};
|
||||
natural_widths[column] = natural_widths[column].max(width);
|
||||
});
|
||||
}
|
||||
if span == 1 {
|
||||
natural_widths[column] = natural_widths[column].max(width);
|
||||
} else {
|
||||
spanning_cells.push((row_index, cell_index, column, span, width));
|
||||
}
|
||||
column += span;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -615,6 +651,17 @@ fn layout_table(
|
||||
.iter()
|
||||
.map(|width| (*width + padding_mm).max(padding_mm))
|
||||
.collect();
|
||||
for (_, _, start, span, width) in &spanning_cells {
|
||||
let end = (*start + *span).min(column_count);
|
||||
let available: f64 = column_widths_mm[*start..end].iter().sum();
|
||||
let required = *width + padding_mm;
|
||||
if required > available && end > *start {
|
||||
let extra = (required - available) / (end - *start) as f64;
|
||||
for column in &mut column_widths_mm[*start..end] {
|
||||
*column += extra;
|
||||
}
|
||||
}
|
||||
}
|
||||
let natural_table_width: f64 = column_widths_mm.iter().sum();
|
||||
let scale = if natural_table_width > content_width_mm {
|
||||
content_width_mm / natural_table_width
|
||||
@@ -629,20 +676,32 @@ fn layout_table(
|
||||
.iter()
|
||||
.map(|width| millimeters_to_scaled(*width).max(1))
|
||||
.collect();
|
||||
let scaled_widths: Vec<f64> = column_widths
|
||||
.iter()
|
||||
.map(|width| scaled_units_to_mm(*width))
|
||||
.collect();
|
||||
|
||||
// Second pass: wrap into the final column width.
|
||||
// Second pass: wrap into the final column width and record each cell's
|
||||
// starting column so `\multicolumn` cells can span several columns.
|
||||
let mut positioned_rows = Vec::with_capacity(rows.len());
|
||||
let mut total_height = 0_i64;
|
||||
for row in rows {
|
||||
let mut cells = Vec::with_capacity(column_count);
|
||||
for (row_index, row) in rows.iter().enumerate() {
|
||||
let mut cells = Vec::with_capacity(row.len());
|
||||
let mut row_height = empty_row_height;
|
||||
for column in 0..column_count {
|
||||
let runs = row.get(column).map(Vec::as_slice).unwrap_or_default();
|
||||
let available_mm = (column_widths_mm[column] - padding_mm).max(1.0);
|
||||
let mut column = 0;
|
||||
for cell_index in 0..row.len() {
|
||||
let style = style_at(row_index, cell_index);
|
||||
let span = style.colspan.max(1).min(column_count - column);
|
||||
if span == 0 {
|
||||
break;
|
||||
}
|
||||
let runs = row[cell_index].as_slice();
|
||||
let available_mm =
|
||||
(scaled_widths[column..column + span].iter().sum::<f64>()) - padding_mm;
|
||||
let lines = measure_positioned_lines(
|
||||
runs,
|
||||
cell_font_size,
|
||||
available_mm,
|
||||
available_mm.max(1.0),
|
||||
metrics,
|
||||
font_cache,
|
||||
cjk_family,
|
||||
@@ -652,27 +711,34 @@ fn layout_table(
|
||||
math_layout,
|
||||
cache,
|
||||
);
|
||||
let alignment = match alignments
|
||||
.get(column)
|
||||
.copied()
|
||||
.unwrap_or(ColumnAlignment::Left)
|
||||
{
|
||||
let alignment = style.alignment.unwrap_or_else(|| {
|
||||
alignments
|
||||
.get(column)
|
||||
.copied()
|
||||
.unwrap_or(ColumnAlignment::Left)
|
||||
});
|
||||
let alignment = match alignment {
|
||||
ColumnAlignment::Left => Alignment::Left,
|
||||
ColumnAlignment::Center => Alignment::Center,
|
||||
ColumnAlignment::Right => Alignment::Right,
|
||||
};
|
||||
let mut cell = Vec::with_capacity(lines.len());
|
||||
let mut cell_lines = Vec::with_capacity(lines.len());
|
||||
let mut cell_height = 0_i64;
|
||||
for line in lines {
|
||||
cell_height = cell_height.saturating_add(line.height);
|
||||
cell.push(PositionedTableLine {
|
||||
cell_lines.push(PositionedTableLine {
|
||||
content: line.content,
|
||||
height: line.height,
|
||||
alignment,
|
||||
});
|
||||
}
|
||||
row_height = row_height.max(cell_height);
|
||||
cells.push(cell);
|
||||
cells.push(PositionedTableCell {
|
||||
start_column: column,
|
||||
colspan: span,
|
||||
lines: cell_lines,
|
||||
});
|
||||
column += span;
|
||||
}
|
||||
total_height = total_height.saturating_add(row_height);
|
||||
positioned_rows.push(PositionedTableRow {
|
||||
@@ -684,7 +750,16 @@ fn layout_table(
|
||||
Some(PositionedTable {
|
||||
rows: positioned_rows,
|
||||
column_widths,
|
||||
rules: rules.iter().copied().collect(),
|
||||
rules: rules
|
||||
.iter()
|
||||
.map(|rule| PositionedTableRule {
|
||||
row: rule.row,
|
||||
start_column: rule.start_column,
|
||||
end_column: rule.end_column,
|
||||
trim_left: rule.trim_left,
|
||||
trim_right: rule.trim_right,
|
||||
})
|
||||
.collect(),
|
||||
height: total_height,
|
||||
table_width,
|
||||
})
|
||||
@@ -2322,6 +2397,7 @@ pub(super) fn build_positioned_pages(
|
||||
caption,
|
||||
alignments,
|
||||
rules,
|
||||
cell_styles,
|
||||
placement,
|
||||
} => {
|
||||
pre_display_size = None;
|
||||
@@ -2344,6 +2420,7 @@ pub(super) fn build_positioned_pages(
|
||||
rows,
|
||||
alignments,
|
||||
rules,
|
||||
cell_styles,
|
||||
content_width_mm,
|
||||
metrics,
|
||||
font_cache,
|
||||
@@ -2404,15 +2481,27 @@ pub(super) fn build_positioned_pages(
|
||||
table_width,
|
||||
..
|
||||
} = table;
|
||||
let table_row_count = table_rows.len();
|
||||
for (row_index, row) in table_rows.into_iter().enumerate() {
|
||||
let row_height = row.height;
|
||||
let mut row_rules = HashSet::new();
|
||||
if row_index == 0 && table_rules.contains(&0) {
|
||||
row_rules.insert(0);
|
||||
}
|
||||
if table_rules.contains(&(row_index + 1)) {
|
||||
row_rules.insert(1);
|
||||
}
|
||||
let row_rules = table_rules
|
||||
.iter()
|
||||
.filter_map(|rule| {
|
||||
if rule.row == row_index {
|
||||
let mut rule = rule.clone();
|
||||
rule.row = 0;
|
||||
Some(rule)
|
||||
} else if row_index + 1 == table_row_count
|
||||
&& rule.row == table_row_count
|
||||
{
|
||||
let mut rule = rule.clone();
|
||||
rule.row = 1;
|
||||
Some(rule)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
pages
|
||||
.last_mut()
|
||||
.expect("the page list starts with one page")
|
||||
@@ -2530,6 +2619,7 @@ pub(super) fn build_positioned_pages(
|
||||
table_width,
|
||||
..
|
||||
} = table;
|
||||
let table_row_count = table_rows.len();
|
||||
for (row_index, row) in table_rows.into_iter().enumerate() {
|
||||
if row.height > page_goal {
|
||||
return None;
|
||||
@@ -2564,13 +2654,24 @@ pub(super) fn build_positioned_pages(
|
||||
);
|
||||
|
||||
let row_height = row.height;
|
||||
let mut row_rules = HashSet::new();
|
||||
if row_index == 0 && table_rules.contains(&0) {
|
||||
row_rules.insert(0);
|
||||
}
|
||||
if table_rules.contains(&(row_index + 1)) {
|
||||
row_rules.insert(1);
|
||||
}
|
||||
let row_rules = table_rules
|
||||
.iter()
|
||||
.filter_map(|rule| {
|
||||
if rule.row == row_index {
|
||||
let mut rule = rule.clone();
|
||||
rule.row = 0;
|
||||
Some(rule)
|
||||
} else if row_index + 1 == table_row_count
|
||||
&& rule.row == table_row_count
|
||||
{
|
||||
let mut rule = rule.clone();
|
||||
rule.row = 1;
|
||||
Some(rule)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let element = PositionedTable {
|
||||
rows: vec![row],
|
||||
column_widths: column_widths.clone(),
|
||||
|
||||
@@ -166,44 +166,98 @@ fn write_table(
|
||||
let text_width_mm = f64::from(content_width);
|
||||
let table_width_mm = scaled_units_to_mm(table.table_width);
|
||||
let table_x = ((text_width_mm - table_width_mm) / 2.0).max(0.0);
|
||||
let width_mm = |width: i64| scaled_units_to_mm(width);
|
||||
let mut column_offsets = Vec::with_capacity(table.column_widths.len() + 1);
|
||||
let mut column_x = 0.0;
|
||||
column_offsets.push(column_x);
|
||||
for width in &table.column_widths {
|
||||
column_x += width_mm(*width);
|
||||
column_offsets.push(column_x);
|
||||
}
|
||||
// Booktabs trims about half an em from the end of a `(r)`/`(l)` rule.
|
||||
let trim_mm = 0.5 * 10.0 * 25.4 / 72.27;
|
||||
let rules = &table.rules;
|
||||
let column_count = table.column_widths.len();
|
||||
let mut cursor = 0.0_f64;
|
||||
for (row_index, row) in table.rows.iter_mut().enumerate() {
|
||||
if table.rules.contains(&row_index) {
|
||||
write_rule(output, table_x, cursor, table_width_mm);
|
||||
}
|
||||
let mut x = table_x;
|
||||
for (column_index, cell) in row.cells.iter_mut().enumerate() {
|
||||
let column_width = Mm::from(
|
||||
table
|
||||
.column_widths
|
||||
.get(column_index)
|
||||
.map(|width| scaled_units_to_mm(*width))
|
||||
.unwrap_or(0.0),
|
||||
for rule in rules.iter().filter(|rule| rule.row == row_index) {
|
||||
write_table_rule(
|
||||
output,
|
||||
table_x,
|
||||
cursor,
|
||||
&column_offsets,
|
||||
column_count,
|
||||
rule,
|
||||
trim_mm,
|
||||
);
|
||||
}
|
||||
for cell in &mut row.cells {
|
||||
let start = cell.start_column.min(column_count);
|
||||
let end = (start + cell.colspan.max(1)).min(column_count);
|
||||
if end <= start {
|
||||
continue;
|
||||
}
|
||||
let cell_x = column_offsets[start];
|
||||
let cell_width = column_offsets[end] - cell_x;
|
||||
let mut cell_y = 0.0;
|
||||
for line in cell.iter_mut() {
|
||||
for line in &mut cell.lines {
|
||||
let alignment = line.alignment;
|
||||
write_line_content(
|
||||
output,
|
||||
&line.content,
|
||||
Mm::from(x),
|
||||
Mm::from(table_x + cell_x),
|
||||
y + Mm::from(cursor + cell_y),
|
||||
alignment,
|
||||
false,
|
||||
column_width,
|
||||
Mm::from(cell_width),
|
||||
fonts,
|
||||
cjk_family,
|
||||
monospace_family,
|
||||
sans_family,
|
||||
);
|
||||
cell_y += scaled_units_to_mm(line.height);
|
||||
cell_y += width_mm(line.height);
|
||||
}
|
||||
x += f64::from(column_width);
|
||||
}
|
||||
cursor += scaled_units_to_mm(row.height);
|
||||
cursor += width_mm(row.height);
|
||||
}
|
||||
if table.rules.contains(&table.rows.len()) {
|
||||
write_rule(output, table_x, cursor, table_width_mm);
|
||||
for rule in rules.iter().filter(|rule| rule.row == table.rows.len()) {
|
||||
write_table_rule(
|
||||
output,
|
||||
table_x,
|
||||
cursor,
|
||||
&column_offsets,
|
||||
column_count,
|
||||
rule,
|
||||
trim_mm,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_table_rule(
|
||||
output: &mut String,
|
||||
table_x: f64,
|
||||
y: f64,
|
||||
column_offsets: &[f64],
|
||||
column_count: usize,
|
||||
rule: &PositionedTableRule,
|
||||
trim_mm: f64,
|
||||
) {
|
||||
if column_count == 0 {
|
||||
return;
|
||||
}
|
||||
let start = rule.start_column.min(column_count);
|
||||
let end = if rule.end_column == usize::MAX {
|
||||
column_count
|
||||
} else {
|
||||
rule.end_column.min(column_count)
|
||||
};
|
||||
if end <= start {
|
||||
return;
|
||||
}
|
||||
let left = column_offsets[start] + if rule.trim_left { trim_mm } else { 0.0 };
|
||||
let right = column_offsets[end] - if rule.trim_right { trim_mm } else { 0.0 };
|
||||
if right > left {
|
||||
write_rule(output, table_x + left, y, right - left);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3205,26 +3205,135 @@ fn url_primitive(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_table_column_range(
|
||||
input: &mut vm::ExecutionInput<CompilerState>,
|
||||
token: token::Token,
|
||||
argument: &[token::Token],
|
||||
) -> texlang::prelude::Result<(usize, usize)> {
|
||||
let text = simple_token_text(strip_braced_tokens(argument));
|
||||
let text = text
|
||||
.chars()
|
||||
.filter(|c| !c.is_whitespace())
|
||||
.collect::<String>();
|
||||
let mut parse_number = |value: &str| {
|
||||
value.parse::<usize>().map_err(|_| {
|
||||
input.fatal_error(error::SimpleTokenError::new(
|
||||
token,
|
||||
format!("expected a table column number, found `{value}`"),
|
||||
))
|
||||
})
|
||||
};
|
||||
if let Some((first, last)) = text.split_once('-') {
|
||||
let start = parse_number(first)?.saturating_sub(1);
|
||||
let end = parse_number(last)?;
|
||||
if end <= start {
|
||||
return Err(input.fatal_error(error::SimpleTokenError::new(
|
||||
token,
|
||||
"table column range must be non-empty",
|
||||
)));
|
||||
}
|
||||
Ok((start, end))
|
||||
} else {
|
||||
let column = parse_number(&text)?.saturating_sub(1);
|
||||
Ok((column, column + 1))
|
||||
}
|
||||
}
|
||||
|
||||
fn cmidrule_primitive(
|
||||
token: token::Token,
|
||||
input: &mut vm::ExecutionInput<CompilerState>,
|
||||
) -> texlang::prelude::Result<()> {
|
||||
if let Some(next) = read_next_non_space_unexpanded(input)?
|
||||
let mut trim_left = false;
|
||||
let mut trim_right = false;
|
||||
let next = read_next_non_space_unexpanded(input)?;
|
||||
if let Some(next) = next
|
||||
&& matches!(next.value(), token::Value::Other('('))
|
||||
{
|
||||
loop {
|
||||
let Some(inner) = input.unexpanded().next()? else {
|
||||
break;
|
||||
};
|
||||
if matches!(inner.value(), token::Value::Other(')')) {
|
||||
break;
|
||||
match inner.value() {
|
||||
token::Value::Other(')') => break,
|
||||
token::Value::Letter('l') | token::Value::Other('l') => trim_left = true,
|
||||
token::Value::Letter('r') | token::Value::Other('r') => trim_right = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
} else if let Some(next) = read_next_non_space_unexpanded(input)? {
|
||||
} else if let Some(next) = next {
|
||||
input.unexpanded().back(next);
|
||||
}
|
||||
let _range = read_unexpanded_argument(input, token, "expects a column range")?;
|
||||
write_event(input, token, FrontendEventKind::TableRule);
|
||||
let range = read_unexpanded_argument(input, token, "expects a column range")?;
|
||||
let (start_column, end_column) = parse_table_column_range(input, token, &range)?;
|
||||
write_event(
|
||||
input,
|
||||
token,
|
||||
FrontendEventKind::TableRuleRange {
|
||||
start_column,
|
||||
end_column,
|
||||
trim_left,
|
||||
trim_right,
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cline_primitive(
|
||||
token: token::Token,
|
||||
input: &mut vm::ExecutionInput<CompilerState>,
|
||||
) -> texlang::prelude::Result<()> {
|
||||
let range = read_unexpanded_argument(input, token, "expects a column range")?;
|
||||
let (start_column, end_column) = parse_table_column_range(input, token, &range)?;
|
||||
write_event(
|
||||
input,
|
||||
token,
|
||||
FrontendEventKind::TableRuleRange {
|
||||
start_column,
|
||||
end_column,
|
||||
trim_left: false,
|
||||
trim_right: false,
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn multicolumn_primitive(
|
||||
token: token::Token,
|
||||
input: &mut vm::ExecutionInput<CompilerState>,
|
||||
) -> texlang::prelude::Result<()> {
|
||||
let columns = read_unexpanded_argument(input, token, "expects a column count")?;
|
||||
let count_text = simple_token_text(strip_braced_tokens(&columns));
|
||||
let colspan = count_text.trim().parse::<usize>().map_err(|_| {
|
||||
input.fatal_error(error::SimpleTokenError::new(
|
||||
token,
|
||||
format!("expected a multicolumn count, found `{count_text}`"),
|
||||
))
|
||||
})?;
|
||||
if colspan == 0 {
|
||||
return Err(input.fatal_error(error::SimpleTokenError::new(
|
||||
token,
|
||||
"multicolumn count must be positive",
|
||||
)));
|
||||
}
|
||||
let alignment = read_unexpanded_argument(input, token, "expects a column alignment")?;
|
||||
let alignment_text = simple_token_text(strip_braced_tokens(&alignment));
|
||||
let alignment = match alignment_text.trim().chars().next() {
|
||||
Some('l') => Some(texrra_core::document::ColumnAlignment::Left),
|
||||
Some('c') => Some(texrra_core::document::ColumnAlignment::Center),
|
||||
Some('r') => Some(texrra_core::document::ColumnAlignment::Right),
|
||||
_ => None,
|
||||
};
|
||||
let content = read_unexpanded_argument(input, token, "expects multicolumn content")?;
|
||||
write_event(
|
||||
input,
|
||||
token,
|
||||
FrontendEventKind::TableCellSpan { colspan, alignment },
|
||||
);
|
||||
let inner = strip_braced_tokens(&content).to_vec();
|
||||
input
|
||||
.as_mut()
|
||||
.expansions_mut()
|
||||
.extend(inner.into_iter().rev());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -6988,6 +7097,14 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn<Compil
|
||||
"cmidrule",
|
||||
texlang::command::BuiltIn::new_execution(cmidrule_primitive),
|
||||
);
|
||||
built_ins.insert(
|
||||
"cline",
|
||||
texlang::command::BuiltIn::new_execution(cline_primitive),
|
||||
);
|
||||
built_ins.insert(
|
||||
"multicolumn",
|
||||
texlang::command::BuiltIn::new_execution(multicolumn_primitive),
|
||||
);
|
||||
built_ins.insert(
|
||||
"url",
|
||||
texlang::command::BuiltIn::new_execution(url_primitive),
|
||||
|
||||
@@ -1050,6 +1050,77 @@ fn arxiv_table_rules_follow_a_narrow_centered_table() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multicolumn_and_cmidrule_render_spans() {
|
||||
let source = r"\documentclass{article}
|
||||
\begin{document}
|
||||
\begin{tabular}{lll}
|
||||
\toprule
|
||||
\multicolumn{2}{c}{Part} \\
|
||||
\cmidrule(r){1-2}
|
||||
Name & Description & Size ($\mu$m) \\
|
||||
\midrule
|
||||
Dendrite & Input terminal & 100 \\
|
||||
\bottomrule
|
||||
\end{tabular}
|
||||
\end{document}";
|
||||
let value = fresh_preview(source, "multicolumn.tex");
|
||||
assert_eq!(value["status"], "ok", "{}", value["message"]);
|
||||
let svg = page_svg(&value, 0);
|
||||
let mut rules = Vec::new();
|
||||
for fragment in svg.split("<line ").skip(1) {
|
||||
let tag = fragment.split('>').next().unwrap_or(fragment);
|
||||
let read = |name: &str| {
|
||||
tag.split(&format!("{name}=\""))
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split('"').next())
|
||||
.and_then(|value| value.parse::<f64>().ok())
|
||||
};
|
||||
if let (Some(x1), Some(x2), Some(y1), Some(y2)) =
|
||||
(read("x1"), read("x2"), read("y1"), read("y2"))
|
||||
&& x2 > x1 + 10.0
|
||||
&& (y1 - y2).abs() < 0.01
|
||||
{
|
||||
rules.push((x1, x2, y1));
|
||||
}
|
||||
}
|
||||
assert_eq!(rules.len(), 4, "expected four table rules, got {rules:?}");
|
||||
let full = rules
|
||||
.iter()
|
||||
.max_by(|left, right| (left.1 - left.0).total_cmp(&(right.1 - right.0)))
|
||||
.copied()
|
||||
.expect("full-width rule");
|
||||
let short = rules
|
||||
.iter()
|
||||
.find(|(x1, x2, _)| *x2 - *x1 < (full.1 - full.0) * 0.9)
|
||||
.copied()
|
||||
.expect("partial cmidrule");
|
||||
assert!(
|
||||
(short.0 - full.0).abs() < 1.0,
|
||||
"partial rule should start at the first column: {short:?}"
|
||||
);
|
||||
assert!(
|
||||
short.1 < full.1 - 5.0,
|
||||
"partial rule extends across the whole table: {short:?}"
|
||||
);
|
||||
let mut part_x = None;
|
||||
for fragment in svg.split("<text ").skip(1) {
|
||||
let tag = fragment.split('>').next().unwrap_or(fragment);
|
||||
if fragment.contains(">Part</text>") {
|
||||
part_x = tag
|
||||
.split("x=\"")
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split('"').next())
|
||||
.and_then(|value| value.parse::<f64>().ok());
|
||||
}
|
||||
}
|
||||
let part_x = part_x.expect("Part text in SVG");
|
||||
assert!(
|
||||
part_x < full.0 + (full.1 - full.0) / 2.0,
|
||||
"multicolumn text should be centered over the first two columns, Part x={part_x}, rule={full:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn abstract_environment_gets_an_unumbered_heading() {
|
||||
let source = r"\documentclass{article}
|
||||
|
||||
Reference in new issue
Block a user