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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
//! Tables.
//!
//! Port of upstream `rich/table.py` (core subset). A [`Table`] lays out columns
//! and rows inside a box, sizing each column to its widest cell.
//!
//! Scope: headers, rows, box choice (with legacy/ASCII substitution), per-cell
//! padding, **`pad_edge`** + **`show_edge`** + **`collapse_padding`**, header
//! styling (incl. a per-column header-content span and a per-column header-cell
//! fill), a **table-level style** + **border style**,
//! multi-line/wrapped cells (with **ellipsis overflow**), **shrink-to-fit** +
//! **expand** column widths, per-column justify, **explicit width**, per-column
//! **`ratio`/`min_width`/`max_width`**, **per-column style**, **`no_wrap`**,
//! title, caption, and `show_lines`. Deferred (tracked in the Table issue): the
//! rare width-0 column padding edge.
use crate::cells::{cell_len, set_cell_size};
use crate::console::{Console, ConsoleOptions, Justify, Overflow};
use crate::protocol::{LineRenderable, Renderable};
use crate::r#box::{Box as BoxSet, RowLevel, HEAVY_HEAD};
use crate::segment::Segment;
use crate::style::Style;
use crate::text::{Text, DEFAULT_TAB_SIZE};
use crate::theme::Theme;
/// A single column definition. Mirrors the used subset of `rich.table.Column`.
struct Column {
header: String,
justify: Justify,
/// An explicit content width; when set, the column doesn't shrink to fit.
width: Option<usize>,
/// A style applied to this column's body cells.
style: Style,
/// An extra style span applied to the header *content* only (over the base
/// `header_style`), leaving the header padding as `header_style`. Mirrors
/// upstream stylizing the heading `Text` (e.g. `markdown.table.header`).
header_content_style: Option<Style>,
/// A per-column header *cell* style — combined over the table-level
/// `header_style` to fill the whole header cell (content + padding). Port of
/// `Column.header_style` (as used by e.g. rich-cli's numeric columns).
header_fill: Option<Style>,
/// When set, the column flexes to this share of the free width when the table
/// is `expand`ed (port of `Column.ratio`; makes the column "flexible").
ratio: Option<usize>,
/// A floor on the column's content width (port of `Column.min_width`).
min_width: Option<usize>,
/// A cap on the column's content width — wider cells wrap (port of
/// `Column.max_width`).
max_width: Option<usize>,
/// When set, cells are never wrapped — they crop to one line (with ellipsis).
no_wrap: bool,
}
/// A grid of cells rendered inside a box. Mirrors `rich.table.Table`.
pub struct Table {
columns: Vec<Column>,
rows: Vec<Vec<String>>,
box_set: BoxSet,
show_header: bool,
show_lines: bool,
show_edge: bool,
pad_edge: bool,
collapse_padding: bool,
expand: bool,
title: Option<String>,
caption: Option<String>,
padding: (usize, usize, usize, usize),
header_style: Style,
border_style: Style,
style: Style,
}
impl Default for Table {
fn default() -> Self {
Table {
columns: Vec::new(),
rows: Vec::new(),
box_set: HEAVY_HEAD,
show_header: true,
show_lines: false,
show_edge: true,
pad_edge: true,
collapse_padding: false,
expand: false,
title: None,
caption: None,
padding: (0, 1, 0, 1),
header_style: Style::parse("bold").expect("valid built-in style"),
border_style: Style::new(),
style: Style::new(),
}
}
}
impl Table {
pub fn new() -> Self {
Table::default()
}
/// Choose the box-drawing set.
pub fn box_set(mut self, box_set: BoxSet) -> Self {
self.box_set = box_set;
self
}
/// Style the box border (edges + dividers). Composed over the table-level
/// style: `border = style + border_style`. Port of `Table(border_style=…)`.
pub fn border_style(mut self, style: Style) -> Self {
self.border_style = style;
self
}
/// Whether to render the header row.
pub fn show_header(mut self, show: bool) -> Self {
self.show_header = show;
self
}
/// Expand the table to fill the available width.
pub fn expand(mut self, expand: bool) -> Self {
self.expand = expand;
self
}
/// Draw a separator line between each body row.
pub fn show_lines(mut self, show: bool) -> Self {
self.show_lines = show;
self
}
/// Draw the outer box edges (top/bottom borders + left/right glyphs). When
/// off, only the internal dividers and content remain. Port of `show_edge`.
pub fn show_edge(mut self, show: bool) -> Self {
self.show_edge = show;
self
}
/// Pad the outer cell edges. When off, the first column drops its left pad
/// and the last column its right pad. Port of `pad_edge`.
pub fn pad_edge(mut self, pad: bool) -> Self {
self.pad_edge = pad;
self
}
/// Merge adjacent cell padding: an interior column's left pad is reduced by
/// the previous column's right pad. Port of `collapse_padding`.
pub fn collapse_padding(mut self, collapse: bool) -> Self {
self.collapse_padding = collapse;
self
}
/// Default style for the whole table. Upstream applies it as the base of the
/// border style (`border_style = style + border_style`); cell content keeps
/// its own styles. Port of `Table(style=…)`.
pub fn style(mut self, style: Style) -> Self {
self.style = style;
self
}
/// The `(left, right)` padding for column `index` of `ncols`. Port of
/// `_get_padding_width` (collapse) combined with the `pad_edge` edge drops.
fn cell_padding(&self, index: usize, ncols: usize) -> (usize, usize) {
let (_, pr, _, pl) = self.padding;
// collapse_padding: interior columns shed the overlap with the previous
// column's right pad.
let mut left = if self.collapse_padding && index > 0 {
pl.saturating_sub(pr)
} else {
pl
};
let mut right = pr;
// pad_edge: the outer edges lose their padding.
if !self.pad_edge && index == 0 {
left = 0;
}
if !self.pad_edge && index + 1 == ncols {
right = 0;
}
(left, right)
}
/// A centered title rendered above the table.
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
/// A centered caption rendered below the table.
pub fn caption(mut self, caption: impl Into<String>) -> Self {
self.caption = Some(caption.into());
self
}
/// Add a left-justified column with the given header.
pub fn add_column(&mut self, header: impl Into<String>) -> &mut Self {
self.add_column_justify(header, Justify::Left)
}
/// Add a column with an explicit justification.
pub fn add_column_justify(&mut self, header: impl Into<String>, justify: Justify) -> &mut Self {
self.columns.push(Column {
header: header.into(),
justify,
width: None,
style: Style::new(),
header_content_style: None,
header_fill: None,
ratio: None,
min_width: None,
max_width: None,
no_wrap: false,
});
self
}
/// Pin the most-recently-added column to an explicit content width. Content
/// wider than this wraps (with ellipsis overflow) instead of shrinking the
/// column. Chain after `add_column`.
pub fn column_width(&mut self, width: usize) -> &mut Self {
if let Some(column) = self.columns.last_mut() {
column.width = Some(width);
}
self
}
/// Give the most-recently-added column a flex `ratio`: when the table is
/// `expand`ed, ratio columns share the free width in proportion. Chain after
/// `add_column`. Port of `Column.ratio`.
pub fn column_ratio(&mut self, ratio: usize) -> &mut Self {
if let Some(column) = self.columns.last_mut() {
column.ratio = Some(ratio);
}
self
}
/// Set a minimum content width on the most-recently-added column. Chain after
/// `add_column`. Port of `Column.min_width`.
pub fn column_min_width(&mut self, min_width: usize) -> &mut Self {
if let Some(column) = self.columns.last_mut() {
column.min_width = Some(min_width);
}
self
}
/// Set a maximum content width on the most-recently-added column — wider
/// cells wrap. Chain after `add_column`. Port of `Column.max_width`.
pub fn column_max_width(&mut self, max_width: usize) -> &mut Self {
if let Some(column) = self.columns.last_mut() {
column.max_width = Some(max_width);
}
self
}
/// Apply a style to the most-recently-added column's body cells. Chain after
/// `add_column`.
pub fn column_style(&mut self, style: Style) -> &mut Self {
if let Some(column) = self.columns.last_mut() {
column.style = style;
}
self
}
/// Style the most-recently-added column's header *content* (the visible
/// characters), leaving its padding as the base `header_style`. Chain after
/// `add_column`. Mirrors upstream stylizing the heading `Text`.
pub fn column_header_style(&mut self, style: Style) -> &mut Self {
if let Some(column) = self.columns.last_mut() {
column.header_content_style = Some(style);
}
self
}
/// Style the most-recently-added column's whole header *cell* (content +
/// padding), combined over the table-level `header_style`. Chain after
/// `add_column`. Port of `Column.header_style`.
pub fn column_header_fill(&mut self, style: Style) -> &mut Self {
if let Some(column) = self.columns.last_mut() {
column.header_fill = Some(style);
}
self
}
/// Mark the most-recently-added column `no_wrap`: its cells crop to a single
/// line (with ellipsis) instead of wrapping. Chain after `add_column`.
pub fn column_no_wrap(&mut self) -> &mut Self {
if let Some(column) = self.columns.last_mut() {
column.no_wrap = true;
}
self
}
/// Add a row of cells (extra cells are ignored; missing cells render empty).
pub fn add_row(&mut self, cells: &[&str]) -> &mut Self {
self.rows
.push(cells.iter().map(|s| s.to_string()).collect());
self
}
/// The measured content width of each column (widest cell, header included).
/// Widest *line* of a cell, not the width of the whole string.
///
/// A cell spanning several lines occupies its widest line, exactly as
/// `Measurement.get` on a `Text` does. Measuring the raw string instead made
/// a multi-line cell as wide as all its lines **summed** — `\n` measures
/// zero, so nothing capped it — and a quoted CSV cell holding two sentences
/// blew its column out to 31 cells where upstream gives 23.
fn block_width(text: &str) -> usize {
text.split('\n').map(cell_len).max().unwrap_or(0)
}
fn max_content_widths(&self) -> Vec<usize> {
let mut widths = vec![0usize; self.columns.len()];
for (index, column) in self.columns.iter().enumerate() {
if self.show_header {
widths[index] = Self::block_width(&column.header);
}
}
for row in &self.rows {
for (index, cell) in row.iter().enumerate() {
if index < widths.len() {
widths[index] = widths[index].max(Self::block_width(cell));
}
}
}
widths
}
/// The rendered width (content + padding) of each column, shrinking the
/// widest columns to fit `available` when necessary. Port of the non-flexible
/// path of `Table._calculate_column_widths` + `_collapse_widths`.
fn column_widths(&self, available: usize) -> Vec<usize> {
let ncols = self.columns.len();
// A fixed-width column uses its declared width; others measure content,
// clamped to the column's [min_width, max_width]. Port of `_measure_column`.
let content = self.max_content_widths();
let mut widths: Vec<i64> = self
.columns
.iter()
.zip(&content)
.enumerate()
.map(|(index, (column, &measured))| {
let (pl, pr) = self.cell_padding(index, ncols);
let content_width = match column.width {
Some(w) => w,
None => {
let mut w = measured;
if let Some(min) = column.min_width {
w = w.max(min);
}
if let Some(max) = column.max_width {
w = w.min(max);
}
w
}
};
(content_width + pl + pr) as i64
})
.collect();
// Expand with explicit ratios: flexible (ratio) columns share the free
// width in proportion, fixed columns keep their measured width. Port of
// the `if self.expand: … if any(ratios)` block of `_calculate_column_widths`.
if self.expand {
let ratios: Vec<i64> = self
.columns
.iter()
.filter(|c| c.ratio.is_some())
.map(|c| c.ratio.unwrap() as i64)
.collect();
if ratios.iter().any(|&r| r > 0) {
let fixed_widths: Vec<i64> = widths
.iter()
.zip(&self.columns)
.map(|(&w, c)| if c.ratio.is_some() { 0 } else { w })
.collect();
let flex_minimum: Vec<i64> = self
.columns
.iter()
.enumerate()
.filter(|(_, c)| c.ratio.is_some())
.map(|(index, c)| {
let (pl, pr) = self.cell_padding(index, ncols);
(c.width.unwrap_or(1) + pl + pr) as i64
})
.collect();
let flexible_width = available as i64 - fixed_widths.iter().sum::<i64>();
let flex_widths = ratio_distribute(flexible_width, &ratios, Some(&flex_minimum));
let mut iter_flex = flex_widths.into_iter();
for (index, column) in self.columns.iter().enumerate() {
if column.ratio.is_some() {
widths[index] = fixed_widths[index] + iter_flex.next().unwrap_or(0);
}
}
}
}
let table_width: i64 = widths.iter().sum();
if table_width > available as i64 {
// Only auto-width, wrapping columns may shrink; fixed and no_wrap
// columns hold their width (no_wrap only yields via the last resort).
let wrapable: Vec<bool> = self
.columns
.iter()
.map(|c| c.width.is_none() && !c.no_wrap)
.collect();
widths = collapse_widths(widths, &wrapable, available as i64);
// Last resort: if fixed columns still overflow, reduce every column
// evenly. Port of `_calculate_column_widths`'s final `ratio_reduce`.
let table_width: i64 = widths.iter().sum();
if table_width > available as i64 {
let excess = table_width - available as i64;
let ratios = vec![1i64; widths.len()];
widths = ratio_reduce(excess, &ratios, &widths, &widths);
}
}
// Expand: distribute the leftover width proportionally. Port of the
// `expand` tail of `_calculate_column_widths` (via `ratio_distribute`).
let table_width: i64 = widths.iter().sum();
if self.expand && table_width < available as i64 && table_width > 0 {
let pad = ratio_distribute(available as i64 - table_width, &widths, None);
for (width, extra) in widths.iter_mut().zip(pad) {
*width += extra;
}
}
widths.into_iter().map(|w| w.max(0) as usize).collect()
}
/// `cell_padding` shrunk so that padding alone can never exceed the width
/// the column was actually allotted.
///
/// When many columns compete for a narrow terminal a column can be squeezed
/// below its own padding. The cell then still emitted a full left and right
/// pad, so every such column spent two cells where its border spent one and
/// the content row grew wider than the table — at 29 columns in an 80-cell
/// terminal the row overflowed by 15 cells and was cropped, taking the
/// right-hand border with it while the border rows kept theirs.
fn cell_padding_fitted(&self, index: usize, ncols: usize, rendered: usize) -> (usize, usize) {
let (mut pl, mut pr) = self.cell_padding(index, ncols);
while pl + pr > rendered {
if pr > pl {
pr -= 1;
} else if pl > 0 {
pl -= 1;
} else {
break;
}
}
(pl, pr)
}
/// The effective style for a cell in column `index`: the header style for a
/// header row, else that column's own style.
fn cell_style(&self, index: usize, is_header: bool) -> Style {
if is_header {
// A per-column header cell style is combined over the table-level one.
match self.columns.get(index).and_then(|c| c.header_fill.as_ref()) {
Some(fill) => self.header_style.combine(fill),
None => self.header_style.clone(),
}
} else {
self.columns
.get(index)
.map(|c| c.style.clone())
.unwrap_or_default()
}
}
/// Render one table row (a list of cell strings) into visual lines.
fn render_row(
&self,
theme: &Theme,
cells: &[String],
rendered_widths: &[usize],
is_header: bool,
edges: (char, char, char),
) -> Vec<Vec<Segment>> {
// Horizontal padding is per-column (see `cell_padding`); only the
// top/bottom vertical padding is uniform.
let (pt, _, pb, _) = self.padding;
let (edge_left, edge_vertical, edge_right) = edges;
let border = Some(self.style.combine(&self.border_style));
let ncols = self.columns.len();
// Derived here rather than by the caller so the padding used to lay the
// row out is the same padding the content width was reduced by.
let paddings: Vec<(usize, usize)> = (0..ncols)
.map(|index| {
let rendered = rendered_widths.get(index).copied().unwrap_or(0);
self.cell_padding_fitted(index, ncols, rendered)
})
.collect();
let content_widths: Vec<usize> = rendered_widths
.iter()
.zip(&paddings)
.map(|(w, (pl, pr))| w.saturating_sub(pl + pr))
.collect();
// Render each cell into padded, simplified visual lines.
let mut cell_lines: Vec<Vec<Vec<Segment>>> = Vec::with_capacity(ncols);
let mut height = 1;
for (index, width) in content_widths.iter().enumerate() {
let style = self.cell_style(index, is_header);
let cell_fill = Some(style.clone());
let content = cells.get(index).map(String::as_str).unwrap_or("");
let column = self.columns.get(index);
let justify = column.map(|c| c.justify).unwrap_or(Justify::Left);
let no_wrap = column.map(|c| c.no_wrap).unwrap_or(false);
// A no_wrap cell is one ellipsis-cropped line; otherwise wrap with
// ellipsis overflow (the table default). Then justify + pad.
let wrapped = if no_wrap {
ellipsis_crop(content, *width)
} else {
wrap_cell(content, *width).join("\n")
};
let mut text = Text::new(wrapped).justify(justify);
// Header content carries its own style span over `header_style`; the
// justify/edge padding stays `header_style` (matches upstream).
if is_header {
if let Some(span) = column.and_then(|c| c.header_content_style.clone()) {
let len = text.plain().len();
text.stylize(span, 0, len);
}
}
let mut lines = text.render_lines(theme, &style, Some(*width));
if lines.is_empty() {
lines.push(Vec::new());
}
// Vertical padding (blank content lines top/bottom).
let blank = || Segment::new(" ".repeat(*width), cell_fill.clone());
let mut padded_lines: Vec<Vec<Segment>> = Vec::new();
for _ in 0..pt {
padded_lines.push(vec![blank()]);
}
for line in &lines {
let padded = Segment::adjust_line_length(line, *width, cell_fill.clone());
padded_lines.push(Segment::simplify(&padded));
}
for _ in 0..pb {
padded_lines.push(vec![blank()]);
}
height = height.max(padded_lines.len());
cell_lines.push(padded_lines);
}
// Pad every column to the row height with blank lines.
for (index, lines) in cell_lines.iter_mut().enumerate() {
let fill = Some(self.cell_style(index, is_header));
while lines.len() < height {
lines.push(vec![Segment::new(
" ".repeat(content_widths[index]),
fill.clone(),
)]);
}
}
let last = ncols.saturating_sub(1);
let mut rows_out: Vec<Vec<Segment>> = Vec::with_capacity(height);
// `r` indexes into each column's per-line vector, so a range loop is the
// natural shape here (the columns are iterated with `enumerate`).
#[allow(clippy::needless_range_loop)]
for r in 0..height {
let mut row = Vec::new();
if self.show_edge {
row.push(Segment::new(edge_left.to_string(), border.clone()));
}
for (c, column_lines) in cell_lines.iter().enumerate() {
let fill = Some(self.cell_style(c, is_header));
let (cpl, cpr) = paddings[c];
if cpl > 0 {
row.push(Segment::new(" ".repeat(cpl), fill.clone()));
}
row.extend(column_lines[r].clone());
if cpr > 0 {
row.push(Segment::new(" ".repeat(cpr), fill.clone()));
}
if c != last {
row.push(Segment::new(edge_vertical.to_string(), border.clone()));
} else if self.show_edge {
row.push(Segment::new(edge_right.to_string(), border.clone()));
}
}
rows_out.push(row);
}
rows_out
}
}
impl LineRenderable for Table {
/// Render visual lines in order without retaining the full rendered table.
///
/// Like upstream's `Table.__rich_console__` / `_render` generators, this
/// measures all columns first, then renders only one row block at a time.
/// Lines contain styled segments without a trailing newline. The callback
/// may write each line immediately; its first error stops rendering.
/// The table still owns its source rows for column-width measurement.
fn try_for_each_line<E>(
&self,
console: &Console,
options: &ConsoleOptions,
mut emit: impl FnMut(Vec<Segment>) -> Result<(), E>,
) -> Result<(), E> {
if self.columns.is_empty() {
return emit(vec![Segment::new("", None)]);
}
// Fall back to a terminal-safe box on legacy Windows / non-UTF-8.
let box_set = self.box_set.substitute(
console.legacy_windows(),
console.safe_box(),
console.ascii_only(),
);
let ncols = self.columns.len();
// Borders occupy: (ncols-1) dividers, plus 2 outer edges when shown.
// Port of `_extra_width`.
let extra_width = (if self.show_edge { 2 } else { 0 }) + ncols.saturating_sub(1);
let available = options.max_width.saturating_sub(extra_width);
let rendered_widths = self.column_widths(available);
let border = Some(self.style.combine(&self.border_style));
// Full table width (for centering title/caption): columns + borders.
let table_width: usize = rendered_widths.iter().sum::<usize>() + extra_width;
// Title, centered above the table.
if let Some(title) = self.title.as_ref().filter(|title| !title.is_empty()) {
for line in render_annotation(console, options, title, "table.title", table_width) {
emit(line)?;
}
}
let edge = self.show_edge;
if edge {
emit(vec![Segment::new(
box_set.get_top(&rendered_widths, edge),
border.clone(),
)])?;
}
let head_edges = (box_set.head_left, box_set.head_vertical, box_set.head_right);
let body_edges = (box_set.mid_left, box_set.mid_vertical, box_set.mid_right);
if self.show_header {
let headers: Vec<String> = self.columns.iter().map(|c| c.header.clone()).collect();
for line in self.render_row(
console.theme(),
&headers,
&rendered_widths,
true,
head_edges,
) {
emit(line)?;
}
emit(vec![Segment::new(
box_set.get_row(&rendered_widths, RowLevel::Head, edge),
border.clone(),
)])?;
}
let row_last = self.rows.len().saturating_sub(1);
for (index, row) in self.rows.iter().enumerate() {
for line in self.render_row(console.theme(), row, &rendered_widths, false, body_edges) {
emit(line)?;
}
if self.show_lines && index != row_last {
emit(vec![Segment::new(
box_set.get_row(&rendered_widths, RowLevel::Row, edge),
border.clone(),
)])?;
}
}
if edge {
emit(vec![Segment::new(
box_set.get_bottom(&rendered_widths, edge),
border.clone(),
)])?;
}
// Caption, centered below the table.
if let Some(caption) = self.caption.as_ref().filter(|caption| !caption.is_empty()) {
for line in render_annotation(console, options, caption, "table.caption", table_width) {
emit(line)?;
}
}
Ok(())
}
}
impl crate::protocol::OwnedTableRows for Table {
fn extend_owned_rows(&mut self, mut rows: Vec<Vec<String>>) -> &mut Self {
if self.rows.is_empty() {
self.rows = rows;
} else {
self.rows.append(&mut rows);
}
self
}
}
impl Renderable for Table {
fn rich_render(&self, console: &Console, options: &ConsoleOptions) -> Vec<Segment> {
let mut segments = Vec::new();
let mut first = true;
let result: Result<(), std::convert::Infallible> =
self.try_for_each_line(console, options, |line| {
if !first {
segments.push(Segment::line());
}
first = false;
segments.extend(line);
Ok(())
});
match result {
Ok(()) => segments,
Err(never) => match never {},
}
}
}
/// Wrap `content` to `width` cells with **ellipsis overflow** (the table
/// default): words are broken between, and a single word wider than `width` is
/// cropped with a trailing `…`. Returns one string per visual line.
fn wrap_cell(content: &str, width: usize) -> Vec<String> {
if width == 0 {
return vec![String::new()];
}
// Wrap each line of the cell on its own, as upstream's `Text.wrap` does —
// it splits on newlines before dividing. Handing the whole cell to
// `divide_line` treated the newline as ordinary whitespace worth zero cells,
// so it packed text from two source lines into one "line" that then printed
// as two rows: a 23-cell line inside a 23-cell column came out split.
if content.contains('\n') {
return content
.split('\n')
.flat_map(|line| wrap_cell(line, width))
.collect();
}
// `fold = false`: over-long words stay on their own (overflowing) line,
// which `ellipsis_crop` then trims — matching `Text(overflow="ellipsis")`.
let breaks = crate::wrap::divide_line(content, width, false);
let chars: Vec<char> = content.chars().collect();
let mut lines: Vec<String> = Vec::new();
let mut start = 0;
for stop in breaks {
lines.push(chars[start..stop].iter().collect());
start = stop;
}
lines.push(chars[start..].iter().collect());
// Trailing whitespace is dropped before the overflow check, so a word that
// fills the width exactly isn't spuriously ellipsized by its trailing space.
lines
.iter()
.map(|line| ellipsis_crop(line.trim_end(), width))
.collect()
}
/// Crop `text` to `width` cells, replacing the trailing cell with `…` when it
/// doesn't fit. Port of the `overflow="ellipsis"` path of `Text.truncate`.
fn ellipsis_crop(text: &str, width: usize) -> String {
if cell_len(text) <= width {
return text.to_string();
}
if width == 0 {
return String::new();
}
format!("{}\u{2026}", set_cell_size(text, width - 1))
}
/// Port of `Table.__rich_console__.render_annotation`: markup and emoji are
/// enabled, automatic highlighting is disabled, and long annotations wrap.
fn render_annotation(
console: &Console,
options: &ConsoleOptions,
annotation: &str,
style: &str,
width: usize,
) -> Vec<Vec<Segment>> {
let expanded = console.expand_emoji(annotation);
let mut text = Text::from_markup(&expanded).unwrap_or_else(|_| Text::new(expanded));
text.set_base_style(style);
let overflow = options.overflow.unwrap_or(Overflow::Fold);
let no_wrap = options.no_wrap.unwrap_or(false) || overflow == Overflow::Ignore;
let mut lines = Vec::new();
for mut hard_line in text.split("\n", false, true) {
hard_line.expand_tabs(DEFAULT_TAB_SIZE);
let wrapped = if no_wrap {
vec![hard_line]
} else {
let char_offsets: Vec<usize> = hard_line
.plain()
.char_indices()
.map(|(i, _)| i)
.chain(std::iter::once(hard_line.plain().len()))
.collect();
let breaks: Vec<usize> =
crate::wrap::divide_line(hard_line.plain(), width, overflow == Overflow::Fold)
.into_iter()
.map(|i| char_offsets[i])
.collect();
hard_line.divide(&breaks)
};
for mut line in wrapped {
if overflow != Overflow::Ignore {
// Upstream justifies the Text before rendering its segments.
// This preserves annotation span boundaries while merging the
// base-styled padding with an unstyled title's single run.
line.rstrip();
line.truncate(width, Some(overflow), false);
line.pad_left(width.saturating_sub(line.cell_len()) / 2, ' ');
line.pad_right(width.saturating_sub(line.cell_len()), ' ');
line.truncate(width, Some(overflow), false);
}
lines.push(line.render(console.theme(), console.base_style()));
}
}
lines
}
/// Round half to even (banker's rounding), matching Python's `round`.
fn round_half_even(value: f64) -> i64 {
let floor = value.floor();
let diff = value - floor;
if (diff - 0.5).abs() < 1e-9 {
let f = floor as i64;
if f % 2 == 0 {
f
} else {
f + 1
}
} else {
value.round() as i64
}
}
/// Reduce `values` by `total`, distributed across slots by `ratios` (capped by
/// `maximums`). Direct port of `rich._ratio.ratio_reduce`.
fn ratio_reduce(total: i64, ratios: &[i64], maximums: &[i64], values: &[i64]) -> Vec<i64> {
let ratios: Vec<i64> = ratios
.iter()
.zip(maximums)
.map(|(&r, &m)| if m != 0 { r } else { 0 })
.collect();
let mut total_ratio: i64 = ratios.iter().sum();
if total_ratio == 0 {
return values.to_vec();
}
let mut total_remaining = total;
let mut result = Vec::with_capacity(values.len());
for ((&ratio, &maximum), &value) in ratios.iter().zip(maximums).zip(values) {
if ratio != 0 && total_ratio > 0 {
let distributed = maximum.min(round_half_even(
ratio as f64 * total_remaining as f64 / total_ratio as f64,
));
result.push(value - distributed);
total_remaining -= distributed;
total_ratio -= ratio;
} else {
result.push(value);
}
}
result
}
/// Divide `total` across slots proportionally to `ratios` (ceil each share),
/// each share floored at the matching `minimums` entry when given. Port of
/// `rich._ratio.ratio_distribute`.
fn ratio_distribute(total: i64, ratios: &[i64], minimums: Option<&[i64]>) -> Vec<i64> {
// Upstream zeroes the ratio of any slot whose minimum is 0 (falsy).
let ratios: Vec<i64> = match minimums {
Some(mins) => ratios
.iter()
.zip(mins)
.map(|(&r, &m)| if m != 0 { r } else { 0 })
.collect(),
None => ratios.to_vec(),
};
let mut total_ratio: i64 = ratios.iter().sum();
let mut total_remaining = total;
let mut result = Vec::with_capacity(ratios.len());
for (index, &ratio) in ratios.iter().enumerate() {
let minimum = minimums.map_or(0, |m| m[index]);
let distributed = if total_ratio > 0 {
// ceil(ratio * total_remaining / total_ratio) for positive values,
// then floored at `minimum`.
let numerator = ratio * total_remaining;
let ceil_div = (numerator + total_ratio - 1) / total_ratio;
minimum.max(ceil_div)
} else {
total_remaining
};
result.push(distributed);
total_ratio -= ratio;
total_remaining -= distributed;
}
result
}
/// Reduce `widths` so their total is under `max_width`, shrinking the widest
/// wrapable columns first. Direct port of `Table._collapse_widths`.
fn collapse_widths(mut widths: Vec<i64>, wrapable: &[bool], max_width: i64) -> Vec<i64> {
let mut total_width: i64 = widths.iter().sum();
let mut excess_width = total_width - max_width;
if wrapable.iter().any(|&w| w) {
while total_width != 0 && excess_width > 0 {
let max_column = widths
.iter()
.zip(wrapable)
.filter(|(_, &w)| w)
.map(|(&x, _)| x)
.max()
.unwrap_or(0);
let second_max_column = widths
.iter()
.zip(wrapable)
.map(|(&x, &w)| if w && x != max_column { x } else { 0 })
.max()
.unwrap_or(0);
let column_difference = max_column - second_max_column;
let ratios: Vec<i64> = widths
.iter()
.zip(wrapable)
.map(|(&x, &w)| i64::from(x == max_column && w))
.collect();
if !ratios.iter().any(|&r| r != 0) || column_difference == 0 {
break;
}
let max_reduce = vec![excess_width.min(column_difference); widths.len()];
widths = ratio_reduce(excess_width, &ratios, &max_reduce, &widths);
total_width = widths.iter().sum();
excess_width = total_width - max_width;
}
}
widths
}
#[cfg(test)]
mod tests {
use super::*;
use crate::color::ColorSystem;
use crate::r#box::SQUARE;
fn console() -> Console {
Console::builder()
.force_terminal(true)
.color_system(Some(ColorSystem::Truecolor))
.width(40)
.no_color(false)
.build()
}
#[test]
fn owned_rows_preserve_measurement_styles_and_missing_cells() {
use crate::protocol::OwnedTableRows;
for width in [1, 12, 40, 80] {
let console = Console::builder().width(width).force_terminal(true).build();
let build = || {
let mut table = Table::new()
.title("Rows")
.caption("owned or borrowed")
.show_lines(true);
table.add_column("Name");
table.add_column_justify("Value", Justify::Right);
table
};
let mut borrowed = build();
let mut owned = build();
for row in [
vec!["漢字\n🙂", "123"],
vec!["short"],
vec!["extra", "4", "ignored"],
] {
borrowed.add_row(&row);
owned.extend_owned_rows(vec![row.into_iter().map(str::to_owned).collect()]);
}
assert_eq!(
console.render_to_string(&borrowed),
console.render_to_string(&owned)
);
}
}
#[test]
fn simple_square_table() {
let mut table = Table::new().box_set(SQUARE);
table.add_column("Name");
table.add_column("Age");
table.add_row(&["Alice", "30"]);
table.add_row(&["Bob", "7"]);
let out = console().render_export(&table);
let expected = concat!(
"┌───────┬─────┐\n",
"│\x1b[1m \x1b[0m\x1b[1mName \x1b[0m\x1b[1m \x1b[0m│\x1b[1m \x1b[0m\x1b[1mAge\x1b[0m\x1b[1m \x1b[0m│\n",
"├───────┼─────┤\n",
"│ Alice │ 30 │\n",
"│ Bob │ 7 │\n",
"└───────┴─────┘\n",
);
assert_eq!(out, expected);
}
#[test]
fn streamed_lines_match_styled_table_output() {
let mut table = Table::new().box_set(SQUARE);
table.add_column("Name");
table.add_column("Age");
table.add_row(&["Alice", "30"]);
table.add_row(&["Bob", "7"]);
let console = console();
let mut streamed = String::new();
table
.try_for_each_line(&console, &console.options(), |line| {
assert!(line.iter().all(|segment| !segment.text.contains('\n')));
streamed.push_str(&console.segments_to_string(&line));
streamed.push('\n');
Ok::<_, std::convert::Infallible>(())
})
.unwrap();
// `simple_square_table` above fixes these bytes independently of the
// collection path, including distinct header-style segments.
assert_eq!(streamed, console.render_export(&table));
assert_eq!(streamed.lines().count(), 6);
}
#[test]
fn streamed_lines_stop_at_the_first_writer_error() {
let mut table = Table::new()
.box_set(SQUARE)
.title("People")
.caption("End")
.show_lines(true);
table.add_column("Name");
table.add_row(&["Alice\nBob"]);
table.add_row(&["Carol"]);
let console = console();
let mut visits = 0;
let result = table.try_for_each_line(&console, &console.options(), |_| {
visits += 1;
if visits == 5 {
Err("writer failed")
} else {
Ok(())
}
});
assert_eq!(result, Err("writer failed"));
assert_eq!(visits, 5);
}
/// A column squeezed below its own padding still emitted a full left and
/// right pad, so each such column spent two cells where its border spent
/// one. The content row then overflowed the table and was cropped, losing
/// its right-hand border while the border rows kept theirs.
#[test]
fn a_column_narrower_than_its_padding_stays_inside_the_border() {
for ncols in [20usize, 29, 40] {
let mut table = Table::new().box_set(SQUARE);
for i in 0..ncols {
table.add_column(format!("c{i}"));
}
let row: Vec<String> = (0..ncols).map(|i| i.to_string()).collect();
table.add_row(&row.iter().map(String::as_str).collect::<Vec<_>>());
let console = Console::builder().width(80).no_color(true).build();
let out = console.render_to_string(&table);
let rows: Vec<&str> = out.lines().filter(|l| !l.trim().is_empty()).collect();
let widths: Vec<usize> = rows.iter().map(|r| r.chars().count()).collect();
assert!(
widths.iter().all(|w| *w == widths[0]),
"{ncols} columns produced ragged rows: {widths:?}"
);
for (index, row) in rows.iter().enumerate() {
let last = row.chars().last().expect("non-empty row");
assert!(
!last.is_whitespace(),
"{ncols} columns: row {index} lost its right border: {row:?}"
);
}
}
}
/// A cell spanning several lines occupies its WIDEST line. Measuring the raw
/// string made it as wide as all its lines summed — `\n` measures zero, so
/// nothing capped it — and a quoted CSV cell holding two sentences blew its
/// column out to 31 cells where upstream gives 23.
#[test]
fn a_multi_line_cell_is_measured_by_its_widest_line() {
let mut table = Table::new().box_set(SQUARE);
table.add_column("name");
table.add_column("bio");
table.add_row(&["Alice", "line one\nline two is much longer"]);
table.add_row(&["Bob", "short"]);
let console = Console::builder().width(60).no_color(true).build();
let out = console.render_to_string(&table);
let top = out.lines().next().expect("a top border");
let width = top.chars().count();
// "line two is much longer" is 23 cells; summing both lines would be 31.
assert!(
width < 40,
"the multi-line cell was measured as the sum of its lines: {width} wide"
);
assert!(
out.contains("line two is much longer"),
"content lost: {out:?}"
);
}
}