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
//! Print ASCII tables to the terminal.
//!
//! # Example
//!
//! ```
//! use ascii_table::AsciiTable;
//!
//! let ascii_table = AsciiTable::default();
//! let data = vec![&[1, 2, 3], &[4, 5, 6], &[7, 8, 9]];
//! ascii_table.print(data);
//! // ┌───┬───┬───┐
//! // │ 1 │ 2 │ 3 │
//! // │ 4 │ 5 │ 6 │
//! // │ 7 │ 8 │ 9 │
//! // └───┴───┴───┘
//! ```
//!
//! # Example
//!
//! ```
//! use std::fmt::Display;
//! use ascii_table::{AsciiTable, Align};
//!
//! let mut ascii_table = AsciiTable::default();
//! ascii_table.set_max_width(26);
//! ascii_table.column(0).set_header("H1").set_align(Align::Left);
//! ascii_table.column(1).set_header("H2").set_align(Align::Center);
//! ascii_table.column(2).set_header("H3").set_align(Align::Right);
//!
//! let data: Vec<Vec<&dyn Display>> = vec![
//!     vec![&'v', &'v', &'v'],
//!     vec![&123, &456, &789, &"abcdef"]
//! ];
//! ascii_table.print(data);
//! // ┌─────┬─────┬─────┬──────┐
//! // │ H1  │ H2  │ H3  │      │
//! // ├─────┼─────┼─────┼──────┤
//! // │ v   │  v  │   v │      │
//! // │ 123 │ 456 │ 789 │ abc+ │
//! // └─────┴─────┴─────┴──────┘
//! ```
//!
//! ## Features
//!
//! - `auto_table_width`: Sets the default max width of the ascii table to the width of the terminal.
//! - `color_codes`: Correctly calculates the width of a string when terminal color codes are present
//!   (like those from the `colorful` crate).
//! - `wide_characters`: Correctly calculates the width of a string when wide characters are present
//!   (like emoli's).

#[cfg(test)]
mod test;

#[cfg(feature = "color_codes")]
use ::lazy_static::lazy_static;
#[cfg(feature = "color_codes")]
use ::regex::Regex;
#[cfg(feature = "wide_characters")]
use ::unicode_width::UnicodeWidthStr;

use ::std::collections::BTreeMap;
use ::std::fmt::Display;

const DEFAULT_WIDTH: usize = 100;
const SE: &str = "┌";
const NW: &str = "┘";
const SW: &str = "┐";
const NS: &str = "│";
const NE: &str = "└";
const EWS: &str = "┬";
const NES: &str = "├";
const NWS: &str = "┤";
const NEW: &str = "┴";
const NEWS: &str = "┼";
const EW: &str = "─";

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct AsciiTable {
    max_width: Option<usize>,
    columns: BTreeMap<usize, Column>,
}

impl AsciiTable {
    /// Sets the maximum width of the table.
    ///
    /// When you use the feature `auto_table_width` the maximum width will be calculated when you
    /// render the table. Note that the value set by this function will take precedence over the value
    /// generated by `auto_table_width`.
    pub fn set_max_width(&mut self, max_width: usize) -> &mut Self {
        self.max_width = Some(max_width);
        self
    }

    /// Gets the maximum width used to render tables. This is either the default width, the width calculated
    /// by the feature `auto_table_width` or the width specified by `set_max_width`.
    pub fn max_width(&self) -> usize {
        match self.max_width {
            Some(width) => width,
            None => default_table_width(),
        }
    }

    pub fn column(&mut self, index: usize) -> &mut Column {
        self.columns.entry(index).or_default()
    }
}

#[cfg(feature = "auto_table_width")]
fn default_table_width() -> usize {
    ::termion::terminal_size()
        .map(|(width, _)| width.into())
        .unwrap_or(DEFAULT_WIDTH)
}

