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 unicode_width::UnicodeWidthStr;
25use ndarray::Array2;
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`. The first row is treated as the header.
134    ///
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    /// Set the border style. Default is [`Style::Simple`].
148    pub fn style(mut self, style: Style) -> Self {
149        self.style = style;
150        self
151    }
152
153    /// Set per-column alignment. Missing columns default to [`Align::Left`].
154    pub fn aligns(mut self, aligns: Vec<Align>) -> Self {
155        self.aligns = aligns;
156        self
157    }
158
159    /// Truncate data cells to at most `width` display columns, appending
160    /// ASCII `...` on overflow. The header is never truncated.
161    pub fn max_cell_width(mut self, width: usize) -> Self {
162        self.max_cell_width = Some(width);
163        self
164    }
165
166    /// Set the header foreground color. Default is no color.
167    pub fn header_color(mut self, color: Color) -> Self {
168        self.header_color = Some(color);
169        self
170    }
171
172    /// Set the data-row foreground color. Default is no color.
173    pub fn body_color(mut self, color: Color) -> Self {
174        self.body_color = Some(color);
175        self
176    }
177
178    fn align_of(&self, col: usize) -> Align {
179        self.aligns.get(col).copied().unwrap_or(Align::Left)
180    }
181
182    /// Number of columns: the maximum row length.
183    fn column_count(&self) -> usize {
184        self.rows.iter().map(|r| r.len()).max().unwrap_or(0)
185    }
186
187    /// Prepare a cell for rendering.
188    ///
189    /// Steps: strip ANSI escape sequences, then truncate to
190    /// `max_cell_width`. Returns `(final_text, display_width)`.
191    ///
192    /// Both width computation and rendering call this, so they always see
193    /// the same content.
194    fn prepare_cell(&self, content: &str) -> (String, usize) {
195        let stripped = strip_ansi(content);
196        let truncated = match self.max_cell_width {
197            Some(max) => truncate_visible(&stripped, max),
198            None => stripped,
199        };
200        let w = display_width(&truncated);
201        (truncated, w)
202    }
203
204    /// Compute the display width of each column.
205    ///
206    /// Each column is `max(display_width of all cells in that column,
207    /// including the header) + 2`, where `+2` reserves one space of padding
208    /// on each side. Data cells are prepared first via [`Self::prepare_cell`].
209    fn column_widths(&self) -> Vec<usize> {
210        let cols = self.column_count();
211        let mut widths = vec![0usize; cols];
212        for (r, row) in self.rows.iter().enumerate() {
213            for (i, cell) in row.iter().enumerate() {
214                let w = if r == 0 {
215                    // Header: never truncated, but ANSI is still stripped
216                    // before measuring.
217                    display_width(cell)
218                } else {
219                    // Data rows go through the same preparation path.
220                    let (_, w) = self.prepare_cell(cell);
221                    w
222                };
223                if w > widths[i] {
224                    widths[i] = w;
225                }
226            }
227        }
228        // Reserve one space of padding on each side.
229        widths.into_iter().map(|w| w + 2).collect()
230    }
231
232    /// Render one data cell: one space of padding on each side, then
233    /// alignment, then `body_color`.
234    fn render_cell(&self, content: &str, width: usize, align: Align) -> String {
235        let (text, vis) = self.prepare_cell(content);
236
237        // `width` already includes one space of padding on each side.
238        let inner = width.saturating_sub(2);
239        let pad = inner.saturating_sub(vis);
240
241        let aligned = match align {
242            Align::Left => format!("{}{}", text, " ".repeat(pad)),
243            Align::Right => format!("{}{}", " ".repeat(pad), text),
244            Align::Auto => {
245                // Decide numeric-ness from the original content (ANSI stripped).
246                if is_numeric_like(&strip_ansi(content)) {
247                    format!("{}{}", " ".repeat(pad), text)
248                } else {
249                    format!("{}{}", text, " ".repeat(pad))
250                }
251            }
252        };
253
254        let padded = format!(" {} ", aligned);
255        colorize(&padded, self.body_color)
256    }
257
258    /// Render one header cell: left aligned, never truncated, one space of
259    /// padding on each side, then `header_color`.
260    fn render_header_cell(&self, content: &str, width: usize) -> String {
261        let stripped = strip_ansi(content);
262        let vis = display_width(&stripped);
263        let inner = width.saturating_sub(2);
264        let pad = inner.saturating_sub(vis);
265        let padded = format!(" {}{} ", stripped, " ".repeat(pad));
266        colorize(&padded, self.header_color)
267    }
268
269    /// Render one row (without the leading and trailing `│`).
270    fn render_row(&self, row: &[String], widths: &[usize], is_header: bool) -> String {
271        let mut cells = Vec::with_capacity(widths.len());
272        for (i, w) in widths.iter().enumerate() {
273            let content = row.get(i).map(String::as_str).unwrap_or("");
274            if is_header {
275                cells.push(self.render_header_cell(content, *w));
276            } else {
277                let align = self.align_of(i);
278                cells.push(self.render_cell(content, *w, align));
279            }
280        }
281        cells.join("│")
282    }
283
284    /// Build a horizontal line, e.g. `├───┼───┤`.
285    fn horizontal(widths: &[usize], left: &str, mid: &str, right: &str, fill: &str) -> String {
286        let segments: Vec<String> = widths.iter().map(|w| fill.repeat(*w)).collect();
287        format!("{}{}{}", left, segments.join(mid), right)
288    }
289
290    /// Render the table to a `String`. Every line ends with `\n`.
291    pub fn render(&self) -> String {
292        if self.rows.is_empty() {
293            return String::new();
294        }
295        let widths = self.column_widths();
296        let mut out = String::new();
297
298        match self.style {
299            Style::Simple => {
300                out.push('│');
301                out.push_str(&self.render_row(&self.rows[0], &widths, true));
302                out.push_str("│\n");
303                out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
304                out.push('\n');
305                for row in &self.rows[1..] {
306                    out.push('│');
307                    out.push_str(&self.render_row(row, &widths, false));
308                    out.push_str("│\n");
309                }
310            }
311            Style::Boxed => {
312                out.push_str(&Self::horizontal(&widths, "┌", "┬", "┐", "─"));
313                out.push('\n');
314                out.push('│');
315                out.push_str(&self.render_row(&self.rows[0], &widths, true));
316                out.push_str("│\n");
317                out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
318                out.push('\n');
319                for (i, row) in self.rows[1..].iter().enumerate() {
320                    out.push('│');
321                    out.push_str(&self.render_row(row, &widths, false));
322                    out.push_str("│\n");
323                    if i + 1 < self.rows.len() - 1 {
324                        out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
325                        out.push('\n');
326                    }
327                }
328                out.push_str(&Self::horizontal(&widths, "└", "┴", "┘", "─"));
329                out.push('\n');
330            }
331        }
332        out
333    }
334}
335
336impl Table {
337    /// Convert an `ndarray::Array2<String>` into the row-major
338    /// `Vec<Vec<String>>` representation used by [`Table::new`].
339    ///
340    /// Each row of the array becomes one `Vec<String>`, preserving the
341    /// array's row/column order.
342    pub fn from_array2(array: Array2<String>) -> Vec<Vec<String>> {
343        array
344            .outer_iter()
345            .map(|row| row.iter().cloned().collect())
346            .collect()
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/// Terminal display width of `s`, ignoring ANSI escape sequences.
372pub fn display_width(s: &str) -> usize {
373    let stripped = strip_ansi(s);
374    UnicodeWidthStr::width(stripped.as_str())
375}
376
377/// Pad `s` on the right with spaces up to `width` display columns.
378pub fn pad_right_with_spaces(s: &str, width: usize) -> String {
379    let w = display_width(s);
380    if w >= width {
381        return s.to_string();
382    }
383    let mut out = String::with_capacity(s.len() + (width - w));
384    out.push_str(s);
385    out.push_str(&" ".repeat(width - w));
386    out
387}
388
389/// Pad `s` on the left with spaces up to `width` display columns.
390pub fn pad_left_with_spaces(s: &str, width: usize) -> String {
391    let w = display_width(s);
392    if w >= width {
393        return s.to_string();
394    }
395    let mut out = String::with_capacity(s.len() + (width - w));
396    out.push_str(&" ".repeat(width - w));
397    out.push_str(s);
398    out
399}
400
401// ============================================================
402// ANSI
403// ============================================================
404
405/// Strip CSI-style ANSI escape sequences (e.g. `\x1b[...m`) from `s`.
406pub fn strip_ansi(s: &str) -> String {
407    let mut out = String::with_capacity(s.len());
408    let mut chars = s.chars().peekable();
409    while let Some(c) = chars.next() {
410        if c == '\x1b' {
411            if chars.peek() == Some(&'[') {
412                chars.next(); // consume '['
413                for c2 in chars.by_ref() {
414                    if c2.is_ascii_alphabetic() {
415                        break;
416                    }
417                }
418            }
419        } else {
420            out.push(c);
421        }
422    }
423    out
424}
425
426// ============================================================
427// Truncation
428// ============================================================
429
430/// Truncate `s` to at most `max_width` display columns, appending ASCII
431/// `...` (3 columns) on overflow.
432///
433/// ASCII `...` is used instead of `…` (U+2026) because the single-character
434/// ellipsis renders as 1 or 2 columns depending on terminal and font, which
435/// breaks alignment. ASCII `...` is always exactly 3 columns.
436///
437/// ANSI escape sequences are preserved (they do not consume width), but
438/// color closure after truncation is not guaranteed. Prefer stripping ANSI
439/// before calling this function.
440pub fn truncate_visible(s: &str, max_width: usize) -> String {
441    if max_width == 0 {
442        return String::new();
443    }
444    let vis = display_width(s);
445    if vis <= max_width {
446        return s.to_string();
447    }
448    let suffix = "...";
449    let suffix_w = 3usize;
450    if max_width <= suffix_w {
451        // Not enough room for any content; show the suffix only.
452        return suffix.to_string();
453    }
454    let target = max_width - suffix_w;
455    let mut out = String::new();
456    let mut used = 0usize;
457    let mut chars = s.chars().peekable();
458    while let Some(c) = chars.next() {
459        if c == '\x1b' {
460            out.push(c);
461            if chars.peek() == Some(&'[') {
462                out.push(chars.next().unwrap());
463                for c2 in chars.by_ref() {
464                    out.push(c2);
465                    if c2.is_ascii_alphabetic() {
466                        break;
467                    }
468                }
469            }
470            continue;
471        }
472        let cw = UnicodeWidthStr::width(c.to_string().as_str());
473        if used + cw > target {
474            break;
475        }
476        out.push(c);
477        used += cw;
478    }
479    out.push_str(suffix);
480    out
481}
482
483// ============================================================
484// Numeric heuristic
485// ============================================================
486
487/// Return `true` if `s` looks like a number, for [`Align::Auto`].
488///
489/// Rule: take the first whitespace-separated token and try to parse it as
490/// `f64`. For example, `"57 ms"` -> `"57"` -> `true`; `"失败"` -> `false`;
491/// `"-3.14"` -> `true`.
492pub fn is_numeric_like(s: &str) -> bool {
493    let s = s.trim();
494    if s.is_empty() {
495        return false;
496    }
497    let head = s.split_whitespace().next().unwrap_or("");
498    head.parse::<f64>().is_ok()
499}