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
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
use std::env;
use std::io::{self, Write};
use std::num::NonZeroUsize;
use std::str::FromStr;

use colored::{self, Colorize};
use numfmt::{Formatter, Precision};
use unicode_width::UnicodeWidthStr;

use crate::config::{Config, Delimiter};
use crate::select::SelectedColumns;
use crate::util::{self, ColorMode};
use crate::CliResult;

#[derive(Debug, Clone, Copy, Default, Deserialize)]
pub enum ComplexToggle {
    #[default]
    Auto,
    Never,
    Always,
}

impl ComplexToggle {
    fn is_auto(&self) -> bool {
        matches!(self, Self::Auto)
    }
}

fn prepend(record: &csv::StringRecord, cell_value: &str) -> csv::StringRecord {
    let mut new_record = csv::StringRecord::new();
    new_record.push_field(cell_value);
    new_record.extend(record);

    new_record
}

const HEADERS_ROWS: usize = 8;

type BoxCharsArray = [char; 11];

#[repr(u8)]
enum BoxChar {
    CornerUpLeft,
    CornerUpRight,
    CornerBottomLeft,
    CornerBottomRight,
    CrossLeft,
    CrossRight,
    CrossBottom,
    CrossUp,
    CrossFull,
    Horizontal,
    Vertical,
}

const BOX_CHARS: BoxCharsArray = ['', '', '', '', '', '', '', '', '', '', ''];
const ROUNDED_BOX_CHARS: BoxCharsArray = ['', '', '', '', '', '', '', '', '', '', ''];
const INVISIBLE_BOX_CHARS: BoxCharsArray = [' '; 11];

struct ViewTheme {
    padding: &'static str,
    index_column_header: &'static str,
    box_chars: BoxCharsArray,
    hr_under_headers: bool,
    external_borders: bool,
    striped: bool,
}

impl Default for ViewTheme {
    fn default() -> Self {
        Self {
            padding: " ",
            index_column_header: "-",
            box_chars: BOX_CHARS,
            hr_under_headers: true,
            external_borders: true,
            striped: false,
        }
    }
}

impl ViewTheme {
    // Themes beyond default
    fn borderless() -> Self {
        Self {
            index_column_header: " ",
            box_chars: INVISIBLE_BOX_CHARS,
            hr_under_headers: false,
            external_borders: false,
            ..Self::default()
        }
    }

    fn compact() -> Self {
        Self {
            padding: "",
            index_column_header: " ",
            box_chars: INVISIBLE_BOX_CHARS,
            hr_under_headers: false,
            external_borders: false,
            ..Self::default()
        }
    }

    fn rounded() -> Self {
        Self {
            box_chars: ROUNDED_BOX_CHARS,
            ..Self::default()
        }
    }

    fn slim() -> Self {
        Self {
            index_column_header: " ",
            external_borders: false,
            ..Self::default()
        }
    }

    fn striped() -> Self {
        Self {
            padding: "",
            index_column_header: " ",
            box_chars: INVISIBLE_BOX_CHARS,
            hr_under_headers: false,
            external_borders: false,
            striped: true,
        }
    }

    // Methods
    #[inline]
    fn horizontal_box(&self) -> String {
        self.box_chars[BoxChar::Horizontal as usize].to_string()
    }

    #[inline]
    fn corner_up_left(&self) -> char {
        self.box_chars[BoxChar::CornerUpLeft as usize]
    }

    #[inline]
    fn corner_up_right(&self) -> char {
        self.box_chars[BoxChar::CornerUpRight as usize]
    }

    #[inline]
    fn corner_bottom_left(&self) -> char {
        self.box_chars[BoxChar::CornerBottomLeft as usize]
    }

    #[inline]
    fn corner_bottom_right(&self) -> char {
        self.box_chars[BoxChar::CornerBottomRight as usize]
    }

    #[inline]
    fn cross_left(&self) -> char {
        self.box_chars[BoxChar::CrossLeft as usize]
    }

    #[inline]
    fn cross_right(&self) -> char {
        self.box_chars[BoxChar::CrossRight as usize]
    }

