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
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
use std::collections::HashMap;
use std::fmt;
use std::iter::IntoIterator;
use std::slice::{Iter, IterMut};
#[cfg(feature = "tty")]
use std::sync::OnceLock;
use crate::cell::Cell;
use crate::column::Column;
use crate::row::Row;
use crate::style::presets::ASCII_FULL;
use crate::style::{ColumnConstraint, ContentArrangement, TableComponent};
use crate::utils::build_table;
/// This is the main interface for building a table.
/// Each table consists of [Rows](Row), which in turn contain [Cells](crate::cell::Cell).
///
/// There also exists a representation of a [Column].
/// Columns are automatically created when adding rows to a table.
#[derive(Debug, Clone)]
pub struct Table {
pub(crate) columns: Vec<Column>,
style: HashMap<TableComponent, char>,
pub(crate) header: Option<Row>,
pub(crate) rows: Vec<Row>,
pub(crate) arrangement: ContentArrangement,
pub(crate) delimiter: Option<char>,
pub(crate) truncation_indicator: String,
#[cfg(feature = "tty")]
no_tty: bool,
#[cfg(feature = "tty")]
is_tty_cache: OnceLock<bool>,
#[cfg(feature = "tty")]
use_stderr: bool,
width: Option<u16>,
#[cfg(feature = "tty")]
enforce_styling: bool,
/// Define whether everything in a cells should be styled, including whitespaces
/// or whether only the text should be styled.
#[cfg(feature = "tty")]
pub(crate) style_text_only: bool,
}
impl fmt::Display for Table {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.lines().collect::<Vec<_>>().join("\n"))
}
}
impl Default for Table {
fn default() -> Self {
Self::new()
}
}
impl Table {
/// Create a new table with default ASCII styling.
pub fn new() -> Self {
let mut table = Self {
columns: Vec::new(),
header: None,
rows: Vec::new(),
arrangement: ContentArrangement::Disabled,
delimiter: None,
truncation_indicator: "...".to_string(),
#[cfg(feature = "tty")]
no_tty: false,
#[cfg(feature = "tty")]
is_tty_cache: OnceLock::new(),
#[cfg(feature = "tty")]
use_stderr: false,
width: None,
style: HashMap::new(),
#[cfg(feature = "tty")]
enforce_styling: false,
#[cfg(feature = "tty")]
style_text_only: false,
};
table.load_preset(ASCII_FULL);
table
}
/// This is an alternative `fmt` function, which simply removes any trailing whitespaces.
/// Trailing whitespaces often occur, when using tables without a right border.
pub fn trim_fmt(&self) -> String {
self.lines()
.map(|line| line.trim_end().to_string())
.collect::<Vec<_>>()
.join("\n")
}
/// This is an alternative to `fmt`, but rather returns an iterator to each line, rather than
/// one String separated by newlines.
pub fn lines(&self) -> impl Iterator<Item = String> {
build_table(self)
}
/// Set the header row of the table. This is usually the title of each column.\
/// There'll be no header unless you explicitly set it with this function.
///
/// ```
/// use super_table::{Table, Row};
///
/// let mut table = Table::new();
/// let header = Row::from(vec!["Header One", "Header Two"]);
/// table.set_header(header);
/// ```
pub fn set_header<T: Into<Row>>(&mut self, row: T) -> &mut Self {
let row = row.into();
self.autogenerate_columns(&row);
self.header = Some(row);
self
}
pub fn header(&self) -> Option<&Row> {
self.header.as_ref()
}
/// Returns the number of currently present columns.
///
/// ```
/// use super_table::Table;
///
/// let mut table = Table::new();
/// table.set_header(vec!["Col 1", "Col 2", "Col 3"]);
///
/// assert_eq!(table.column_count(), 3);
/// ```
pub fn column_count(&mut self) -> usize {
self.discover_columns();
self.columns.len()
}
/// Add a new row to the table.
///
/// ```
/// use super_table::{Table, Row};
///
/// let mut table = Table::new();
/// table.add_row(vec!["One", "Two"]);
/// ```
pub fn add_row<T: Into<Row>>(&mut self, row: T) -> &mut Self {
let mut row = row.into();
self.autogenerate_columns(&row);
row.index = Some(self.rows.len());
self.rows.push(row);
self
}
/// Add a new row to the table if the predicate evaluates to `true`.
///
/// ```
/// use super_table::{Table, Row};
///
/// let mut table = Table::new();
/// table.add_row_if(|index, row| true, vec!["One", "Two"]);
/// ```
pub fn add_row_if<P, T>(&mut self, predicate: P, row: T) -> &mut Self
where
P: Fn(usize, &T) -> bool,
T: Into<Row>,
{
if predicate(self.rows.len(), &row) {
return self.add_row(row);
}
self
}
/// Add multiple rows to the table.
///
/// ```
/// use super_table::{Table, Row};
///
/// let mut table = Table::new();
/// let rows = vec![
/// vec!["One", "Two"],
/// vec!["Three", "Four"]
/// ];
/// table.add_rows(rows);
/// ```
pub fn add_rows<I>(&mut self, rows: I) -> &mut Self
where
I: IntoIterator,
I::Item: Into<Row>,
{
for row in rows.into_iter() {
let mut row = row.into();
self.autogenerate_columns(&row);
row.index = Some(self.rows.len());
self.rows.push(row);
}
self
}
/// Add multiple rows to the table if the predicate evaluates to `true`.
///
/// ```
/// use super_table::{Table, Row};
///
/// let mut table = Table::new();
/// let rows = vec![
/// vec!["One", "Two"],
/// vec!["Three", "Four"]
/// ];
/// table.add_rows_if(|index, rows| true, rows);
/// ```
pub fn add_rows_if<P, I>(&mut self, predicate: P, rows: I) -> &mut Self
where
P: Fn(usize, &I) -> bool,
I: IntoIterator,
I::Item: Into<Row>,
{
if predicate(self.rows.len(), &rows) {
return self.add_rows(rows);
}
self
}
/// Returns the number of currently present rows.
///
/// ```
/// use super_table::Table;
///
/// let mut table = Table::new();
/// table.add_row(vec!["One", "Two"]);
///
/// assert_eq!(table.row_count(), 1);
/// ```
pub fn row_count(&self) -> usize {
self.rows.len()
}
/// Returns if the table is empty (contains no data rows).
///
/// ```
/// use super_table::Table;
///
/// let mut table = Table::new();
/// assert!(table.is_empty());
///
/// table.add_row(vec!["One", "Two"]);
/// assert!(!table.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.rows.is_empty()
}
/// Enforce a max width that should be used in combination with [dynamic content arrangement](ContentArrangement::Dynamic).\
/// This is usually not necessary, if you plan to output your table to a tty,
/// since the terminal width can be automatically determined.
pub fn set_width(&mut self, width: u16) -> &mut Self {
self.width = Some(width);
self
}
/// Get the expected width of the table.
///
/// This will be `Some(width)`, if the terminal width can be detected or if the table width is set via [set_width](Table::set_width).
///
/// If neither is not possible, `None` will be returned.\
/// This implies that both the [Dynamic](ContentArrangement::Dynamic) mode and the [Percentage](crate::style::Width::Percentage) constraint won't work.
#[cfg(feature = "tty")]
pub fn width(&self) -> Option<u16> {
if let Some(width) = self.width {
Some(width)
} else if self.is_tty() {
if let Ok((width, _)) = crossterm::terminal::size() {
Some(width)
} else {
None
}
} else {
None
}
}
#[cfg(not(feature = "tty"))]
pub fn width(&self) -> Option<u16> {
self.width
}
/// Specify how Comfy Table should arrange the content in your table.
///
/// ```
/// use super_table::{Table, ContentArrangement};
///
/// let mut table = Table::new();
/// table.set_content_arrangement(ContentArrangement::Dynamic);
/// ```
pub fn set_content_arrangement(&mut self, arrangement: ContentArrangement) -> &mut Self {
self.arrangement = arrangement;
self
}
/// Get the current content arrangement of the table.
pub fn content_arrangement(&self) -> ContentArrangement {
self.arrangement.clone()
}
/// Set the delimiter used to split text in all cells.
///
/// A custom delimiter on a cell in will overwrite the column's delimiter.\
/// Normal text uses spaces (` `) as delimiters. This is necessary to help super-table
/// understand the concept of _words_.
pub fn set_delimiter(&mut self, delimiter: char) -> &mut Self {
self.delimiter = Some(delimiter);
self
}
/// Set the truncation indicator for cells that are too long to be displayed.
///
/// Set it to "…" for example to use an ellipsis that only takes up one character.
pub fn set_truncation_indicator(&mut self, indicator: &str) -> &mut Self {
self.truncation_indicator = indicator.to_string();
self
}
/// In case you are sure you don't want export tables to a tty or you experience
/// problems with tty specific code, you can enforce a non_tty mode.
///
/// This disables:
///
/// - width lookup from the current tty
/// - Styling and attributes on cells (unless you use [Table::enforce_styling])
///
/// If you use the [dynamic content arrangement](ContentArrangement::Dynamic),
/// you need to set the width of your desired table manually with [set_width](Table::set_width).
#[cfg(feature = "tty")]
pub fn force_no_tty(&mut self) -> &mut Self {
self.no_tty = true;
self
}
/// Use this function to check whether `stderr` is a tty.
///
/// The default is `stdout`.
#[cfg(feature = "tty")]
pub fn use_stderr(&mut self) -> &mut Self {
self.use_stderr = true;
self
}
/// Returns whether the table will be handled as if it's printed to a tty.
///
/// By default, super-table looks at `stdout` and checks whether it's a tty.
/// This behavior can be changed via [Table::force_no_tty] and [Table::use_stderr].
#[cfg(feature = "tty")]
pub fn is_tty(&self) -> bool {
use std::io::IsTerminal;
if self.no_tty {
return false;
}
*self.is_tty_cache.get_or_init(|| {
if self.use_stderr {
std::io::stderr().is_terminal()
} else {
std::io::stdout().is_terminal()
}
})
}
/// Enforce terminal styling.
///
/// Only useful if you forcefully disabled tty, but still want those fancy terminal styles.
///
/// ```
/// use super_table::Table;
///
/// let mut table = Table::new();
/// table.force_no_tty()
/// .enforce_styling();
/// ```
#[cfg(feature = "tty")]
pub fn enforce_styling(&mut self) -> &mut Self {
self.enforce_styling = true;
self
}
/// Returns whether the content of this table should be styled with the current settings and
/// environment.
#[cfg(feature = "tty")]
pub fn should_style(&self) -> bool {
if self.enforce_styling {
return true;
}
self.is_tty()
}
/// By default, the whole content of a cells will be styled.
/// Calling this function disables this behavior for all cells, resulting in
/// only the text of cells being styled.
#[cfg(feature = "tty")]
pub fn style_text_only(&mut self) {
self.style_text_only = true;
}
/// Convenience method to set a [ColumnConstraint] for all columns at once.
/// Constraints are used to influence the way the columns will be arranged.
/// Check out their docs for more information.
///
/// **Attention:**
/// This function should be called after at least one row (or the headers) has been added to the table.
/// Before that, the columns won't initialized.
///
/// If more constraints are passed than there are columns, any superfluous constraints will be ignored.
/// ```
/// use super_table::{Width::*, CellAlignment, ColumnConstraint::*, ContentArrangement, Table};
///
/// let mut table = Table::new();
/// table.add_row(&vec!["one", "two", "three"])
/// .set_content_arrangement(ContentArrangement::Dynamic)
/// .set_constraints(vec![
/// UpperBoundary(Fixed(15)),
/// LowerBoundary(Fixed(20)),
/// ]);
/// ```
pub fn set_constraints<T: IntoIterator<Item = ColumnConstraint>>(
&mut self,
constraints: T,
) -> &mut Self {
let mut constraints = constraints.into_iter();
for column in self.column_iter_mut() {
if let Some(constraint) = constraints.next() {
column.set_constraint(constraint);
} else {
break;
}
}
self
}
/// This function creates a TableStyle from a given preset string.\
/// Preset strings can be found in `styling::presets::*`.
///
/// You can also write your own preset strings and use them with this function.
/// There's the convenience method [Table::current_style_as_preset], which prints you a preset
/// string from your current style configuration. \
/// The function expects the to-be-drawn characters to be in the same order as in the [TableComponent] enum.
///
/// If the string isn't long enough, the default [ASCII_FULL] style will be used for all remaining components.
///
/// If the string is too long, remaining charaacters will be simply ignored.
pub fn load_preset(&mut self, preset: &str) -> &mut Self {
let mut components = TableComponent::iter();
for character in preset.chars() {
if let Some(component) = components.next() {
// White spaces mean "don't draw this" in presets
// If we want to override the default preset, we need to remove
// this component from the HashMap in case we find a whitespace.
if character == ' ' {
self.remove_style(component);
continue;
}
self.set_style(component, character);
} else {
break;
}
}
self
}
/// Returns the current style as a preset string.
///
/// A pure convenience method, so you're not force to fiddle with those preset strings yourself.
///
/// ```
/// use super_table::Table;
/// use super_table::presets::UTF8_FULL;
///
/// let mut table = Table::new();
/// table.load_preset(UTF8_FULL);
///
/// assert_eq!(UTF8_FULL, table.current_style_as_preset())
/// ```
pub fn current_style_as_preset(&mut self) -> String {
let components = TableComponent::iter();
let mut preset_string = String::new();
for component in components {
match self.style(component) {
None => preset_string.push(' '),
Some(character) => preset_string.push(character),
}
}
preset_string
}
/// Modify a preset with a modifier string from [modifiers](crate::style::modifiers).
///
/// For instance, the [UTF8_ROUND_CORNERS](crate::style::modifiers::UTF8_ROUND_CORNERS) modifies all corners to be round UTF8 box corners.
///
/// ```
/// use super_table::Table;
/// use super_table::presets::UTF8_FULL;
/// use super_table::modifiers::UTF8_ROUND_CORNERS;
///
/// let mut table = Table::new();
/// table.load_preset(UTF8_FULL);
/// table.apply_modifier(UTF8_ROUND_CORNERS);
/// ```
pub fn apply_modifier(&mut self, modifier: &str) -> &mut Self {
let mut components = TableComponent::iter();
for character in modifier.chars() {
// Skip spaces while applying modifiers.
if character == ' ' {
components.next();
continue;
}
if let Some(component) = components.next() {
self.set_style(component, character);
} else {
break;
}
}
self
}
/// Define the char that will be used to draw a specific component.\
/// Look at [TableComponent] to see all stylable components
///
/// If `None` is supplied, the element won't be displayed.\
/// In case of a e.g. *BorderIntersection a whitespace will be used as placeholder,
/// unless related borders and and corners are set to `None` as well.
///
/// For example, if `TopBorderIntersections` is `None` the first row would look like this:
///
/// ```text
/// +------ ------+
/// | this | test |
/// ```
///
/// If in addition `TopLeftCorner`,`TopBorder` and `TopRightCorner` would be `None` as well,
/// the first line wouldn't be displayed at all.
///
/// ```
/// use super_table::Table;
/// use super_table::presets::UTF8_FULL;
/// use super_table::TableComponent::*;
///
/// let mut table = Table::new();
/// // Load the UTF8_FULL preset
/// table.load_preset(UTF8_FULL);
/// // Set all outer corners to round UTF8 corners
/// // This is basically the same as the UTF8_ROUND_CORNERS modifier
/// table.set_style(TopLeftCorner, 'â•');
/// table.set_style(TopRightCorner, 'â•®');
/// table.set_style(BottomLeftCorner, 'â•°');
/// table.set_style(BottomRightCorner, '╯');
/// ```
pub fn set_style(&mut self, component: TableComponent, character: char) -> &mut Self {
self.style.insert(component, character);
self
}
/// Get a copy of the char that's currently used for drawing this component.
/// ```
/// use super_table::Table;
/// use super_table::TableComponent::*;
///
/// let mut table = Table::new();
/// assert_eq!(table.style(TopLeftCorner), Some('+'));
/// ```
pub fn style(&mut self, component: TableComponent) -> Option<char> {
self.style.get(&component).copied()
}
/// Remove the style for a specific component of the table.\
/// By default, a space will be used as a placeholder instead.\
/// Though, if for instance all components of the left border are removed, the left border won't be displayed.
pub fn remove_style(&mut self, component: TableComponent) -> &mut Self {
self.style.remove(&component);
self
}
/// Get a reference to a specific column.
pub fn column(&self, index: usize) -> Option<&Column> {
self.columns.get(index)
}
/// Get a mutable reference to a specific column.
pub fn column_mut(&mut self, index: usize) -> Option<&mut Column> {
self.columns.get_mut(index)
}
/// Iterator over all columns
pub fn column_iter(&self) -> Iter<'_, Column> {
self.columns.iter()
}
/// Get a mutable iterator over all columns.
///
/// ```
/// use super_table::{Width::*, ColumnConstraint::*, Table};
///
/// let mut table = Table::new();
/// table.add_row(&vec!["First", "Second", "Third"]);
///
/// // Add a ColumnConstraint to each column (left->right)
/// // first -> min width of 10
/// // second -> max width of 8
/// // third -> fixed width of 10
/// let constraints = vec![
/// LowerBoundary(Fixed(10)),
/// UpperBoundary(Fixed(8)),
/// Absolute(Fixed(10)),
/// ];
///
/// // Add the constraints to their respective column
/// for (column_index, column) in table.column_iter_mut().enumerate() {
/// let constraint = constraints.get(column_index).unwrap();
/// column.set_constraint(*constraint);
/// }
/// ```
pub fn column_iter_mut(&mut self) -> IterMut<'_, Column> {
self.columns.iter_mut()
}
/// Get a mutable iterator over cells of a column.
/// The iterator returns a nested `Option<Option<Cell>>`, since there might be
/// rows that are missing this specific Cell.
///
/// ```
/// use super_table::Table;
/// let mut table = Table::new();
/// table.add_row(&vec!["First", "Second"]);
/// table.add_row(&vec!["Third"]);
/// table.add_row(&vec!["Fourth", "Fifth"]);
///
/// // Create an iterator over the second column
/// let mut cell_iter = table.column_cells_iter(1);
/// assert_eq!(cell_iter.next().unwrap().unwrap().content(), "Second");
/// assert!(cell_iter.next().unwrap().is_none());
/// assert_eq!(cell_iter.next().unwrap().unwrap().content(), "Fifth");
/// assert!(cell_iter.next().is_none());
/// ```
pub fn column_cells_iter(&self, column_index: usize) -> ColumnCellIter<'_> {
ColumnCellIter {
rows: &self.rows,
column_index,
row_index: 0,
}
}
/// Get a mutable iterator over cells of a column, including the header cell.
/// The header cell will be the very first cell returned.
/// The iterator returns a nested `Option<Option<Cell>>`, since there might be
/// rows that are missing this specific Cell.
///
/// ```
/// use super_table::Table;
/// let mut table = Table::new();
/// table.set_header(&vec!["A", "B"]);
/// table.add_row(&vec!["First", "Second"]);
/// table.add_row(&vec!["Third"]);
/// table.add_row(&vec!["Fourth", "Fifth"]);
///
/// // Create an iterator over the second column
/// let mut cell_iter = table.column_cells_with_header_iter(1);
/// assert_eq!(cell_iter.next().unwrap().unwrap().content(), "B");
/// assert_eq!(cell_iter.next().unwrap().unwrap().content(), "Second");
/// assert!(cell_iter.next().unwrap().is_none());
/// assert_eq!(cell_iter.next().unwrap().unwrap().content(), "Fifth");
/// assert!(cell_iter.next().is_none());
/// ```
pub fn column_cells_with_header_iter(
&self,
column_index: usize,
) -> ColumnCellsWithHeaderIter<'_> {
ColumnCellsWithHeaderIter {
header_checked: false,
header: &self.header,
rows: &self.rows,
column_index,
row_index: 0,
}
}
/// Reference to a specific row
pub fn row(&self, index: usize) -> Option<&Row> {
self.rows.get(index)
}
/// Mutable reference to a specific row
pub fn row_mut(&mut self, index: usize) -> Option<&mut Row> {
self.rows.get_mut(index)
}
/// Iterator over all rows
pub fn row_iter(&self) -> Iter<'_, Row> {
self.rows.iter()
}
/// Get a mutable iterator over all rows.
///
/// ```
/// use super_table::Table;
/// let mut table = Table::new();
/// table.add_row(&vec!["First", "Second", "Third"]);
///
/// // Add the constraints to their respective row
/// for row in table.row_iter_mut() {
/// row.max_height(5);
/// }
/// assert!(table.row_iter_mut().len() == 1);
/// ```
pub fn row_iter_mut(&mut self) -> IterMut<'_, Row> {
self.rows.iter_mut()
}
/// Return a vector representing the maximum amount of characters in any line of this column.\
///
/// **Attention** This scans the whole current content of the table.
/// Accounts for colspan and rowspan when calculating column widths.
pub fn column_max_content_widths(&self) -> Vec<u16> {
// The vector that'll contain the max widths per column.
let mut max_widths = vec![0; self.columns.len()];
// Track active rowspans: (start_row, start_col) -> (remaining_rows, colspan)
use std::collections::HashMap;
let mut active_rowspans: HashMap<(usize, usize), (u16, u16)> = HashMap::new();
// Helper function to check if a column is occupied by a rowspan
fn is_col_occupied_by_rowspan(
active_rowspans: &HashMap<(usize, usize), (u16, u16)>,
row_index: usize,
col_index: usize,
) -> bool {
for ((start_row, start_col), (remaining_rows, colspan)) in active_rowspans.iter() {
if *start_row < row_index
&& *remaining_rows > 0
&& *start_col <= col_index
&& col_index < *start_col + *colspan as usize
{
return true;
}
}
false
}
// Helper function to update max widths for a row, accounting for colspan and rowspan
fn set_max_content_widths(
max_widths: &mut [u16],
row: &Row,
row_index: usize,
active_rowspans: &mut HashMap<(usize, usize), (u16, u16)>,
) {
// Get the max width for each cell of the row
let row_max_widths = row.max_content_widths();
let mut col_index = 0;
for (cell_index, width) in row_max_widths.iter().enumerate() {
// Skip column positions that are occupied by rowspan from above
while col_index < max_widths.len()
&& is_col_occupied_by_rowspan(active_rowspans, row_index, col_index)
{
col_index += 1;
}
if col_index >= max_widths.len() {
break;
}
let cell = &row.cells[cell_index];
let colspan = cell.colspan() as usize;
let rowspan = cell.rowspan();
let mut cell_width = (*width).try_into().unwrap_or(u16::MAX);
// A column's content is at least 1 char wide.
cell_width = std::cmp::max(1, cell_width);
if colspan == 1 {
// Simple case: no colspan, just update the column directly
// For rowspan cells, the full width applies to the column
let current_max = max_widths[col_index];
if current_max < cell_width {
max_widths[col_index] = cell_width;
}
col_index += 1;
} else {
// Colspan case: ensure the sum of the spanned columns can accommodate the cell
// The border/content formatting code sums content_widths and adds padding once
// So we need content_widths to sum to cell_width (padding is added separately)
// But we also need to ensure the columns are wide enough for other cells
// So we calculate the minimum needed, then check if we need to increase it
let total_content_needed = cell_width;
let min_width_per_col = total_content_needed / colspan as u16;
let remainder = total_content_needed % colspan as u16;
// First, set minimum widths
for i in 0..colspan {
if col_index + i >= max_widths.len() {
break;
}
let width_for_col = if i < remainder as usize {
min_width_per_col + 1
} else {
min_width_per_col
};
let current_max = max_widths[col_index + i];
if current_max < width_for_col {
max_widths[col_index + i] = width_for_col;
}
}
// Then, check if the sum is sufficient (the largest accumulation counts)
// If other cells in these columns need more space, they'll increase the widths
// and we'll need to ensure the colspan cell still fits
let current_sum: u16 = (0..colspan)
.map(|i| {
if col_index + i < max_widths.len() {
max_widths[col_index + i]
} else {
0
}
})
.sum();
// If current sum is less than needed, increase columns proportionally
if current_sum < total_content_needed {
let diff = total_content_needed - current_sum;
let per_col_inc = diff / colspan as u16;
let remainder_inc = diff % colspan as u16;
for i in 0..colspan {
if col_index + i < max_widths.len() {
let inc = if i < remainder_inc as usize {
per_col_inc + 1
} else {
per_col_inc
};
max_widths[col_index + i] += inc;
}
}
}
col_index += colspan;
}
// Register rowspan if needed
if rowspan > 1 {
active_rowspans.insert(
(row_index, col_index - colspan),
(rowspan - 1, colspan as u16),
);
}
}
}
// Process header if it exists
if let Some(header) = &self.header {
set_max_content_widths(&mut max_widths, header, 0, &mut active_rowspans);
}
// Iterate through all rows of the table
for (row_idx, row) in self.rows.iter().enumerate() {
let actual_row_index = if self.header.is_some() {
row_idx + 1
} else {
row_idx
};
set_max_content_widths(&mut max_widths, row, actual_row_index, &mut active_rowspans);
// Advance rowspans after processing this row
// First decrement remaining_rows for all active spans that have been displayed
for ((start_row, _), (remaining_rows, _)) in active_rowspans.iter_mut() {
if *start_row < actual_row_index && *remaining_rows > 0 {
*remaining_rows -= 1;
}
}
// Then remove expired spans (remaining_rows == 0 means it was just displayed in its last row)
active_rowspans.retain(|_, (remaining_rows, _)| *remaining_rows > 0);
}
// Second pass: ensure colspan cells have enough space (the largest accumulation counts)
// After all cells have been processed, check if any colspan cell needs more space
// We compare total widths (content + padding), not just content widths
active_rowspans.clear();
if let Some(header) = &self.header {
let row_max_widths = header.max_content_widths();
let mut col_index = 0;
for (cell_index, width) in row_max_widths.iter().enumerate() {
let cell = &header.cells[cell_index];
let colspan = cell.colspan() as usize;
let cell_width = (*width).try_into().unwrap_or(u16::MAX);
let cell_width = std::cmp::max(1, cell_width);
if colspan > 1 {
// Colspan cell needs: content_widths should sum to cell_width
// Padding is added once during formatting, not per column
let colspan_cell_need = cell_width;
// Sum the current content widths of the spanned columns
let current_content_sum: u16 = (0..colspan)
.map(|i| {
if col_index + i < max_widths.len() {
max_widths[col_index + i]
} else {
0
}
})
.sum();
// Ensure the sum of content widths is at least cell_width
if current_content_sum < colspan_cell_need {
let diff = colspan_cell_need - current_content_sum;
let per_col_inc = diff / colspan as u16;
let remainder_inc = diff % colspan as u16;
for i in 0..colspan {
if col_index + i < max_widths.len() {
let inc = if i < remainder_inc as usize {
per_col_inc + 1
} else {
per_col_inc
};
max_widths[col_index + i] += inc;
}
}
}
}
col_index += colspan;
}
}
for row in &self.rows {
let row_max_widths = row.max_content_widths();
let mut col_index = 0;
for (cell_index, width) in row_max_widths.iter().enumerate() {
let cell = &row.cells[cell_index];
let colspan = cell.colspan() as usize;
let cell_width = (*width).try_into().unwrap_or(u16::MAX);
let cell_width = std::cmp::max(1, cell_width);
if colspan > 1 {
// Colspan cell needs: content_widths should sum to cell_width
// Padding is added once during formatting, not per column
let colspan_cell_need = cell_width;
let current_sum: u16 = (0..colspan)
.map(|i| {
if col_index + i < max_widths.len() {
max_widths[col_index + i]
} else {
0
}
})
.sum();
// Ensure the sum of content widths is at least cell_width
if current_sum < colspan_cell_need {
let diff = colspan_cell_need - current_sum;
let per_col_inc = diff / colspan as u16;
let remainder_inc = diff % colspan as u16;
for i in 0..colspan {
if col_index + i < max_widths.len() {
let inc = if i < remainder_inc as usize {
per_col_inc + 1
} else {
per_col_inc
};
max_widths[col_index + i] += inc;
}
}
}
}
col_index += colspan;
}
}
max_widths
}
pub(crate) fn style_or_default(&self, component: TableComponent) -> String {
match self.style.get(&component) {
None => " ".to_string(),
Some(character) => character.to_string(),
}
}
pub(crate) fn style_exists(&self, component: TableComponent) -> bool {
self.style.contains_key(&component)
}
/// Autogenerate new columns, if a row is added with more cells than existing columns.
/// Accounts for colspan when determining the required number of columns.
fn autogenerate_columns(&mut self, row: &Row) {
let effective_cols = row.effective_column_count();
if effective_cols > self.columns.len() {
for index in self.columns.len()..effective_cols {
self.columns.push(Column::new(index));
}
}
}
/// Calling this might be necessary if you add new cells to rows that're already added to the
/// table.
///
/// If more cells than're currently know to the table are added to that row,
/// the table cannot know about these, since new [Column]s are only
/// automatically detected when a new row is added.
///
/// To make sure everything works as expected, just call this function if you're adding cells
/// to rows that're already added to the table.
///
/// Accounts for colspan when determining the required number of columns.
pub fn discover_columns(&mut self) {
// Check header if it exists
if let Some(header) = &self.header {
let effective_cols = header.effective_column_count();
if effective_cols > self.columns.len() {
for index in self.columns.len()..effective_cols {
self.columns.push(Column::new(index));
}
}
}
// Check all rows
for row in self.rows.iter() {
let effective_cols = row.effective_column_count();
if effective_cols > self.columns.len() {
for index in self.columns.len()..effective_cols {
self.columns.push(Column::new(index));
}
}
}
}
}
/// An iterator over cells of a specific column.
/// A dedicated struct is necessary, as data is usually handled by rows and thereby stored in
/// `Table::rows`. This type is returned by [Table::column_cells_iter].
pub struct ColumnCellIter<'a> {
rows: &'a [Row],
column_index: usize,
row_index: usize,
}
impl<'a> Iterator for ColumnCellIter<'a> {
type Item = Option<&'a Cell>;
fn next(&mut self) -> Option<Option<&'a Cell>> {
// Check if there's a next row
if let Some(row) = self.rows.get(self.row_index) {
self.row_index += 1;
// Return the cell (if it exists).
return Some(row.cells.get(self.column_index));
}
None
}
}
/// An iterator over cells of a specific column.
/// A dedicated struct is necessary, as data is usually handled by rows and thereby stored in
/// `Table::rows`. This type is returned by [Table::column_cells_iter].
pub struct ColumnCellsWithHeaderIter<'a> {
header_checked: bool,
header: &'a Option<Row>,
rows: &'a [Row],
column_index: usize,
row_index: usize,
}
impl<'a> Iterator for ColumnCellsWithHeaderIter<'a> {
type Item = Option<&'a Cell>;
fn next(&mut self) -> Option<Option<&'a Cell>> {
// Get the header as the first cell
if !self.header_checked {
self.header_checked = true;
return match self.header {
Some(header) => {
// Return the cell (if it exists).
Some(header.cells.get(self.column_index))
}
None => Some(None),
};
}
// Check if there's a next row
if let Some(row) = self.rows.get(self.row_index) {
self.row_index += 1;
// Return the cell (if it exists).
return Some(row.cells.get(self.column_index));
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_column_generation() {
let mut table = Table::new();
table.set_header(vec!["thr", "four", "fivef"]);
// When adding a new row, columns are automatically generated
assert_eq!(table.columns.len(), 3);
// The max content width is also correctly set for each column
assert_eq!(table.column_max_content_widths(), vec![3, 4, 5]);
// When adding a new row, the max content width is updated accordingly
table.add_row(vec!["four", "fivef", "very long text with 23"]);
assert_eq!(table.column_max_content_widths(), vec![4, 5, 22]);
// Now add a row that has column lines. The max content width shouldn't change
table.add_row(vec!["", "", "shorter"]);
assert_eq!(table.column_max_content_widths(), vec![4, 5, 22]);
println!("{table}");
}
}