#[cfg(not(feature = "auto_table_width"))]
fn default_table_width() -> usize {
    DEFAULT_WIDTH
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Column {
    header: String,
    align: Align,
    max_width: usize,
}

impl Column {
    /// Sets the value for the header row. When none of the table's columns has a header value then
    /// the header row wont be rendered.
    pub fn set_header<T>(&mut self, header: T) -> &mut Self
    where
        T: Into<String>,
    {
        self.header = header.into();
        self
    }

    pub fn header(&self) -> &str {
        &self.header
    }

    pub fn set_align(&mut self, align: Align) -> &mut Self {
        self.align = align;
        self
    }

    pub fn align(&self) -> Align {
        self.align
    }

    /// Sets the maximum width of the content (rendered text) for this column.
    ///
    /// The maximum width of the table takes precedence over the maximum width of its columns. So you
    /// can't use the columns maximum width to extends the table beyond its maximum width.
    pub fn set_max_width(&mut self, max_width: usize) -> &mut Self {
        self.max_width = max_width;
        self
    }

    pub fn max_width(&self) -> usize {
        self.max_width
    }
}

impl Default for Column {
    fn default() -> Self {
        Column {
            header: Default::default(),
            align: Default::default(),
            max_width: usize::max_value(),
        }
    }
}

/// Alignment of text in a cell.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum Align {
    #[default]
    Left,
    Center,
    Right,
}

impl AsciiTable {
    pub fn print<L1, L2, T>(&self, data: L1)
    where
        L1: IntoIterator<Item = L2>,
        L2: IntoIterator<Item = T>,
        T: Display,
    {
        print!("{}", self.format(data))
    }

    pub fn format<L1, L2, T>(&self, data: L1) -> String
    where
        L1: IntoIterator<Item = L2>,
        L2: IntoIterator<Item = T>,
        T: Display,
    {
        self.format_inner(self.stringify(data))
    }

    fn format_inner(&self, data: Vec<Vec<SmartString>>) -> String {
        let num_cols = data.iter().map(|row| row.len()).max().unwrap_or(0);
        let table_max_width = self.max_width();
        if !self.valid(&data, num_cols, table_max_width) {
            return self.format_empty();
        }

        let header = self.stringify_header(num_cols);
        let data = self.square_data(data, num_cols);
        let has_header = header.iter().any(|text| !text.is_empty());
        let widths = self.column_widths(&header, &data, table_max_width);

        let mut result = String::new();
        result.push_str(&self.format_first(&widths));
        if has_header {
            result.push_str(&self.format_header_row(&header, &widths));
            result.push_str(&self.format_middle(&widths));
        }
        for row in data {
            result.push_str(&self.format_row(&row, &widths));
        }
        result.push_str(&self.format_last(&widths));
        result
    }

    fn valid(&self, data: &Vec<Vec<SmartString>>, num_cols: usize, table_max_width: usize) -> bool {
        if data.len() == 0 {
            false
        } else if num_cols == 0 {
            false
        } else if table_max_width < Self::smallest_width(num_cols) {
            false
        } else {
            true
        }
    }

    fn smallest_width(num_cols: usize) -> usize {
        ((num_cols - 1) * 3) + 4
    }

    fn stringify<L1, L2, T>(&self, data: L1) -> Vec<Vec<SmartString>>
    where
        L1: IntoIterator<Item = L2>,
        L2: IntoIterator<Item = T>,
        T: Display,
    {
        data.into_iter()
            .map(|row| {
                row.into_iter()
                    .map(|cell| SmartString::from(cell.to_string()))
                    .collect()
            })
            .collect()
    }

    fn stringify_header(&self, num_cols: usize) -> Vec<SmartString> {
        (0..num_cols)
            .map(|n| {
                let value = self
                    .columns
                    .get(&n)
                    .map(|column| column.header.as_str())
                    .unwrap_or("");
                SmartString::from(value)
            })
            .collect()
    }

    fn square_data(
        &self,
        mut data: Vec<Vec<SmartString>>,
        num_cols: usize,
    ) -> Vec<Vec<SmartString>> {
        for row in &mut data {
            while row.len() < num_cols {
                row.push(SmartString::new());
            }
        }
        data
    }