    #[inline]
    fn cross_bottom(&self) -> char {
        self.box_chars[BoxChar::CrossBottom as usize]
    }

    #[inline]
    fn cross_up(&self) -> char {
        self.box_chars[BoxChar::CrossUp as usize]
    }

    #[inline]
    fn cross_full(&self) -> char {
        self.box_chars[BoxChar::CrossFull as usize]
    }

    #[inline]
    fn vertical(&self) -> char {
        self.box_chars[BoxChar::Vertical as usize]
    }
}

impl FromStr for ViewTheme {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s.to_ascii_lowercase().as_str() {
            "table" => Self::default(),
            "borderless" => Self::borderless(),
            "compact" => Self::compact(),
            "rounded" => Self::rounded(),
            "slim" => Self::slim(),
            "striped" => Self::striped(),
            _ => return Err(format!("unknown \"{}\" theme!", s)),
        })
    }
}

static USAGE: &str = "
Preview CSV data in the terminal in a human-friendly way with aligned columns,
shiny colors & all.

The command will by default try to display as many columns as possible but
will truncate cells/columns to avoid overflowing available terminal screen.

If you want to display all the columns using a pager, prefer using
the -p/--pager flag that internally rely on the ubiquitous \"less\"
command.

If you still want to use a pager manually, don't forget to use
the -e/--expand and --color=always flags before piping like so:

    $ xan view -e --color=always file.csv | less -SR

Finally, it is possible to customize the default behavior of this command through
the \"XAN_VIEW_ARGS\" environment variable. This variable takes a series of
supported flags: -t/--theme, -p/--pager, -l/--limit, -R/--rainbow, -E/--sanitize-emojis,
and -S/--significance, -I/--hide-index, --color, --repeat-headers, --reveal-whitespace
& -M/--hide-info.

To use the `borderless` theme, hide the index column and restrict the number of
floating points decimals to be shown by default, here is how it would be done
through the \"XAN_VIEW_ARGS\" variable:

    $ XAN_VIEW_ARGS=\"-t borderless -S 5 -I\"

Usage:
    xan view [options] [<input>]
    xan v [options] [<input>]
    xan view --help

view options:
    -s, --select <arg>          Select the columns to visualize. See 'xan select -h'
                                for the full syntax.
    -t, --theme <name>          Theme for the table display, one of: \"table\", \"borderless\",
                                \"compact\", \"rounded\", \"slim\" or \"striped\".
                                [default: table]
    -p, --pager                 Automatically use the \"less\" command to page the results.
                                This flag does not work on windows!
    -A, --all                   Remove the row limit and display everything.
    -l, --limit <number>        Maximum of rows to read into memory. Use -A, --all or
                                set to 0 to disable the limit.
                                [default: 100]
    -R, --rainbow               Alternating colors for columns, rather than color by value type.
    --cols <num>                Width of the graph in terminal columns, i.e. characters.
                                Defaults to using all your terminal's width or 80 if
                                terminal's size cannot be found (i.e. when piping to file).
                                Can also be given as a ratio of the terminal's width e.g. \"0.5\".
    --color <when>              When to color the output using ANSI escape codes.
                                Use `auto` for automatic detection, `never` to
                                disable colors completely and `always` to force
                                colors, even when the output could not handle them.
                                [default: auto]
    -e, --expand                Expand the table so that in can be easily piped to
                                a pager such as \"less\", with larger width constraints.
    -E, --sanitize-emojis       Replace emojis by their shortcode to avoid formatting issues.
    -S, --significance <n>      Maximum floating point significance used to format numbers.
    -I, --hide-index            Hide the row index on the left.
    -H, --hide-headers          Hide the headers. Implied when -n, --no-headers is given.
    -M, --hide-info             Hide information about number of displayed columns, rows etc.
    -g, --groupby <cols>        Isolate and emphasize groups of rows, represented by consecutive
                                rows with identical values in selected columns.
    -r, --right <col>           Force right alignment of selected columns.
    --repeat-headers <when>     When to repeat headers at the bottom of the printed table.
                                By default, the header is repeated when your terminal is too short
                                to display the full data, meaning you will need to scroll up to see
                                the headers. Use `auto` for automatic detection, `never` or `always`.
                                [default: auto]
    --reveal-whitespace <when>  When to reveal leading/trailing whitespace using mid dots and highlight
                                carriage return, tabulation, line feed etc. Those are by default
                                revealed when color is enabled for the output. Use `auto` for
                                automatic detection, `never` or `always`.
                                [default: auto]

