Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/cortex-core/src/markdown/table/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,29 @@ mod tests {
assert!(table.column_widths[1] >= 20);
}

#[test]
fn test_column_width_distribution_preserves_available_space() {
let mut builder = TableBuilder::new();
builder.start_header();
builder.add_cell("A A A".to_string());
builder.add_cell("B B B".to_string());
builder.add_cell("C C C".to_string());
builder.end_header();

builder.start_row();
builder.add_cell("aa bb cc".to_string());
builder.add_cell("dd ee ff".to_string());
builder.add_cell("gg hh ii".to_string());
builder.end_row();

let mut table = builder.build();
let max_width = 21;
table.calculate_column_widths(max_width);

// Three columns have 4 border chars and 6 padding chars, leaving 11 content chars.
assert_eq!(table.column_widths.iter().sum::<usize>(), 11);
}

#[test]
fn test_missing_cells_in_rows() {
let mut builder = TableBuilder::new();
Expand Down
28 changes: 26 additions & 2 deletions src/cortex-core/src/markdown/table/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,11 +209,35 @@ impl Table {
self.column_widths = min_widths.clone();

if pref_extra > 0 {
let mut allocated_total = 0;
let mut remainders = Vec::with_capacity(num_cols);

for i in 0..num_cols {
let col_extra = pref_widths[i].saturating_sub(min_widths[i]);
let allocated =
(col_extra as f64 / pref_extra as f64 * extra_space as f64) as usize;
let weighted_extra = col_extra * extra_space;
let allocated = weighted_extra / pref_extra;
let remainder = weighted_extra % pref_extra;

self.column_widths[i] += allocated;
allocated_total += allocated;

if allocated < col_extra {
remainders.push((i, remainder));
}
}

let mut remaining = extra_space.saturating_sub(allocated_total);
remainders.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));

for (i, _) in remainders {
if remaining == 0 {
break;
}

if self.column_widths[i] < pref_widths[i] {
self.column_widths[i] += 1;
remaining -= 1;
}
}
}
} else {
Expand Down