    fn column_widths(
        &self,
        header: &[SmartString],
        data: &[Vec<SmartString>],
        table_max_width: usize,
    ) -> Vec<usize> {
        let default_conf = &Default::default();
        let result: Vec<_> = (0..header.len())
            .map(|n| {
                let conf = self.columns.get(&n).unwrap_or(default_conf);
                let column_width = data.iter().map(|row| row[n].width()).max().unwrap();
                let header_width = header[n].width();
                column_width.max(header_width).min(conf.max_width)
            })
            .collect();
        self.truncate_widths(result, table_max_width)
    }

    fn truncate_widths(&self, mut widths: Vec<usize>, table_max_width: usize) -> Vec<usize> {
        let table_padding = Self::smallest_width(widths.len());
        while widths.iter().sum::<usize>() + table_padding > table_max_width
            && *widths.iter().max().unwrap() > 0
        {
            let max = widths.iter().max().unwrap();
            let idx = widths.iter().rposition(|x| x == max).unwrap();
            widths[idx] -= 1;
        }
        widths
    }

    fn format_line(&self, row: &[SmartString], head: &str, delim: &str, tail: &str) -> String {
        let mut result = String::new();
        result.push_str(head);
        for cell in row {
            result.push_str(&format!("{}{}", cell, delim));
        }
        for _ in 0..delim.chars().count() {
            result.pop();
        }
        result.push_str(tail);
        result.push('\n');
        result
    }

    fn format_empty(&self) -> String {
        self.format_first(&vec![0])
            + &self.format_line(
                &[SmartString::new()],
                &format!("{}{}", NS, ' '),
                &format!("{}{}{}", ' ', NS, ' '),
                &format!("{}{}", ' ', NS),
            )
            + &self.format_last(&[0])
    }

    fn format_first(&self, widths: &[usize]) -> String {
        let row: Vec<_> = widths
            .iter()
            .map(|&x| SmartString::from_visible(EW.repeat(x)))
            .collect();
        self.format_line(
            &row,
            &format!("{}{}", SE, EW),
            &format!("{}{}{}", EW, EWS, EW),
            &format!("{}{}", EW, SW),
        )
    }

    fn format_middle(&self, widths: &[usize]) -> String {
        let row: Vec<_> = widths
            .iter()
            .map(|&x| SmartString::from_visible(EW.repeat(x)))
            .collect();
        self.format_line(
            &row,
            &format!("{}{}", NES, EW),
            &format!("{}{}{}", EW, NEWS, EW),
            &format!("{}{}", EW, NWS),
        )
    }

    fn format_row(&self, row: &[SmartString], widths: &[usize]) -> String {
        let default_conf = &Default::default();
        let row: Vec<_> = (0..widths.len())
            .map(|a| {
                let cell = &row[a];
                let width = widths[a];
                let conf = self.columns.get(&a).unwrap_or(default_conf);
                self.format_cell(cell, width, ' ', conf.align)
            })
            .collect();
        self.format_line(
            &row,
            &format!("{}{}", NS, ' '),
            &format!("{}{}{}", ' ', NS, ' '),
            &format!("{}{}", ' ', NS),
        )
    }

    fn format_header_row(&self, row: &[SmartString], widths: &[usize]) -> String {
        let row: Vec<_> = row
            .iter()
            .zip(widths.iter())
            .map(|(cell, &width)| self.format_cell(cell, width, ' ', Align::Left))
            .collect();
        self.format_line(
            &row,
            &format!("{}{}", NS, ' '),
            &format!("{}{}{}", ' ', NS, ' '),
            &format!("{}{}", ' ', NS),
        )
    }

    fn format_last(&self, widths: &[usize]) -> String {
        let row: Vec<_> = widths
            .iter()
            .map(|&x| SmartString::from_visible(EW.repeat(x)))
            .collect();
        self.format_line(
            &row,
            &format!("{}{}", NE, EW),
            &format!("{}{}{}", EW, NEW, EW),
            &format!("{}{}", EW, NW),
        )
    }