Common options:
    -h, --help             Display this message
    -n, --no-headers       When set, the first row will not considered as being
                           the file header.
    -d, --delimiter <arg>  The field delimiter for reading CSV data.
                           Must be a single character.
";

#[derive(Deserialize, Debug)]
struct Args {
    arg_input: Option<String>,
    flag_select: SelectedColumns,
    flag_pager: bool,
    flag_theme: String,
    flag_cols: Option<String>,
    flag_delimiter: Option<Delimiter>,
    flag_no_headers: bool,
    flag_color: ColorMode,
    flag_all: bool,
    flag_limit: usize,
    flag_rainbow: bool,
    flag_expand: bool,
    flag_sanitize_emojis: bool,
    flag_hide_index: bool,
    flag_hide_headers: bool,
    flag_hide_info: bool,
    flag_groupby: Option<SelectedColumns>,
    flag_right: Option<SelectedColumns>,
    flag_significance: Option<NonZeroUsize>,
    flag_repeat_headers: ComplexToggle,
    flag_reveal_whitespace: ComplexToggle,
}

impl Args {
    fn resolve(&mut self) {
        if self.flag_all {
            self.flag_limit = 0;
        }

        if self.flag_no_headers {
            self.flag_hide_headers = true;
        }

        if self.flag_pager {
            self.flag_color = ColorMode::Always;
        }
    }

    fn infer_expand(&self) -> bool {
        self.flag_pager || self.flag_expand
    }

    fn merge(from_env: Self, mut from_argv: Self) -> Self {
        if from_argv.flag_theme == "table" && from_env.flag_theme != "table" {
            from_argv.flag_theme = from_env.flag_theme;
        }

        if !from_argv.flag_hide_index && from_env.flag_hide_index {
            from_argv.flag_hide_index = true;
        }

        if !from_argv.flag_hide_info && from_env.flag_hide_info {
            from_argv.flag_hide_info = true;
        }

        if !from_argv.flag_pager && from_env.flag_pager {
            from_argv.flag_pager = true;
        }

        if !from_argv.flag_rainbow && from_env.flag_rainbow {
            from_argv.flag_rainbow = true;
        }

        if !from_argv.flag_sanitize_emojis && from_env.flag_sanitize_emojis {
            from_argv.flag_sanitize_emojis = true;
        }

        if from_argv.flag_limit == 100 && from_env.flag_limit != 100 {
            from_argv.flag_limit = from_env.flag_limit;
        }

        if from_argv.flag_significance.is_none() && from_env.flag_significance.is_some() {
            from_argv.flag_significance = from_env.flag_significance;
        }

        if from_argv.flag_color.is_auto() && !from_env.flag_color.is_auto() {
            from_argv.flag_color = from_env.flag_color;
        }

        if from_argv.flag_repeat_headers.is_auto() && !from_env.flag_repeat_headers.is_auto() {
            from_argv.flag_repeat_headers = from_env.flag_repeat_headers;
        }

        if from_argv.flag_reveal_whitespace.is_auto() && !from_env.flag_reveal_whitespace.is_auto()
        {
            from_argv.flag_reveal_whitespace = from_env.flag_reveal_whitespace;
        }

        from_argv
    }
}

