1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
#[cfg(feature = "tty")]
use crossterm::style::{Stylize, style};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use super::content_split::measure_text_width;
use super::content_split::split_line;
use crate::cell::Cell;
use crate::row::Row;
use crate::style::{CellAlignment, VerticalAlignment};
#[cfg(feature = "tty")]
use crate::style::{map_attribute, map_color};
use crate::table::Table;
use crate::utils::ColumnDisplayInfo;
use crate::utils::spanning::SpanTracker;
pub fn delimiter(cell: &Cell, info: &ColumnDisplayInfo, table: &Table) -> char {
// Determine, which delimiter should be used
if let Some(delimiter) = cell.delimiter {
delimiter
} else if let Some(delimiter) = info.delimiter {
delimiter
} else if let Some(delimiter) = table.delimiter {
delimiter
} else {
' '
}
}
/// Returns the formatted content of the table.
/// The content is organized in the following structure
///
/// tc stands for table content and represents the returned value
/// ``` text
/// column1 column2
/// row1 tc[0][0][0] tc[0][0][1] <-line1
/// tc[0][1][0] tc[0][1][1] <-line2
/// tc[0][2][0] tc[0][2][1] <-line3
///
/// row2 tc[1][0][0] tc[1][0][1] <-line1
/// tc[1][1][0] tc[1][1][1] <-line2
/// tc[1][2][0] tc[1][2][1] <-line3
/// ```
///
/// The strings for each row will be padded and aligned according to their respective column.
pub fn format_content(table: &Table, display_info: &[ColumnDisplayInfo]) -> Vec<Vec<Vec<String>>> {
// The content of the whole table
let mut table_content = Vec::with_capacity(table.rows.len() + 1);
let mut span_tracker = SpanTracker::new();
// Format table header if it exists
if let Some(header) = table.header() {
table_content.push(format_row(
header,
display_info,
table,
0,
&mut span_tracker,
));
span_tracker.advance_row(1);
}
for (row_index, row) in table.rows.iter().enumerate() {
let actual_row_index = if table.header.is_some() {
row_index + 1
} else {
row_index
};
table_content.push(format_row(
row,
display_info,
table,
actual_row_index,
&mut span_tracker,
));
// Advance row AFTER processing, so rowspan content is available for the next row
span_tracker.advance_row(actual_row_index + 1);
}
table_content
}
pub(crate) fn format_row(
row: &Row,
display_infos: &[ColumnDisplayInfo],
table: &Table,
row_index: usize,
span_tracker: &mut SpanTracker,
) -> Vec<Vec<String>> {
// The content of this specific row
// We'll build a vector where each element represents a column position
// For colspan cells, we'll store the formatted content once and mark the spanned positions
let mut temp_row_content: Vec<Option<Vec<String>>> = vec![None; display_infos.len()];
// Track which columns are part of a colspan (maps col_index -> colspan)
let mut colspan_map: Vec<Option<usize>> = vec![None; display_infos.len()];
// Track vertical alignment for each column (for applying after we know max_lines)
let mut vertical_alignments: Vec<Option<VerticalAlignment>> = vec![None; display_infos.len()];
let mut col_index = 0;
// Process each cell in the row
for cell in &row.cells {
// Skip column positions that are occupied by rowspan from above
while col_index < display_infos.len()
&& span_tracker.is_col_occupied_by_rowspan(row_index, col_index)
{
// This position is occupied by a rowspan, mark it as such
temp_row_content[col_index] = Some(vec!["".to_string()]);
col_index += 1;
}
if col_index >= display_infos.len() {
break;
}
let colspan = cell.colspan() as usize;
let rowspan = cell.rowspan();
// Get the spanned column infos
let spanned_infos: Vec<&ColumnDisplayInfo> = display_infos
.iter()
.skip(col_index)
.take(colspan)
.filter(|info| !info.is_hidden)
.collect();
if spanned_infos.is_empty() {
col_index += colspan;
continue;
}
// Calculate combined width for colspan cells
// Sum the content widths, PLUS add 3 chars per span for the missing borders " | " between columns
// If there were 2 separate cells, they'd have " | " (3 chars) between them
// Use the number of visible columns, not the logical colspan (hidden columns don't need border compensation)
let visible_colspan_count = spanned_infos.len();
let borders_between = (visible_colspan_count.saturating_sub(1)) as u16 * 3;
let combined_content_width: u16 = spanned_infos
.iter()
.map(|info| info.content_width)
.sum::<u16>()
+ borders_between;
let combined_padding_left: u16 = spanned_infos
.first()
.map(|info| info.padding.0)
.unwrap_or(0);
let combined_padding_right: u16 =
spanned_infos.last().map(|info| info.padding.1).unwrap_or(0);
// Create a temporary ColumnDisplayInfo for the spanned cell
let spanned_info = ColumnDisplayInfo {
padding: (combined_padding_left, combined_padding_right),
delimiter: spanned_infos[0].delimiter,
content_width: combined_content_width,
cell_alignment: cell.alignment.or(spanned_infos[0].cell_alignment),
vertical_alignment: cell
.vertical_alignment
.or(spanned_infos[0].vertical_alignment),
is_hidden: false,
};
// Format the cell content
let mut cell_lines = Vec::new();
let cell_delimiter = delimiter(cell, &spanned_info, table);
// Iterate over each line and split it into multiple lines if necessary.
// Newlines added by the user will be preserved.
for line in cell.content.iter() {
if measure_text_width(line) > combined_content_width.into() {
let mut parts = split_line(line, &spanned_info, cell_delimiter);
cell_lines.append(&mut parts);
} else {
cell_lines.push(line.into());
}
}
// Remove all unneeded lines of this cell, if the row's height is capped to a certain
// amount of lines and there're too many lines in this cell.
// This then truncates and inserts a '...' string at the end of the last line to indicate
// that the cell has been truncated.
if let Some(lines) = row.max_height {
if cell_lines.len() > lines {
// We already have to many lines. Cut off the surplus lines.
let _ = cell_lines.split_off(lines);
// Directly access the last line.
let last_line = cell_lines
.get_mut(lines - 1)
.expect("We know it's this long.");
// Truncate any ansi codes, as the following cutoff might break ansi code
// otherwise anyway. This could be handled smarter, but it's simple and just works.
#[cfg(feature = "custom_styling")]
{
let stripped = console::strip_ansi_codes(last_line).to_string();
*last_line = stripped;
}
let max_width: usize = combined_content_width.into();
let indicator_width = table.truncation_indicator.width();
let mut truncate_at = 0;
// Start the accumulated_width with the indicator_width, which is the minimum width
// we may show anyway.
let mut accumulated_width = indicator_width;
let mut full_string_fits = false;
// Leave these print statements in here in case we ever have to debug this annoying
// stuff again.
//println!("\nSTART:");
//println!("\nMax width: {max_width}, Indicator width: {indicator_width}");
//println!("Full line hex: {last_line}");
//println!(
// "Full line hex: {}",
// last_line
// .as_bytes()
// .iter()
// .map(|byte| format!("{byte:02x}"))
// .collect::<Vec<String>>()
// .join(", ")
//);
// Iterate through the UTF-8 graphemes.
// Check the `split_long_word` inline function docs to see why we're using
// graphemes.
// **Note:** The `index` here is the **byte** index. So we cannot just
// String::truncate afterwards. We have to convert to a byte vector to perform
// the truncation first.
let mut grapheme_iter = last_line.grapheme_indices(true).peekable();
while let Some((index, grapheme)) = grapheme_iter.next() {
// Leave these print statements in here in case we ever have to debug this
// annoying stuff again
//println!(
// "Current index: {index}, Next grapheme: {grapheme} (width: {})",
// grapheme.width()
//);
//println!(
// "Next grapheme hex: {}",
// grapheme
// .as_bytes()
// .iter()
// .map(|byte| format!("{byte:02x}"))
// .collect::<Vec<String>>()
// .join(", ")
//);
// Immediately save where to truncate in case this grapheme doesn't fit.
// The index is just before the current grapheme actually starts.
truncate_at = index;
// Check if the next grapheme would break the boundary of the allowed line
// length.
let new_width = accumulated_width + grapheme.width();
//println!(
// "Next width: {new_width}/{max_width} ({accumulated_width} + {})",
// grapheme.width()
//);
if new_width > max_width {
//println!(
// "Breaking: {:?}",
// accumulated_width + grapheme.width() > max_width
//);
break;
}
// The grapheme seems to fit. Save the index and check the next one.
accumulated_width += grapheme.width();
// This is a special case.
// We reached the last char, meaning that full last line + the indicator fit.
if grapheme_iter.peek().is_none() {
full_string_fits = true
}
}
// Only do any truncation logic if the line doesn't fit.
if !full_string_fits {
// Truncate the string at the byte index just behind the last valid grapheme
// and overwrite the last line with the new truncated string.
let mut last_line_bytes = last_line.clone().into_bytes();
last_line_bytes.truncate(truncate_at);
let new_last_line = String::from_utf8(last_line_bytes)
.expect("We cut at an exact char boundary");
*last_line = new_last_line;
}
// Push the truncation indicator.
last_line.push_str(&table.truncation_indicator);
}
}
// Iterate over all generated lines of this cell and align them
let aligned_cell_lines: Vec<String> = cell_lines
.iter()
.map(|line| align_line(table, &spanned_info, cell, line.to_string()))
.collect();
// Track vertical alignment for this cell
// Cell setting overrides column setting, default is Top
let v_align = cell
.vertical_alignment
.or(spanned_infos[0].vertical_alignment)
.unwrap_or(VerticalAlignment::Top);
vertical_alignments[col_index] = Some(v_align);
// Store content in temp_row_content for this row
// Clone for rowspan registration if needed
let content_for_storage = aligned_cell_lines.clone();
temp_row_content[col_index] = Some(aligned_cell_lines);
// Register rowspan if needed, caching the formatted content for subsequent rows
if rowspan > 1 {
span_tracker.register_rowspan(
row_index,
col_index,
rowspan,
colspan as u16,
Some(content_for_storage),
v_align,
);
}
for i in 0..colspan {
if col_index + i < colspan_map.len() {
if i == 0 {
colspan_map[col_index + i] = Some(colspan);
} else {
colspan_map[col_index + i] = Some(0); // Mark as spanned (0 means part of colspan)
}
}
}
// Advance column index by colspan
col_index += colspan;
}
// Fill in any remaining positions that weren't covered (shouldn't happen in valid tables)
for i in col_index..display_infos.len() {
if temp_row_content[i].is_none() && !span_tracker.is_col_occupied_by_rowspan(row_index, i) {
if display_infos[i].is_hidden {
continue;
}
temp_row_content[i] = Some(vec![" ".repeat(display_infos[i].width().into())]);
}
}
// Now convert from column-based to line-based structure
// Find the maximum number of lines across all cells
let max_lines = temp_row_content
.iter()
.filter_map(|cell| cell.as_ref().map(|lines| lines.len()))
.max()
.unwrap_or(0);
// Apply vertical alignment to each cell
for (col_idx, cell_content) in temp_row_content.iter_mut().enumerate() {
if let Some(lines) = cell_content {
let v_align = vertical_alignments[col_idx].unwrap_or(VerticalAlignment::Top);
let content_height = lines.len();
if content_height < max_lines {
// Calculate the width for empty lines
// For colspan cells, need to calculate combined width
let colspan = colspan_map[col_idx].unwrap_or(1);
let line_width = if colspan > 1 {
// Colspan cell - calculate combined width
let visible_cols: Vec<&ColumnDisplayInfo> = display_infos
[col_idx..(col_idx + colspan).min(display_infos.len())]
.iter()
.filter(|info| !info.is_hidden)
.collect();
let width_sum: usize =
visible_cols.iter().map(|info| info.width() as usize).sum();
let visible_colspan_count = visible_cols.len();
width_sum + visible_colspan_count.saturating_sub(1)
} else {
// Normal cell - use column width
display_infos[col_idx].width() as usize
};
let empty_line = " ".repeat(line_width);
*lines = apply_vertical_alignment(lines.clone(), max_lines, v_align, empty_line);
}
}
}
let mut row_content = Vec::with_capacity(max_lines);
// Build the row content line by line
for line_index in 0..max_lines {
let mut line = Vec::with_capacity(display_infos.len());
let mut current_col = 0;
while current_col < display_infos.len() {
if display_infos[current_col].is_hidden {
current_col += 1;
continue;
}
// Check if this position is occupied by a rowspan from a PREVIOUS row
// Starting row content is handled through temp_row_content
if let Some((start_row, start_col, colspan)) =
span_tracker.get_rowspan_start(row_index, current_col)
{
// Calculate combined width for this rowspan
let spanned_infos: Vec<&ColumnDisplayInfo> = display_infos
.iter()
.skip(start_col)
.take(colspan as usize)
.filter(|info| !info.is_hidden)
.collect();
let width_sum: usize = spanned_infos.iter().map(|info| info.width() as usize).sum();
let combined_width = width_sum + (colspan as usize - 1);
let empty_line = " ".repeat(combined_width);
// Get content and calculate display position based on vertical alignment
if let Some(cached_content) = span_tracker.get_rowspan_content(row_index, start_col)
{
let content_height = cached_content.len();
let row_within_span = row_index - start_row;
let content_offset = span_tracker.get_rowspan_content_offset(
start_row,
start_col,
content_height,
);
// Check if this row should show content based on vertical alignment
// Content is shown starting at row `content_offset` within the span
if row_within_span == content_offset {
// This row shows the content - display the appropriate line
if let Some(content) = cached_content.get(line_index) {
line.push(content.clone());
} else {
// More lines in this row than content has
line.push(empty_line.clone());
}
} else {
// This row is padding (before or after content based on alignment)
line.push(empty_line.clone());
}
} else {
// Fallback: empty space
line.push(empty_line);
}
// Advance by colspan to skip all columns in the rowspan
current_col += colspan as usize;
continue;
}
// Check if this column has content
if let Some(cell_lines) = &temp_row_content[current_col] {
// Check if this cell spans multiple columns
let colspan = colspan_map[current_col].unwrap_or(1);
// Check if this is a rowspan cell that should display content in a later row
// (based on vertical alignment)
let should_show_content = if let Some((_, start_col, _)) =
span_tracker.get_rowspan_start_including_self(row_index, current_col)
{
// This is a rowspan starting at this row
// Check if content should be displayed here based on vertical alignment
let content_height = cell_lines.len();
let content_offset = span_tracker.get_rowspan_content_offset(
row_index,
start_col,
content_height,
);
content_offset == 0 // Only show if content starts at row 0 (this row)
} else {
true // Normal cell, always show
};
// Get empty line for this column's width
let empty_width = if colspan == 1 {
display_infos[current_col].width() as usize
} else {
let visible_cols: Vec<&ColumnDisplayInfo> = display_infos
[current_col..(current_col + colspan).min(display_infos.len())]
.iter()
.filter(|info| !info.is_hidden)
.collect();
let width_sum: usize =
visible_cols.iter().map(|info| info.width() as usize).sum();
let visible_colspan_count = visible_cols.len();
width_sum + visible_colspan_count.saturating_sub(1)
};
if colspan == 1 {
// Normal cell
if should_show_content {
if let Some(content) = cell_lines.get(line_index) {
line.push(content.clone());
} else {
line.push(" ".repeat(display_infos[current_col].width().into()));
}
} else {
line.push(" ".repeat(empty_width));
}
current_col += 1;
} else {
// Colspan cell - the content is already formatted to the combined width
if should_show_content {
if let Some(content) = cell_lines.get(line_index) {
line.push(content.clone());
} else {
line.push(" ".repeat(empty_width));
}
} else {
line.push(" ".repeat(empty_width));
}
// Skip the spanned columns - they're already included in the content above
// We need to advance through colspan-1 more logical columns
// For visible columns, add empty strings (borders will be drawn correctly)
let mut logical_cols_skipped = 0;
while logical_cols_skipped < colspan - 1
&& current_col + 1 < display_infos.len()
{
current_col += 1;
logical_cols_skipped += 1;
// Only add empty string for visible columns (hidden ones are skipped by outer loop)
if !display_infos[current_col].is_hidden {
line.push("".to_string());
}
}
current_col += 1;
}
} else {
// No content for this column, fill with spaces
line.push(" ".repeat(display_infos[current_col].width().into()));
current_col += 1;
}
}
row_content.push(line);
}
row_content
}
/// Apply the alignment for a column. Alignment can be either Left/Right/Center.
/// In every case all lines will be exactly the same character length `info.width - padding long`
/// This is needed, so we can simply insert it into the border frame later on.
/// Padding is applied in this function as well.
#[allow(unused_variables)]
fn align_line(table: &Table, info: &ColumnDisplayInfo, cell: &Cell, mut line: String) -> String {
let content_width = info.content_width;
let remaining: usize = usize::from(content_width).saturating_sub(measure_text_width(&line));
// Apply the styling before aligning the line, if the user requests it.
// That way non-delimiter whitespaces won't have stuff like underlines.
#[cfg(feature = "tty")]
if table.should_style() && table.style_text_only {
line = style_line(line, cell);
}
// Determine the alignment of the column cells.
// Cell settings overwrite the columns Alignment settings.
// Default is Left
let alignment = if let Some(alignment) = cell.alignment {
alignment
} else if let Some(alignment) = info.cell_alignment {
alignment
} else {
CellAlignment::Left
};
// Apply left/right/both side padding depending on the alignment of the column
match alignment {
CellAlignment::Left => {
line += &" ".repeat(remaining);
}
CellAlignment::Right => {
line = " ".repeat(remaining) + &line;
}
CellAlignment::Center => {
let left_padding = (remaining as f32 / 2f32).ceil() as usize;
let right_padding = (remaining as f32 / 2f32).floor() as usize;
line = " ".repeat(left_padding) + &line + &" ".repeat(right_padding);
}
}
line = pad_line(&line, info);
#[cfg(feature = "tty")]
if table.should_style() && !table.style_text_only {
return style_line(line, cell);
}
line
}
/// Apply the column's padding to this line
fn pad_line(line: &str, info: &ColumnDisplayInfo) -> String {
let mut padded_line = String::new();
padded_line += &" ".repeat(info.padding.0.into());
padded_line += line;
padded_line += &" ".repeat(info.padding.1.into());
padded_line
}
/// Apply vertical alignment to cell content.
/// Pads the content with empty lines at top/bottom to achieve the desired alignment.
fn apply_vertical_alignment(
content_lines: Vec<String>,
total_height: usize,
alignment: VerticalAlignment,
empty_line: String,
) -> Vec<String> {
let content_height = content_lines.len();
if content_height >= total_height {
return content_lines;
}
let padding_needed = total_height - content_height;
match alignment {
VerticalAlignment::Top => {
let mut result = content_lines;
result.resize(total_height, empty_line);
result
}
VerticalAlignment::Bottom => {
let mut result = vec![empty_line; padding_needed];
result.extend(content_lines);
result
}
VerticalAlignment::Middle => {
let top_padding = padding_needed / 2;
let mut result = vec![empty_line.clone(); top_padding];
result.extend(content_lines);
result.resize(total_height, empty_line);
result
}
}
}
#[cfg(feature = "tty")]
fn style_line(line: String, cell: &Cell) -> String {
// Just return the line, if there's no need to style.
if cell.fg.is_none() && cell.bg.is_none() && cell.attributes.is_empty() {
return line;
}
let mut content = style(line);
// Apply text color
if let Some(color) = cell.fg {
content = content.with(map_color(color));
}
// Apply background color
if let Some(color) = cell.bg {
content = content.on(map_color(color));
}
for attribute in cell.attributes.iter() {
content = content.attribute(map_attribute(*attribute));
}
content.to_string()
}