Skip to main content

console_table/
lib.rs

1//! Console table rendering with Unicode/CJK-aware alignment, truncation,
2//! and ANSI color support.
3//!
4//! # Example
5//!
6//! ```
7//! use console_table::{Align, Style, Table};
8//!
9//! let rows = vec![
10//!     vec!["#".to_string(), "source".to_string(), "latency".to_string()],
11//!     vec!["1".to_string(), "rsproxy".to_string(), "57 ms".to_string()],
12//!     vec!["2".to_string(), "tuna".to_string(), "16 ms".to_string()],
13//! ];
14//!
15//! let table = Table::new(rows)
16//!     .style(Style::Boxed)
17//!     .aligns(vec![Align::Right, Align::Left, Align::Auto]);
18//!
19//! println!("{}", table.render());
20//! ```
21
22#![warn(missing_docs)]
23
24use ndarray::Array2;
25use unicode_width::UnicodeWidthChar;
26
27// ============================================================
28// Public types
29// ============================================================
30
31/// Border style of the table.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Style {
34    /// Header row, a single separator, then data rows.
35    Simple,
36    /// Full box drawing: top, header separator, row separators, bottom.
37    Boxed,
38}
39
40/// Horizontal alignment of a cell.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Align {
43    /// Left align.
44    Left,
45    /// Right align.
46    Right,
47    /// Right align if the first whitespace-separated token parses as `f64`,
48    /// otherwise left align.
49    Auto,
50}
51
52/// ANSI foreground color.
53///
54/// The first eight are the standard colors, the `Bright*` variants are
55/// the corresponding high-intensity colors. Mapping to ANSI codes:
56/// `Black`=30 ... `White`=37, `BrightBlack`=90 ... `BrightWhite`=97.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Color {
59    /// ANSI color 30.
60    Black,
61    /// ANSI color 31.
62    Red,
63    /// ANSI color 32.
64    Green,
65    /// ANSI color 33.
66    Yellow,
67    /// ANSI color 34.
68    Blue,
69    /// ANSI color 35.
70    Magenta,
71    /// ANSI color 36.
72    Cyan,
73    /// ANSI color 37.
74    White,
75    /// ANSI color 90 (high-intensity black / gray).
76    BrightBlack,
77    /// ANSI color 91.
78    BrightRed,
79    /// ANSI color 92.
80    BrightGreen,
81    /// ANSI color 93.
82    BrightYellow,
83    /// ANSI color 94.
84    BrightBlue,
85    /// ANSI color 95.
86    BrightMagenta,
87    /// ANSI color 96.
88    BrightCyan,
89    /// ANSI color 97.
90    BrightWhite,
91}
92
93impl Color {
94    /// The ANSI foreground color code.
95    fn fg_code(self) -> u8 {
96        match self {
97            Color::Black => 30,
98            Color::Red => 31,
99            Color::Green => 32,
100            Color::Yellow => 33,
101            Color::Blue => 34,
102            Color::Magenta => 35,
103            Color::Cyan => 36,
104            Color::White => 37,
105            Color::BrightBlack => 90,
106            Color::BrightRed => 91,
107            Color::BrightGreen => 92,
108            Color::BrightYellow => 93,
109            Color::BrightBlue => 94,
110            Color::BrightMagenta => 95,
111            Color::BrightCyan => 96,
112            Color::BrightWhite => 97,
113        }
114    }
115}
116
117/// Table configuration.
118#[derive(Debug, Clone)]
119pub struct Table {
120    rows: Vec<Vec<String>>,
121    style: Style,
122    aligns: Vec<Align>,
123    /// Maximum display width of a data cell (padding excluded).
124    /// `None` means no truncation.
125    max_cell_width: Option<usize>,
126    /// Foreground color for the header row.
127    header_color: Option<Color>,
128    /// Foreground color for data rows.
129    body_color: Option<Color>,
130}
131
132impl Table {
133    /// Create a table from `rows`.
134    /// The first row is treated as the header.
135    /// Rows may have different lengths; missing cells are treated as empty.
136    pub fn new(rows: Vec<Vec<String>>) -> Self {
137        Self {
138            rows,
139            style: Style::Simple,
140            aligns: Vec::new(),
141            max_cell_width: None,
142            header_color: None,
143            body_color: None,
144        }
145    }
146
147    /// Create a table from an `ndarray::Array2<String>`.
148    /// The first row is treated as the header.
149    /// Rows may have different lengths; missing cells are treated as empty.
150    pub fn from_array2(array: Array2<String>) -> Self {
151        let rows = array
152            .outer_iter()
153            .map(|row| row.iter().cloned().collect())
154            .collect();
155        Self::new(rows)
156    }
157
158    /// Set the border style. Default is [`Style::Simple`].
159    pub fn style(mut self, style: Style) -> Self {
160        self.style = style;
161        self
162    }
163
164    /// Set per-column alignment. Missing columns default to [`Align::Left`].
165    pub fn aligns(mut self, aligns: Vec<Align>) -> Self {
166        self.aligns = aligns;
167        self
168    }
169
170    /// Truncate data cells to at most `width` display columns, appending
171    /// ASCII `...` on overflow. The header is never truncated.
172    pub fn max_cell_width(mut self, width: usize) -> Self {
173        self.max_cell_width = Some(width);
174        self
175    }
176
177    /// Set the header foreground color. Default is no color.
178    pub fn header_color(mut self, color: Color) -> Self {
179        self.header_color = Some(color);
180        self
181    }
182
183    /// Set the data-row foreground color. Default is no color.
184    pub fn body_color(mut self, color: Color) -> Self {
185        self.body_color = Some(color);
186        self
187    }
188
189    /// Render the table to a `String`. Every line ends with `\n`.
190    pub fn render(&self) -> String {
191        if self.rows.is_empty() {
192            return String::new();
193        }
194        let widths = self.column_widths();
195        let mut out = String::new();
196
197        match self.style {
198            Style::Simple => {
199                out.push('│');
200                out.push_str(&self.render_row(&self.rows[0], &widths, true));
201                out.push_str("│\n");
202                out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
203                out.push('\n');
204                for row in &self.rows[1..] {
205                    out.push('│');
206                    out.push_str(&self.render_row(row, &widths, false));
207                    out.push_str("│\n");
208                }
209            }
210            Style::Boxed => {
211                out.push_str(&Self::horizontal(&widths, "┌", "┬", "┐", "─"));
212                out.push('\n');
213                out.push('│');
214                out.push_str(&self.render_row(&self.rows[0], &widths, true));
215                out.push_str("│\n");
216                out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
217                out.push('\n');
218                for (i, row) in self.rows[1..].iter().enumerate() {
219                    out.push('│');
220                    out.push_str(&self.render_row(row, &widths, false));
221                    out.push_str("│\n");
222                    if i + 1 < self.rows.len() - 1 {
223                        out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
224                        out.push('\n');
225                    }
226                }
227                out.push_str(&Self::horizontal(&widths, "└", "┴", "┘", "─"));
228                out.push('\n');
229            }
230        }
231        out
232    }
233}
234
235impl Table {
236    fn align_of(&self, col: usize) -> Align {
237        self.aligns.get(col).copied().unwrap_or(Align::Left)
238    }
239
240    /// Number of columns: the maximum row length.
241    fn column_count(&self) -> usize {
242        self.rows.iter().map(|r| r.len()).max().unwrap_or(0)
243    }
244
245    /// Prepare a cell for rendering.
246    ///
247    /// Steps: strip ANSI escape sequences, trim surrounding whitespace,
248    /// then truncate to `max_cell_width`. Returns `(final_text, display_width)`.
249    ///
250    /// Both width computation and rendering call this, so they always see
251    /// the same content.
252    fn prepare_cell(&self, content: &str) -> (String, usize) {
253        let stripped = strip_ansi(content);
254        let trimmed = stripped.trim();
255        let truncated = match self.max_cell_width {
256            Some(max) => truncate_visible(trimmed, max),
257            None => trimmed.to_string(),
258        };
259        let w = display_width(&truncated);
260        (truncated, w)
261    }
262
263    /// Compute the display width of each column.
264    ///
265    /// Each column is `max(display_width of all cells in that column,
266    /// including the header) + 2`, where `+2` reserves one space of padding
267    /// on each side. Data cells are prepared first via [`Self::prepare_cell`].
268    fn column_widths(&self) -> Vec<usize> {
269        let cols = self.column_count();
270        let mut widths = vec![0usize; cols];
271        for (r, row) in self.rows.iter().enumerate() {
272            for (i, cell) in row.iter().enumerate() {
273                let w = if r == 0 {
274                    // Header: never truncated, but ANSI is still stripped
275                    // before measuring.
276                    display_width(cell)
277                } else {
278                    // Data rows go through the same preparation path.
279                    let (_, w) = self.prepare_cell(cell);
280                    w
281                };
282                if w > widths[i] {
283                    widths[i] = w;
284                }
285            }
286        }
287        // Reserve one space of padding on each side.
288        widths.into_iter().map(|w| w + 2).collect()
289    }
290
291    /// Render one data cell: one space of padding on each side, then
292    /// alignment, then `body_color`.
293    fn render_cell(&self, content: &str, width: usize, align: Align) -> String {
294        let (text, vis) = self.prepare_cell(content);
295
296        // `width` already includes one space of padding on each side.
297        let inner = width.saturating_sub(2);
298        let pad = inner.saturating_sub(vis);
299
300        let aligned = match align {
301            Align::Left => format!("{}{}", text, " ".repeat(pad)),
302            Align::Right => format!("{}{}", " ".repeat(pad), text),
303            Align::Auto => {
304                // Decide numeric-ness from the original content (ANSI stripped).
305                if is_numeric_like(&strip_ansi(content)) {
306                    format!("{}{}", " ".repeat(pad), text)
307                } else {
308                    format!("{}{}", text, " ".repeat(pad))
309                }
310            }
311        };
312
313        let padded = format!(" {} ", aligned);
314        colorize(&padded, self.body_color)
315    }
316
317    /// Render one header cell: left aligned, never truncated, one space of
318    /// padding on each side, then `header_color`.
319    fn render_header_cell(&self, content: &str, width: usize) -> String {
320        let stripped = strip_ansi(content);
321        let vis = display_width(&stripped);
322        let inner = width.saturating_sub(2);
323        let pad = inner.saturating_sub(vis);
324        let padded = format!(" {}{} ", stripped, " ".repeat(pad));
325        colorize(&padded, self.header_color)
326    }
327
328    /// Render one row (without the leading and trailing `│`).
329    fn render_row(&self, row: &[String], widths: &[usize], is_header: bool) -> String {
330        let mut cells = Vec::with_capacity(widths.len());
331        for (i, w) in widths.iter().enumerate() {
332            let content = row.get(i).map(String::as_str).unwrap_or("");
333            if is_header {
334                cells.push(self.render_header_cell(content, *w));
335            } else {
336                let align = self.align_of(i);
337                cells.push(self.render_cell(content, *w, align));
338            }
339        }
340        cells.join("│")
341    }
342
343    /// Build a horizontal line, e.g. `├───┼───┤`.
344    fn horizontal(widths: &[usize], left: &str, mid: &str, right: &str, fill: &str) -> String {
345        let segments: Vec<String> = widths.iter().map(|w| fill.repeat(*w)).collect();
346        format!("{}{}{}", left, segments.join(mid), right)
347    }
348}
349
350/// Convenience function: render a table directly.
351pub fn render_table(rows: Vec<Vec<String>>, style: Style) -> String {
352    Table::new(rows).style(style).render()
353}
354
355// ============================================================
356// Color
357// ============================================================
358
359/// Wrap `s` in an ANSI foreground color. `None` returns `s` unchanged.
360fn colorize(s: &str, color: Option<Color>) -> String {
361    match color {
362        Some(c) => format!("\x1b[{}m{}\x1b[0m", c.fg_code(), s),
363        None => s.to_string(),
364    }
365}
366
367// ============================================================
368// Width
369// ============================================================
370
371/// Characters that the current terminal renders as 2 columns, but
372/// `unicode_width` counts as 1 (even with `width_cjk`).
373///
374/// `Φ` (U+03A6) is the motivating example: `unicode_width` gives it width 1,
375/// but CJK terminals render it 2 columns wide, causing misalignment.
376/// Extend this list as new such characters appear in real data.
377fn extra_wide(c: char) -> bool {
378    matches!(
379        c,
380        'Φ' | 'φ'                 // 希腊字母 Phi
381        | 'Ⅱ' | 'Ⅲ' | 'Ⅰ'       // 罗马数字
382        | '±' | '×' | '÷'        // 数学符号
383        | '≤' | '≥' | '≠'
384        | '→' | '←' | '↑' | '↓'
385        | '①'..='⑳'             // 带圈数字
386    )
387}
388
389/// Display width of a single `char`, with [`extra_wide`] compensation.
390fn char_width(c: char) -> usize {
391    if extra_wide(c) {
392        2
393    } else {
394        UnicodeWidthChar::width(c).unwrap_or(0)
395    }
396}
397
398/// Terminal display width of `s`, ignoring ANSI escape sequences.
399///
400/// Uses [`char_width`] per character so that characters which
401/// `unicode_width` under-reports are counted correctly.
402pub fn display_width(s: &str) -> usize {
403    let stripped = strip_ansi(s);
404    stripped.chars().map(char_width).sum()
405}
406
407/// Pad `s` on the right with spaces up to `width` display columns.
408pub fn pad_right_with_spaces(s: &str, width: usize) -> String {
409    let w = display_width(s);
410    if w >= width {
411        return s.to_string();
412    }
413    let mut out = String::with_capacity(s.len() + (width - w));
414    out.push_str(s);
415    out.push_str(&" ".repeat(width - w));
416    out
417}
418
419/// Pad `s` on the left with spaces up to `width` display columns.
420pub fn pad_left_with_spaces(s: &str, width: usize) -> String {
421    let w = display_width(s);
422    if w >= width {
423        return s.to_string();
424    }
425    let mut out = String::with_capacity(s.len() + (width - w));
426    out.push_str(&" ".repeat(width - w));
427    out.push_str(s);
428    out
429}
430
431// ============================================================
432// ANSI
433// ============================================================
434
435/// Strip CSI-style ANSI escape sequences (e.g. `\x1b[...m`) from `s`.
436pub fn strip_ansi(s: &str) -> String {
437    let mut out = String::with_capacity(s.len());
438    let mut chars = s.chars().peekable();
439    while let Some(c) = chars.next() {
440        if c == '\x1b' {
441            if chars.peek() == Some(&'[') {
442                chars.next(); // consume '['
443                for c2 in chars.by_ref() {
444                    if c2.is_ascii_alphabetic() {
445                        break;
446                    }
447                }
448            }
449        } else {
450            out.push(c);
451        }
452    }
453    out
454}
455
456// ============================================================
457// Truncation
458// ============================================================
459
460/// Truncate `s` to at most `max_width` display columns, appending ASCII
461/// `...` (3 columns) on overflow.
462///
463/// ASCII `...` is used instead of `…` (U+2026) because the single-character
464/// ellipsis renders as 1 or 2 columns depending on terminal and font, which
465/// breaks alignment. ASCII `...` is always exactly 3 columns.
466///
467/// ANSI escape sequences are preserved (they do not consume width), but
468/// color closure after truncation is not guaranteed. Prefer stripping ANSI
469/// before calling this function.
470pub fn truncate_visible(s: &str, max_width: usize) -> String {
471    if max_width == 0 {
472        return String::new();
473    }
474    let vis = display_width(s);
475    if vis <= max_width {
476        return s.to_string();
477    }
478    let suffix = "...";
479    let suffix_w = 3usize;
480    if max_width <= suffix_w {
481        // Not enough room for any content; show the suffix only.
482        return suffix.to_string();
483    }
484    let target = max_width - suffix_w;
485    let mut out = String::new();
486    let mut used = 0usize;
487    let mut chars = s.chars().peekable();
488    while let Some(c) = chars.next() {
489        if c == '\x1b' {
490            out.push(c);
491            if chars.peek() == Some(&'[') {
492                out.push(chars.next().unwrap());
493                for c2 in chars.by_ref() {
494                    out.push(c2);
495                    if c2.is_ascii_alphabetic() {
496                        break;
497                    }
498                }
499            }
500            continue;
501        }
502        // Use `char_width` so compensation matches `display_width`.
503        let cw = char_width(c);
504        if used + cw > target {
505            break;
506        }
507        out.push(c);
508        used += cw;
509    }
510    out.push_str(suffix);
511    out
512}
513
514// ============================================================
515// Numeric heuristic
516// ============================================================
517
518/// Return `true` if `s` looks like a number, for [`Align::Auto`].
519///
520/// Rule: take the first whitespace-separated token and try to parse it as
521/// `f64`. For example, `"57 ms"` -> `"57"` -> `true`; `"失败"` -> `false`;
522/// `"-3.14"` -> `true`.
523pub fn is_numeric_like(s: &str) -> bool {
524    let s = s.trim();
525    if s.is_empty() {
526        return false;
527    }
528    let head = s.split_whitespace().next().unwrap_or("");
529    head.parse::<f64>().is_ok()
530}
531
532// ============================================================
533// Tests
534// ============================================================
535
536#[cfg(test)]
537mod tests {
538    use super::*;
539    use unicode_width::UnicodeWidthStr;
540
541    #[test]
542    fn phi_is_ambiguous_width() {
543        // `unicode_width` 把 `Φ` 算 1(即使 `width_cjk` 也是 1)。
544        // 这是 crate 的行为;`display_width` 通过 `extra_wide` 补偿为 2。
545        let s = "Φ170";
546        assert_eq!(UnicodeWidthStr::width(s), 4, "crate 默认宽度:Φ(1)+170(3)=4");
547        assert_eq!(
548            UnicodeWidthStr::width_cjk(s),
549            4,
550            "crate cjk 宽度同样是 4"
551        );
552        assert_eq!(
553            display_width(s),
554            5,
555            "display_width 补偿后:Φ(2)+170(3)=5"
556        );
557    }
558
559    #[test]
560    fn display_width_uses_cjk_for_phi() {
561        assert_eq!(display_width("Φ"), 2);
562        assert_eq!(display_width("Φ170"), 5);
563        assert_eq!(display_width("Φ8"), 3);
564        // "Φ16  III":Φ(2) + 1(1) + 6(1) + 空格(1) + 空格(1) + I(1)*3 = 9
565        assert_eq!(display_width("Φ16  III"), 9);
566    }
567
568    #[test]
569    fn display_width_ascii_unchanged() {
570        // ASCII 不受补偿影响。
571        assert_eq!(display_width("abc"), 3);
572        assert_eq!(display_width("170CD1"), 6);
573        assert_eq!(display_width("NUT-1"), 5);
574    }
575
576    #[test]
577    fn display_width_cjk_unchanged() {
578        // 汉字本来就是 2,两种模式一致。
579        assert_eq!(display_width("电杆"), 4);
580        assert_eq!(display_width("名称"), 4);
581        assert_eq!(display_width("电阻值设计定"), 12);
582    }
583
584    #[test]
585    fn display_width_strips_ansi() {
586        // ANSI 转义序列不计入宽度。
587        let colored = "\x1b[93m电杆\x1b[0m";
588        assert_eq!(display_width(colored), 4);
589    }
590
591    #[test]
592    fn phi_rows_align() {
593        // 构造含 Φ 和不含 Φ 的行,验证每行竖线数量一致。
594        let rows = vec![
595            vec!["名称".into(), "规格".into(), "材料".into()],
596            vec!["电杆".into(), "Φ170".into(), "".into()],
597            vec!["横担".into(), "03D103-133".into(), "2II2".into()],
598            vec!["接地线".into(), "Φ8".into(), "".into()],
599            vec!["拉线棒".into(), "03D103-187".into(), "Φ16  III".into()],
600        ];
601        let out = Table::new(rows).style(Style::Boxed).render();
602
603        // 3 列 → 行首 1 + 列间 2 + 行尾 1 = 4 个 `│`。
604        for line in out.lines() {
605            if line.starts_with('│') {
606                let n = line.matches('│').count();
607                assert_eq!(n, 4, "行竖线数量异常: {:?}", line);
608            }
609        }
610    }
611
612    #[test]
613    fn phi_align_matches_ascii_row() {
614        // 含 Φ 的行和不含 Φ 的行,渲染后每列宽度应一致。
615        let rows = vec![
616            vec!["规格".into()],
617            vec!["Φ170".into()],
618            vec!["170C".into()], // 4 个 ASCII 字符,宽度 4
619        ];
620        let out = Table::new(rows).style(Style::Boxed).render();
621
622        let data_lines: Vec<&str> = out
623            .lines()
624            .filter(|l| l.starts_with('│') && !l.contains("规格"))
625            .collect();
626
627        let widths: Vec<usize> = data_lines
628            .iter()
629            .map(|l| {
630                let inner = l.trim_matches('│');
631                display_width(inner)
632            })
633            .collect();
634
635        assert!(
636            widths.windows(2).all(|w| w[0] == w[1]),
637            "含 Φ 的行与 ASCII 行宽度不一致: {:?}",
638            widths
639        );
640    }
641
642    #[test]
643    fn truncate_phi_consistent() {
644        // 允许 6 列,末尾 "..." 占 3 列,前缀最多 3 列。
645        // Φ(2) + "1"(1) = 3 → "Φ1...",总宽 6。
646        let s = "Φ170CD1XYZ";
647        let t = truncate_visible(s, 6);
648        assert_eq!(t, "Φ1...");
649        assert_eq!(display_width(&t), 6);
650    }
651
652    #[test]
653    fn truncate_ascii_unchanged() {
654        let s = "abcdefghij";
655        let t = truncate_visible(s, 7);
656        assert_eq!(t, "abcd...");
657        assert_eq!(display_width(&t), 7);
658    }
659
660    #[test]
661    fn truncate_no_overflow_returns_original() {
662        let s = "Φ8";
663        let t = truncate_visible(s, 10);
664        assert_eq!(t, "Φ8");
665    }
666}