pub fn run(argv: &[&str]) -> CliResult<()> {
    let mut args: Args = util::get_args(USAGE, argv)?;
    args.resolve();

    let mut env_var_argv = vec!["xan", "view"];
    let env_var_split =
        shlex::split(&env::var("XAN_VIEW_ARGS").unwrap_or("".to_string())).unwrap_or_default();

    for env_arg in env_var_split.iter() {
        env_var_argv.push(env_arg);
    }

    let mut env_args: Args = util::get_args(USAGE, &env_var_argv)?;
    env_args.resolve();

    let mut args = Args::merge(env_args, args);
    args.flag_color.apply();

    let emoji_sanitizer = util::EmojiSanitizer::new();

    let output = io::stdout();

    let cols = util::acquire_term_cols_ratio(&args.flag_cols)?;
    let rows = termsize::get().map(|size| size.rows as usize);

    // Theme
    let theme = args.flag_theme.parse::<ViewTheme>()?;

    let padding = theme.padding;
    let horizontal_box = theme.horizontal_box();

    let rconfig = Config::new(&args.arg_input)
        .delimiter(args.flag_delimiter)
        .no_headers(args.flag_no_headers)
        .select(args.flag_select.clone());

    if rconfig.no_headers {
        args.flag_hide_headers = true;
    }

    let mut rdr = rconfig.reader()?;
    let byte_headers = rdr.byte_headers()?.clone();
    let mut sel = rconfig.selection(&byte_headers)?;

    // NOTE: the groupby selection logic is a bit complex because it must work
    // in conjunction with --select correctly.
    let mut groupby_sel_opt = args
        .flag_groupby
        .clone()
        .map(|cols| cols.selection(&byte_headers, !rconfig.no_headers))
        .transpose()?;

    if let Some(groupby_sel) = &groupby_sel_opt {
        for i in groupby_sel.iter().rev() {
            if !sel.contains(*i) {
                sel.insert(0, *i);
            }
        }
    }

    groupby_sel_opt = args
        .flag_groupby
        .clone()
        .map(|cols| {
            cols.selection(
                &sel.select(&byte_headers).collect::<csv::ByteRecord>(),
                !rconfig.no_headers,
            )
        })
        .transpose()?;

    if let (Some(groupby_sel), false) = (&mut groupby_sel_opt, args.flag_hide_index) {
        groupby_sel.offset_by(1);
    }

    let headers = rdr.headers()?.clone();
    let mut headers = sel.select(&headers).collect::<csv::StringRecord>();

    let mut right_sel_opt = args
        .flag_right
        .as_ref()
        .map(|s| s.selection(headers.as_byte_record(), !rconfig.no_headers))
        .transpose()?;

    if !args.flag_hide_index {
        headers = prepend(&headers, theme.index_column_header);

        if let Some(right_sel) = &mut right_sel_opt {
            right_sel.offset_by(1);
        }
    }

    if rconfig.no_headers {
        headers = headers
            .into_iter()
            .enumerate()
            .map(|(i, h)| {
                if args.flag_hide_index {
                    i.to_string()
                } else if i == 0 {
                    h.to_string()
                } else {
                    (i - 1).to_string()
                }
            })
            .collect();
    }

    headers = headers
        .into_iter()
        .map(util::sanitize_text_for_single_line_printing)
        .collect();

    let mut all_records_buffered = false;

    let mut number_formatter = args.flag_significance.map(|s| {
        Formatter::new()
            .precision(Precision::Significance(s.get() as u8))
            .separator(None)
            .unwrap()
    });

    let records = {
        let limit = args.flag_limit;

        let mut r_iter = rdr.into_records().enumerate();

        let mut records: Vec<csv::StringRecord> = Vec::new();

        loop {
            match r_iter.next() {
                None => break,
                Some((i, record)) => {
                    let mut record = sel
                        .select(&record?)
                        .map(|cell| {
                            let mut cell = cell.to_string();

                            cell = util::sanitize_text_for_single_line_printing(&cell);

                            if args.flag_sanitize_emojis {
                                cell = emoji_sanitizer.sanitize(&cell);
                            }

                            if let Some(fmt) = number_formatter.as_mut() {
                                if let Ok(f) = cell.parse::<f64>() {
                                    cell = util::format_number_with_formatter(fmt, f);
                                }
                            }

                            cell
                        })
                        .collect::<csv::StringRecord>();

                    if !args.flag_hide_index {
                        record = prepend(&record, &i.to_string());
                    }

                    records.push(record);

                    if limit > 0 && records.len() == limit {
                        break;
                    }
                }
            };
        }

        if r_iter.next().is_none() {
            all_records_buffered = true;
        }

        records
    };

    if records.is_empty() && byte_headers.is_empty() {
        Err("either input is completely empty or piped process errored upstream!")?;
    }

    let need_to_repeat_headers = match args.flag_repeat_headers {
        ComplexToggle::Auto => {
            let mut auto = match rows {
                None => true,
                Some(r) => records.len() + HEADERS_ROWS > r,
            };

            if args.flag_pager {
                auto = false;
            }

            auto
        }
        ComplexToggle::Always => true,
        ComplexToggle::Never => false,
    };

    let reveal_whitespace = match args.flag_reveal_whitespace {
        ComplexToggle::Auto => colored::control::SHOULD_COLORIZE.should_colorize(),
        ComplexToggle::Always => true,
        ComplexToggle::Never => false,
    };

    let max_column_widths: Vec<usize> = headers
        .iter()
        .enumerate()
        .map(|(i, h)| {
            usize::max(
                if args.flag_hide_headers { 0 } else { h.width() },
                records
                    .iter()
                    .map(|c| match c[i].width() {
                        0 => 7, // NOTE: taking <empty> into account
                        v => v,
                    })
                    .max()
                    .unwrap_or(0),
            )
        })
        .collect();

    // Alignment inference
    // TODO: type tagging for values should happen on initial read
    let right_sel_mask_opt = right_sel_opt.map(|sel| sel.mask(headers.len()));

    let alignments = (0..headers.len())
        .map(|i| {
            if !args.flag_hide_index && i == 0 {
                return false;
            }

            if let Some(right_sel_mask) = &right_sel_mask_opt {
                if right_sel_mask[i] {
                    return true;
                }
            }

            records.iter().all(|r| {
                let cell = &r[i];

                cell.is_empty() || cell.parse::<i64>().is_ok()
            })
        })
        .collect::<Vec<_>>();

    // Width inference
    let displayed_columns = infer_best_column_display(
        cols,
        &max_column_widths,
        args.infer_expand(),
        if args.flag_hide_index { 0 } else { 1 },
        padding,
    );

    let all_columns_shown = displayed_columns.len() == headers.len();

    // NOTE: we setup the pager when everything has been read and process and no error
    // occurred along the way, so that we don't get to read a paged error
    if args.flag_pager {
        #[cfg(not(windows))]
        {
            pager::Pager::with_pager("less -SR").setup();
        }

        #[cfg(windows)]
        {
            Err("The -p/--pager flag does not work on windows, sorry :'(".to_string())?;
        }
    }

    let write_info = || -> Result<(), io::Error> {
        if args.flag_hide_info {
            return Ok(());
        }

        let len_offset = if args.flag_hide_index { 0 } else { 1 };

        let pretty_records_len = util::format_number(records.len());
        let pretty_headers_len = util::format_number(headers.len() - len_offset);
        let pretty_displayed_headers_len =
            util::format_number(displayed_columns.len() - len_offset);

        writeln!(
            &output,
            "Displaying {} col{} from {} of {}",
            if all_columns_shown {
                format!("{}", pretty_headers_len.cyan())
            } else {
                format!(
                    "{}/{}",
                    pretty_displayed_headers_len.cyan(),
                    pretty_headers_len.cyan(),
                )
            },
            if headers.len() > 2 { "s" } else { "" },
            if all_records_buffered {
                format!("{} rows", pretty_records_len.cyan())
            } else {
                format!("{} first rows", pretty_records_len.cyan())
            },
            match &args.arg_input {
                Some(filename) => filename,
                None => "<stdin>",
            }
            .dimmed()
        )?;

        Ok(())
    };

    enum HRPosition {
        Top,
        Middle,
        Bottom,
    }

    let write_horizontal_ruler = |pos: HRPosition| -> Result<(), io::Error> {
        let mut s = String::new();

        if theme.external_borders {
            s.push(match pos {
                HRPosition::Bottom => theme.corner_up_left(),
                HRPosition::Top => theme.corner_bottom_left(),
                HRPosition::Middle => theme.cross_right(),
            });
        }

        displayed_columns.iter().enumerate().for_each(|(i, col)| {
            s.push_str(&horizontal_box.repeat(
                col.allowed_width + 2 * padding.len()
                    - (if i == 0 && !theme.external_borders {
                        1
                    } else {
                        0
                    }),
            ));

            if !all_columns_shown && Some(i) == displayed_columns.split_point() {
                s.push(match pos {
                    HRPosition::Bottom => theme.cross_bottom(),
                    HRPosition::Top => theme.cross_up(),
                    HRPosition::Middle => theme.cross_full(),
                });

                s.push_str(&horizontal_box.repeat(1 + 2 * padding.len()));
            }

            if i == displayed_columns.len() - 1 {
                return;
            }

            s.push(match pos {
                HRPosition::Bottom => theme.cross_bottom(),
                HRPosition::Top => theme.cross_up(),
                HRPosition::Middle => theme.cross_full(),
            });
        });

        if theme.external_borders {
            s.push(match pos {
                HRPosition::Bottom => theme.corner_up_right(),
                HRPosition::Top => theme.corner_bottom_right(),
                HRPosition::Middle => theme.cross_left(),
            });
        }

        writeln!(&output, "{}", s.dimmed())?;

        Ok(())
    };

    let write_row = |row: Vec<colored::ColoredString>, mut dimmed: bool| -> Result<(), io::Error> {
        if !theme.striped {
            dimmed = false;
        }

        if theme.external_borders {
            write!(
                &output,
                "{}",
                format!("{}{}", theme.vertical(), padding).dimmed()
            )?;
        }

        for (i, cell) in row.iter().enumerate() {
            if i != 0 {
                write!(
                    &output,
                    "{}",
                    format!("{}{}{}", padding, theme.vertical(), padding).dimmed()
                )?;
            }

            if dimmed {
                write!(&output, "{}", cell.clone().reversed())?;
            } else {
                write!(&output, "{}", cell)?;
            }

            if !all_columns_shown && Some(i) == displayed_columns.split_point() {
                write!(
                    &output,
                    "{}",
                    format!("{}{}{}", padding, theme.vertical(), padding).dimmed(),
                )?;
            }
        }

        if theme.external_borders {
            write!(
                &output,
                "{}",
                format!("{}{}", padding, theme.vertical()).dimmed()
            )?;
        }

        writeln!(&output)?;

        Ok(())
    };

    let write_headers = |above: bool| -> Result<(), io::Error> {
        if above || theme.hr_under_headers {
            write_horizontal_ruler(if above {
                HRPosition::Bottom
            } else {
                HRPosition::Middle
            })?;
        }

        let headers_row: Vec<colored::ColoredString> = displayed_columns
            .iter()
            .map(|col| (col, &headers[col.index]))
            .enumerate()
            .map(|(i, (col, h))| {
                let cell = util::unicode_aware_highlighted_pad_with_ellipsis(
                    false,
                    h,
                    col.allowed_width,
                    " ",
                    reveal_whitespace,
                );

                if !args.flag_hide_index && i == 0 {
                    cell.dimmed()
                } else {
                    cell.bold()
                }
            })
            .collect();

        write_row(headers_row, false)?;

        if !above || theme.hr_under_headers {
            write_horizontal_ruler(if above {
                HRPosition::Middle
            } else {
                HRPosition::Top
            })?;
        }

        Ok(())
    };

    writeln!(&output)?;
    write_info()?;

    // NOTE: we stop if there is nothing to show
    let nothing_to_show =
        records.is_empty() && (headers.is_empty() || (!args.flag_hide_index && headers.len() == 1));

    if nothing_to_show {
        return Ok(());
    }

    if args.flag_hide_headers {
        write_horizontal_ruler(HRPosition::Bottom)?;
    } else {
        write_headers(true)?;
    }

    let mut last_group: Option<Vec<String>> = None;
    let mut record_i: usize = 0;

    for record in records.iter() {
        let (need_to_draw_hr, need_to_erase_sel) = if let Some(groupby_sel) = &groupby_sel_opt {
            let current_key = groupby_sel
                .select(record)
                .map(|cell| cell.to_string())
                .collect::<Vec<_>>();

            match &last_group {
                None => {
                    last_group = Some(current_key);
                    (false, false)
                }
                Some(last_key) if last_key != &current_key => {
                    last_group = Some(current_key);
                    (true, false)
                }
                _ => (false, true),
            }
        } else {
            (false, false)
        };

        if need_to_draw_hr {
            write_horizontal_ruler(HRPosition::Middle)?;
        }

        let row: Vec<colored::ColoredString> = displayed_columns
            .iter()
            .map(|col| (col, &record[col.index]))
            .enumerate()
            .map(|(i, (col, cell))| {
                if let Some(groupby_sel) = &groupby_sel_opt {
                    if need_to_erase_sel && groupby_sel.contains(i) {
                        return " ".repeat(col.allowed_width).normal();
                    }
                }

                let cell = match cell {
                    "" => "<empty>",
                    _ => cell,
                };

                let colorizer = if args.flag_rainbow {
                    util::colorizer_by_rainbow(i, cell)
                } else {
                    util::colorizer_by_type(cell)
                };

                if !args.flag_hide_index && i == 0 {
                    util::unicode_aware_rpad_with_ellipsis(cell, col.allowed_width, " ").dimmed()
                } else {
                    util::colorize(
                        &colorizer,
                        &util::unicode_aware_highlighted_pad_with_ellipsis(
                            alignments[col.index],
                            cell,
                            col.allowed_width,
                            " ",
                            reveal_whitespace,
                        ),
                    )
                }
            })
            .collect();

        write_row(row, record_i % 2 == 0)?;
        record_i += 1;
    }

    if !all_records_buffered {
        let row: Vec<colored::ColoredString> = displayed_columns
            .iter()
            .map(|col| {
                util::unicode_aware_pad_with_ellipsis(
                    alignments[col.index],
                    "",
                    col.allowed_width,
                    " ",
                )
                .dimmed()
            })
            .collect();

        write_row(row, record_i % 2 == 0)?;
    }

    if need_to_repeat_headers {
        if args.flag_hide_headers {
            write_horizontal_ruler(HRPosition::Top)?;
        } else {
            write_headers(false)?;
        }
        write_info()?;
        writeln!(&output)?;
    } else {
        write_horizontal_ruler(HRPosition::Top)?;
        writeln!(&output)?;
    }

    Ok(())
}

