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
// Copyright (c) 2018 10x Genomics, Inc. All rights reserved.

// Functions print_tabular and print_tabular_vbox for making pretty tables.  And related utilities.

extern crate io_utils;
extern crate itertools;
extern crate string_utils;

use io_utils::*;
use itertools::Itertools;
use std::cmp::{max, min};
use string_utils::*;

// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓

// Package characters with ANSI escape codes that come before them.

pub fn package_characters_with_escapes(c: &Vec<u8>) -> Vec<Vec<u8>> {
    let mut x = Vec::<Vec<u8>>::new();
    let mut escaped = false;
    let mut package = Vec::<u8>::new();
    for b in c.iter() {
        if escaped && *b != b'm' {
            package.push(*b);
        } else if *b == b'' {
            escaped = true;
            package.push(*b);
        } else if escaped && *b == b'm' {
            escaped = false;
            package.push(*b);
        } else {
            package.push(*b);
            x.push(package.clone());
            package.clear();
        }
    }
    x
}

pub fn package_characters_with_escapes_char(c: &Vec<char>) -> Vec<Vec<char>> {
    let mut x = Vec::<Vec<char>>::new();
    let mut escaped = false;
    let mut package = Vec::<char>::new();
    for b in c.iter() {
        if escaped && *b != 'm' {
            package.push(*b);
        } else if *b == '' {
            escaped = true;
            package.push(*b);
        } else if escaped && *b == 'm' {
            escaped = false;
            package.push(*b);
        } else {
            package.push(*b);
            x.push(package.clone());
            package.clear();
        }
    }
    x
}

// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓

// Print out a matrix, with left-justified entries, and given separation between
// columns.  (Justification may be changed by supplying an optional argument
// consisting of a string of l's and r's.)

pub fn print_tabular(
    log: &mut Vec<u8>,
    rows: &Vec<Vec<String>>,
    sep: usize,
    justify: Option<Vec<u8>>,
) {
    let just = match justify {
        Some(x) => x,
        None => Vec::<u8>::new(),
    };
    let nrows = rows.len();
    let mut ncols = 0;
    for i in 0..nrows {
        ncols = max(ncols, rows[i].len());
    }
    let mut maxcol = vec![0; ncols];
    for i in 0..rows.len() {
        for j in 0..rows[i].len() {
            maxcol[j] = max(maxcol[j], rows[i][j].chars().count());
        }
    }
    for i in 0..rows.len() {
        for j in 0..rows[i].len() {
            let x = rows[i][j].clone();
            if j < just.len() && just[j] == b'r' {
                log.append(&mut vec![b' '; maxcol[j] - x.chars().count()]);
                log.append(&mut x.as_bytes().to_vec());
                if j < rows[i].len() - 1 {
                    log.append(&mut vec![b' '; sep]);
                }
            } else {
                log.append(&mut x.as_bytes().to_vec());
                if j < rows[i].len() - 1 {
                    log.append(&mut vec![b' '; maxcol[j] - x.chars().count() + sep]);
                }
            }
        }
        log.push(b'\n');
    }
}

// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓

// Compute the visible length of a string, counting unicode characters as width one and
// ignoring some ASCII escape sequences.

pub fn visible_width(s: &str) -> usize {
    let mut n = 0;
    let mut escaped = false;
    for c in s.chars() {
        if escaped && c != 'm' {
        } else if c == '' {
            escaped = true;
        } else if escaped && c == 'm' {
            escaped = false;
        } else {
            n += 1;
        }
    }
    n
}

// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓

// Print out a matrix, with given separation between columns.  Rows of the matrix
// may contain arbitrary UTF-8 and some escape sequences.  Put the entire thing in a box, with
// extra vertical bars.  The argument justify consists of symbols l and r, denoting
// left and right justification for given columns, respectively, and the symbol | to
// denote a vertical bar.
//
// There is no separation printed on the far left or far right.
//
// By a "matrix entry", we mean one of the Strings in "rows".
//
// Entries that begin with a backslash are reserved for future features.
// Symbols other than l or r or | in "justify" are reserved for future features.
//
// An entry may be followed on the right by one more entries whose contents are
// exactly "\ext".  In that case the entries are treated as multi-column.  Padding
// is inserted as needed on the "right of the multicolumn".
//
// An entry may be "\hline", which gets you a horizontal line.  The normal use case is to
// use one or more of these in succession horizontally to connect two vertical lines.  Cannot
// be combined with \ext.
//
// bold_box: use bold box characters
//
// Really only guaranteed to work for the tested cases.