    fn format_cell(&self, text: &SmartString, len: usize, pad: char, align: Align) -> SmartString {
        if text.width() > len {
            let mut result = text.clone();
            while result.width() > len {
                result.pop();
            }
            if result.pop().is_some() {
                result.push_visible('+')
            }
            result
        } else {
            let mut result = text.clone();
            match align {
                Align::Left => {
                    while result.width() < len {
                        result.push_visible(pad)
                    }
                }
                Align::Right => {
                    while result.width() < len {
                        result.lpush_visible(pad)
                    }
                }
                Align::Center => {
                    while result.width() < len {
                        result.push_visible(pad);
                        if result.width() < len {
                            result.lpush_visible(pad)
                        }
                    }
                }
            }
            result
        }
    }
}

#[cfg(feature = "color_codes")]
lazy_static! {
    static ref COLOR_CODE_PARSER: Regex =
        Regex::new("\u{1b}\\[([0-9]+;)*[0-9]+m").expect("Regex compilation error");
}

#[derive(Clone, Debug)]
struct SmartString {
    fragments: Vec<SmartStringFragment>,
}

#[derive(Clone, Debug)]
struct SmartStringFragment {
    string: String,
    visible: bool,
}

impl SmartString {
    fn new() -> Self {
        Self {
            fragments: Vec::new(),
        }
    }

    #[cfg(feature = "color_codes")]
    fn from<T>(string: T) -> Self
    where
        T: AsRef<str>,
    {
        let string = string.as_ref();
        let mut fragments = Vec::new();
        let mut last = 0;
        for r#match in COLOR_CODE_PARSER.find_iter(string) {
            let start = r#match.start();
            let end = r#match.end();

            if last < start {
                fragments.push(SmartStringFragment::new(&string[last..start], true));
            }
            fragments.push(SmartStringFragment::new(&string[start..end], false));

            last = end;
        }

        if last < string.len() {
            fragments.push(SmartStringFragment::new(&string[last..], true));
        }

        Self { fragments }
    }

    #[cfg(not(feature = "color_codes"))]
    fn from<T>(string: T) -> Self
    where
        T: Into<String>,
    {
        Self {
            fragments: vec![SmartStringFragment::new(string, true)],
        }
    }

    fn from_visible<T>(string: T) -> Self
    where
        T: Into<String>,
    {
        Self {
            fragments: vec![SmartStringFragment::new(string, true)],
        }
    }

    fn width(&self) -> usize {
        self.fragments
            .iter()
            .filter(|fragment| fragment.visible)
            .map(|fragment| fragment.width())
            .sum()
    }

    fn is_empty(&self) -> bool {
        self.fragments
            .iter()
            .filter(|fragment| fragment.visible)
            .all(|fragment| fragment.string.is_empty())
    }

    fn pop(&mut self) -> Option<char> {
        self.fragments
            .iter_mut()
            .filter(|fragment| fragment.visible && !fragment.string.is_empty())
            .last()
            .and_then(|fragment| fragment.string.pop())
    }

    fn push_visible(&mut self, ch: char) {
        let last_fragment = self
            .fragments
            .iter_mut()
            .filter(|fragment| fragment.visible)
            .map(|fragment| &mut fragment.string)
            .last();
        if let Some(fragment) = last_fragment {
            fragment.push(ch);
        } else {
            self.fragments.push(SmartStringFragment::new(ch, true));
        }
    }

    fn lpush_visible(&mut self, ch: char) {
        let first_fragment = self
            .fragments
            .iter_mut()
            .filter(|fragment| fragment.visible)
            .map(|fragment| &mut fragment.string)
            .next();
        if let Some(fragment) = first_fragment {
            fragment.insert(0, ch);
        } else {
            self.fragments.insert(0, SmartStringFragment::new(ch, true));
        }
    }
}

impl Display for SmartString {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
        self.fragments
            .iter()
            .try_for_each(|fragment| fragment.string.fmt(fmt))
    }
}

impl SmartStringFragment {
    fn new<T>(string: T, visible: bool) -> Self
    where
        T: Into<String>,
    {
        Self {
            string: string.into(),
            visible,
        }
    }

    #[cfg(feature = "wide_characters")]
    fn width(&self) -> usize {
        UnicodeWidthStr::width(self.string.as_str())
    }

    #[cfg(not(feature = "wide_characters"))]
    fn width(&self) -> usize {
        self.string.chars().count()
    }
}