fn adjust_column_widths(widths: &[usize], max_width: usize) -> Vec<usize> {
    widths.iter().map(|m| usize::min(*m, max_width)).collect()
}

#[derive(Debug)]
struct DisplayedColumn {
    index: usize,
    allowed_width: usize,
    max_width: usize,
}

#[derive(Debug)]
struct DisplayedColumns {
    max_allowed_cols: usize,
    left: Vec<DisplayedColumn>,
    // NOTE: columns are inserted into right in reversed order
    right: Vec<DisplayedColumn>,
}

impl DisplayedColumns {
    fn new(max_allowed_cols: usize) -> Self {
        DisplayedColumns {
            max_allowed_cols,
            left: Vec::new(),
            right: Vec::new(),
        }
    }

    fn split_point(&self) -> Option<usize> {
        self.left.last().map(|col| col.index)
    }

    fn from_widths(cols: usize, widths: Vec<usize>) -> Self {
        let left = widths
            .iter()
            .copied()
            .enumerate()
            .map(|(i, w)| DisplayedColumn {
                index: i,
                allowed_width: w,
                max_width: w,
            })
            .collect::<Vec<_>>();

        DisplayedColumns {
            max_allowed_cols: cols,
            left,
            right: Vec::new(),
        }
    }

    fn len(&self) -> usize {
        self.left.len() + self.right.len()
    }