pub fn print_tabular_vbox(
    log: &mut String,
    rows: &Vec<Vec<String>>,
    sep: usize,
    justify: &Vec<u8>,
    debug_print: bool,
    bold_box: bool,
) {
    // Define box characters.

    let dash;
    if !bold_box {
        dash = '─';
    } else {
        dash = '━';
    }
    let verty;
    if !bold_box {
        verty = '│';
    } else {
        verty = '┃';
    }
    let topleft;
    if !bold_box {
        topleft = '┌';
    } else {
        topleft = '┏';
    }
    let topright;
    if !bold_box {
        topright = '┐';
    } else {
        topright = '┓';
    }
    let botleft;
    if !bold_box {
        botleft = '└';
    } else {
        botleft = '┗';
    }
    let botright;
    if !bold_box {
        botright = '┘';
    } else {
        botright = '┛';
    }
    let tee;
    if !bold_box {
        tee = '┬';
    } else {
        tee = '┳';
    }
    let uptee;
    if !bold_box {
        uptee = '┴';
    } else {
        uptee = '┻';
    }
    let cross;
    if !bold_box {
        cross = '┼';
    } else {
        cross = '╋';
    }
    let lefty;
    if !bold_box {
        lefty = '├';
    } else {
        lefty = '┣';
    }
    let righty;
    if !bold_box {
        righty = '┤';
    } else {
        righty = '┫';
    }

    // Proceed.

    let mut rrr = rows.clone();
    let nrows = rrr.len();
    let mut ncols = 0;
    for i in 0..nrows {
        ncols = max(ncols, rrr[i].len());
    }
    let mut vert = vec![false; ncols];
    let mut just = Vec::<u8>::new();
    let mut count = 0 as isize;
    for i in 0..justify.len() {
        if justify[i] == b'|' {
            assert!(count > 0);
            if count >= ncols as isize {
                eprintln!("\nposition of | in justify string is illegal");
                eprintme!(count, ncols);
            }
            assert!(count < ncols as isize);
            vert[(count - 1) as usize] = true;
        } else {
            just.push(justify[i]);
            count += 1;
        }
    }
    if just.len() != ncols {
        eprintln!(
            "\nError.  Your table has {} columns but the number of \
             l or r symbols in justify is {}.\nThese numbers should be equal.",
            ncols,
            just.len()
        );
        eprintln!("justify = {}", strme(&justify));
        for i in 0..rows.len() {
            eprintln!(
                "row {} = {} = {}",
                i + 1,
                rows[i].len(),
                rows[i].iter().format(",")
            );
        }
        assert_eq!(just.len(), ncols);
    }
    let mut maxcol = vec![0; ncols];
    let mut ext = vec![0; ncols];
    for i in 0..rrr.len() {
        for j in 0..rrr[i].len() {
            if j < rrr[i].len() - 1 && rrr[i][j + 1] == "\\ext".to_string() {
                continue;
            }
            if rrr[i][j] == "\\ext".to_string() || rrr[i][j] == "\\hline".to_string() {
                continue;
            }
            maxcol[j] = max(maxcol[j], visible_width(&rrr[i][j]));
        }
    }
    if debug_print {
        println!("maxcol = {}", maxcol.iter().format(","));
    }

    // Add space according to ext entries.

    for i in 0..rrr.len() {
        for j in 0..rrr[i].len() {
            if j < rrr[i].len() - 1
                && rrr[i][j + 1] == "\\ext".to_string()
                && rrr[i][j] != "\\ext".to_string()
            {
                let mut k = j + 1;
                while k < rrr[i].len() {
                    if rrr[i][k] != "\\ext".to_string() {
                        break;
                    }
                    k += 1;
                }
                let need = visible_width(&rrr[i][j]);
                let mut have = 0;
                for l in j..k {
                    have += maxcol[l];
                    if l < k - 1 {
                        have += sep;
                        if vert[l] {
                            have += sep + 1;
                        }
                    }
                }
                if debug_print {
                    println!("row {} column {}, have = {}, need = {}", i, j, have, need);
                }
                if have > need {
                    if debug_print {
                        println!(
                            "adding {} spaces to right of row {} col {}",
                            have - need,
                            i,
                            j
                        );
                    }
                    for _ in need..have {
                        rrr[i][j].push(' ');
                    }
                } else if need > have {
                    maxcol[k - 1] += need - have;
                    if debug_print {
                        println!("increasing maxcol[{}] to {}", k - 1, maxcol[k - 1]);
                    }
                    ext[k - 1] += need - have;
                }
                let mut m = 0;
                for u in 0..rrr.len() {
                    if j >= rrr[u].len() {
                        eprintln!("\nProblem with line {}, not enough fields.\n", u);
                    }
                    if rrr[u][j] != "\\ext".to_string() {
                        m = max(m, visible_width(&rrr[u][j]));
                    }
                }
                if m > visible_width(&rrr[i][j]) {
                    for _ in visible_width(&rrr[i][j])..m {
                        rrr[i][j].push(' ');
                    }
                }
            }
        }
    }

    // Create top boundary of table.

    log.push(topleft);
    for i in 0..ncols {
        let mut n = maxcol[i];
        if i < ncols - 1 {
            n += sep;
        }
        for _ in 0..n {
            log.push(dash);
        }
        if vert[i] {
            log.push(tee);
            for _ in 0..sep {
                log.push(dash);
            }
        }
    }
    log.push(topright);
    log.push('\n');

    // Go through the rows.

    for i in 0..nrows {
        if debug_print {
            println!("now row {} = {}", i, rrr[i].iter().format(","));
            println!("0 - pushing │ onto row {}", i);
        }
        log.push(verty);
        for j in 0..min(ncols, rrr[i].len()) {
            // Pad entries according to justification.

            let mut x = String::new();
            if j >= rrr[i].len() {
                for _ in 0..maxcol[j] {
                    x.push(' ');
                }
            } else if rrr[i][j] == "\\hline".to_string() {
                for _ in 0..maxcol[j] {
                    x.push(dash);
                }
            } else {
                let r = rrr[i][j].clone();
                let rlen = visible_width(&r);
                let mut xlen = 0;
                if r != "\\ext".to_string() {
                    if just[j] == b'r' {
                        for _ in rlen..(maxcol[j] - ext[j]) {
                            x.push(' ');
                            xlen += 1;
                        }
                    }
                    if j < rrr[i].len() {
                        x += &r;
                        xlen += visible_width(&r);
                    }
                    if just[j] == b'r' {
                        for _ in (maxcol[j] - ext[j])..maxcol[j] {
                            x.push(' ');
                            xlen += 1;
                        }
                    }
                    if just[j] == b'l' {
                        for _ in xlen..maxcol[j] {
                            x.push(' ');
                        }
                    }
                }
            }
            for c in x.chars() {
                log.push(c);
            }

            // Add separations and separators.

            let mut add_sep = true;
            if j + 1 < rrr[i].len() && rrr[i][j + 1] == "\\ext".to_string() {
                add_sep = false;
            }
            let mut jp = j;
            while jp + 1 < rrr[i].len() {
                if rrr[i][jp + 1] != "\\ext".to_string() {
                    break;
                }
                jp += 1;
            }
            if add_sep && jp < ncols - 1 {
                if rrr[i][j] == "\\hline".to_string() {
                    for _ in 0..sep {
                        log.push(dash);
                    }
                } else {
                    for _ in 0..sep {
                        log.push(' ');
                    }
                }
            }
            if vert[j] && rrr[i][j + 1] != "\\ext" {
                if debug_print {
                    println!("1 - pushing {} onto row {}, j = {}", verty, i, j);
                }
                log.push(verty);
                if rrr[i][j + 1] == "\\hline".to_string() {
                    for _ in 0..sep {
                        log.push(dash);
                    }
                } else {
                    for _ in 0..sep {
                        log.push(' ');
                    }
                }
            }
        }
        if debug_print {
            println!("2 - pushing {} onto row {}", verty, i);
        }
        log.push(verty);
        log.push('\n');
    }
    log.push(botleft);
    for i in 0..ncols {
        let mut n = maxcol[i];
        if i < ncols - 1 {
            n += sep;
        }
        for _ in 0..n {
            log.push(dash);
        }
        if vert[i] {
            if rrr[rrr.len() - 1][i + 1] != "\\ext" {
                log.push(uptee);
            } else {
                log.push(dash);
            }
            for _ in 0..sep {
                log.push(dash);
            }
        }
    }
    log.push(botright);
    log.push('\n');

    // Convert into a super-character vec of matrices.  There is one vector entry per line.
    // In each matrix, an entry is a super_character: a rust character, together with the escape
    // code characters that came before it.

    let mut mat = Vec::<Vec<Vec<char>>>::new();
    {
        let mut all = Vec::<Vec<char>>::new();
        let mut z = Vec::<char>::new();
        for c in log.chars() {
            if c != '\n' {
                z.push(c);
            } else {
                if !z.is_empty() {
                    all.push(z.clone());
                }
                z.clear();
            }
        }
        if !z.is_empty() {
            all.push(z);
        }
        for i in 0..all.len() {
            mat.push(package_characters_with_escapes_char(&all[i]));
        }
    }

    // "Smooth" edges of hlines.

    for i in 0..mat.len() {
        for j in 0..mat[i].len() {
            if j > 0
                && mat[i][j - 1] == vec![dash]
                && mat[i][j] == vec![verty]
                && j + 1 < mat[i].len()
                && mat[i][j + 1] == vec![dash]
                && i + 1 < mat.len()
                && j < mat[i + 1].len()
                && mat[i + 1][j] != vec![verty]
            {
                mat[i][j] = vec![uptee];
            } else if j > 0
                && mat[i][j - 1] == vec![dash]
                && mat[i][j] == vec![verty]
                && j + 1 < mat[i].len()
                && mat[i][j + 1] == vec![dash]
            {
                mat[i][j] = vec![cross];
            } else if mat[i][j] == vec![verty]
                && j + 1 < mat[i].len()
                && mat[i][j + 1] == vec![dash]
            {
                mat[i][j] = vec![lefty];
            } else if j > 0
                && mat[i][j - 1] == vec![dash]
                && mat[i][j] == vec![verty]
                && (j + 1 == mat[i].len() || mat[i][j + 1] != vec![dash])
            {
                mat[i][j] = vec![righty];
            }
        }
    }

    // Output matrix.

    log.clear();
    for i in 0..mat.len() {
        for j in 0..mat[i].len() {
            for k in 0..mat[i][j].len() {
                log.push(mat[i][j][k]);
            }
        }
        log.push('\n');
    }

    // Finish.

    if debug_print {
        println!("");
    }
}

// ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓

#[cfg(test)]
mod tests {

    // run this test using:
    // cargo test -p tenkit2 test_print_tabular_vbox

    use crate::print_tabular_vbox;

    // (should add some escape codes)

    #[test]
    fn test_print_tabular_vbox() {
        // test 1

        let mut rows = Vec::<Vec<String>>::new();
        let row = vec![
            "omega".to_string(),
            "superduperfineexcellent".to_string(),
            "\\ext".to_string(),
        ];
        rows.push(row);
        let row = vec![
            "woof".to_string(),
            "snarl".to_string(),
            "octopus".to_string(),
        ];
        rows.push(row);
        let row = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        rows.push(row);
        let row = vec![
            "hiccup".to_string(),
            "tomatillo".to_string(),
            "ddd".to_string(),
        ];
        rows.push(row);
        let mut log = String::new();
        let mut justify = Vec::<u8>::new();
        justify.push(b'r');
        justify.push(b'|');
        justify.push(b'l');
        justify.push(b'l');
        print_tabular_vbox(&mut log, &rows, 2, &justify, false, false);
        let answer = "┌────────┬─────────────────────────┐\n\
                      │ omega  │  superduperfineexcellent│\n\
                      │  woof  │  snarl      octopus     │\n\
                      │     a  │  b          c           │\n\
                      │hiccup  │  tomatillo  ddd         │\n\
                      └────────┴─────────────────────────┘\n";
        if log != answer {
            println!("\ntest 1 failed");
            println!("\nyour answer:\n{}", log);
            println!("correct answer:\n{}", answer);
        }
        if log != answer {
            panic!();
        }

        // test 2

        let mut rows = Vec::<Vec<String>>::new();
        let row = vec!["pencil".to_string(), "pusher".to_string()];
        rows.push(row);
        let row = vec!["\\hline".to_string(), "\\hline".to_string()];
        rows.push(row);
        let row = vec!["fabulous pumpkins".to_string(), "\\ext".to_string()];
        rows.push(row);
        let mut log = String::new();
        let mut justify = Vec::<u8>::new();
        justify.push(b'l');
        justify.push(b'|');
        justify.push(b'l');
        print_tabular_vbox(&mut log, &rows, 2, &justify, false, false);
        let answer = "┌────────┬────────┐\n\
                      │pencil  │  pusher│\n\
                      ├────────┴────────┤\n\
                      │fabulous pumpkins│\n\
                      └─────────────────┘\n";
        if log != answer {
            println!("\ntest 2 failed");
            println!("\nyour answer:\n{}", log);
            println!("correct answer:\n{}", answer);
        }
        if log != answer {
            panic!();
        }
    }
}