    fn fitting_count(&self) -> usize {
        self.iter()
            .filter(|col| col.allowed_width == col.max_width)
            .count()
    }

    fn push(&mut self, left: bool, index: usize, allowed_width: usize, max_width: usize) {
        let col = DisplayedColumn {
            index,
            allowed_width,
            max_width,
        };

        if left {
            self.left.push(col);
        } else {
            self.right.push(col);
        }
    }

    fn iter(&self) -> DisplayedColumnsIter<'_> {
        DisplayedColumnsIter {
            iter_left: self.left.iter(),
            iter_right: self.right.iter(),
        }
    }
}

struct DisplayedColumnsIter<'a> {
    iter_left: std::slice::Iter<'a, DisplayedColumn>,
    iter_right: std::slice::Iter<'a, DisplayedColumn>,
}

impl<'a> Iterator for DisplayedColumnsIter<'a> {
    type Item = &'a DisplayedColumn;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter_left
            .next()
            .or_else(|| self.iter_right.next_back())
    }
}

// NOTE: greedy way to find best ratio for columns
// We basically test a range of dividers based on the number of columns in the
// CSV file and we try to find the organization optimizing the number of columns
// fitting perfectly, then the number of columns displayed.
fn infer_best_column_display(
    cols: usize,
    max_column_widths: &[usize],
    expand: bool,
    left_advantage: usize,
    padding: &str,
) -> DisplayedColumns {
    if expand {
        // NOTE: we keep max column size to 3/4 of current screen
        return DisplayedColumns::from_widths(
            cols,
            adjust_column_widths(max_column_widths, ((cols as f64) * 0.75) as usize),
        );
    }

    let per_cell_padding_cols = padding.len() * 2 + 1;
    let ellipsis_padding_cols = padding.len() * 4 + 4;

    let mut attempts: Vec<DisplayedColumns> = Vec::new();

    // NOTE: we could also proceed by col increments rather than dividers I suppose
    let extra_dividers = [1.05, 1.1, 2.5];

    let mut dividers = extra_dividers
        .iter()
        .copied()
        .chain((1..=max_column_widths.len()).map(|d| d as f64))
        .collect::<Vec<_>>();

    dividers.sort_by(|a, b| a.total_cmp(b));

    // TODO: this code can be greatly optimized and early break
    // NOTE: here we iteratively test for a range of max width being a division
    // of the term width. But we could also test for an increasing number of
    // columns, all while respecting the width proportion of each column compared
    // to the other selected ones.
    for divider in dividers {
        let max_allowed_width = (cols as f64 / divider) as usize;

        // If we don't have reasonable space we break
        if max_allowed_width <= 3 {
            break;
        }

        let mut attempt = DisplayedColumns::new(max_allowed_width);

        let widths = adjust_column_widths(max_column_widths, max_allowed_width);

        let mut col_budget = cols - ellipsis_padding_cols;
        let mut widths_iter = widths.iter().enumerate();
        let mut toggle = true;
        let mut left_leaning = left_advantage;

        loop {
            let value = if toggle {
                widths_iter
                    .next()
                    .map(|step| (step, true))
                    .or_else(|| widths_iter.next_back().map(|step| (step, false)))
            } else {
                widths_iter
                    .next_back()
                    .map(|step| (step, false))
                    .or_else(|| widths_iter.next().map(|step| (step, true)))
            };

            if let Some(((i, column_width), left)) = value {
                // NOTE: we favor left-leaning columns because of
                // the index column or just for aesthetical reasons
                if left_leaning > 0 {
                    left_leaning -= 1;
                } else {
                    toggle = !toggle;
                }

                if col_budget == 0 {
                    break;
                }

                if *column_width + per_cell_padding_cols > col_budget {
                    if col_budget > 7 {
                        attempt.push(left, i, col_budget, max_column_widths[i]);
                    }
                    break;
                }

                col_budget -= column_width + per_cell_padding_cols;
                attempt.push(left, i, *column_width, max_column_widths[i]);
            } else {
                break;
            }
        }

        attempts.push(attempt);
    }

    // NOTE: we sort by number of columns fitting perfectly, then number of
    // columns we can display, then the maximum cols one cell can have
    attempts
        .into_iter()
        .max_by_key(|a| (a.fitting_count(), a.len(), a.max_allowed_cols))
        .unwrap()
}