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//! # Ambiguous-width characters
5//!
6//! Characters like `Φ` (U+03A6) have Unicode `East_Asian_Width=Ambiguous`.
7//! Terminals render them as 1 or 2 columns depending on locale and terminal
8//! settings. `unicode_width` reports them as 1. To align with the terminal,
9//! this crate counts them as 2 when it believes the output target is a CJK
10//! context, and 1 otherwise.
11//!
12//! **Default behavior**: ambiguous characters are counted as **2 columns**
13//! (`AmbiguousWidth::Wide`). This matches CJK terminals, which are the
14//! primary target of this crate. If your terminal renders `Φ` as 1 column,
15//! call [`Table::cjk_context(false)`] or [`Table::ambiguous_width`] to
16//! override.
17//!
18//! # Example
19//!
20//! ```
21//! use console_table::{Align, Style, Table};
22//!
23//! let rows = vec![
24//!     vec!["#".to_string(), "source".to_string(), "latency".to_string()],
25//!     vec!["1".to_string(), "rsproxy".to_string(), "57 ms".to_string()],
26//!     vec!["2".to_string(), "tuna".to_string(), "16 ms".to_string()],
27//! ];
28//!
29//! let table = Table::new(rows)
30//!     .style(Style::Boxed)
31//!     .aligns(vec![Align::Right, Align::Left, Align::Auto]);
32//!
33//! println!("{}", table.render());
34//! ```
35
36#![warn(missing_docs)]
37
38use ndarray::Array2;
39use unicode_width::UnicodeWidthChar;
40
41// ============================================================
42// Ambiguous-width context
43// ============================================================
44
45/// How to treat Unicode `East_Asian_Width=Ambiguous` characters.
46///
47/// Examples: `Φ`, `±`, `×`, `Ⅱ`, `①`. These are 1 column in most Western
48/// terminals and 2 columns in most CJK terminals.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum AmbiguousWidth {
51    /// Count ambiguous characters as 1 column (Western terminal default).
52    Narrow,
53    /// Count ambiguous characters as 2 columns (CJK terminal default).
54    Wide,
55    /// Decide from environment variables at render time.
56    Auto,
57}
58
59impl AmbiguousWidth {
60    /// Resolve to a concrete width using the environment.
61    fn resolve(self) -> usize {
62        match self {
63            AmbiguousWidth::Narrow => 1,
64            AmbiguousWidth::Wide => 2,
65            AmbiguousWidth::Auto => {
66                if is_cjk_locale() {
67                    2
68                } else {
69                    1
70                }
71            }
72        }
73    }
74}
75
76impl Default for AmbiguousWidth {
77    /// Default is [`AmbiguousWidth::Wide`], matching CJK terminals.
78    ///
79    /// Rationale: the crate targets CJK output by default. `Auto` guesses
80    /// from `LANG`/`LC_*`, but environment locale does not necessarily match
81    /// how the terminal renders ambiguous characters. A fixed default is
82    /// more predictable; callers can override per [`Table`].
83    fn default() -> Self {
84        AmbiguousWidth::Wide
85    }
86}
87
88/// Heuristic: is the current process likely targeting a CJK terminal?
89///
90/// Checks `LC_ALL`, `LC_CTYPE`, `LANG` for a CJK locale prefix
91/// (`zh`, `ja`, `ko`). If nothing matches, returns `false` (narrow).
92fn is_cjk_locale() -> bool {
93    for key in ["LC_ALL", "LC_CTYPE", "LANG"] {
94        if let Ok(v) = std::env::var(key) {
95            let v = v.to_ascii_lowercase();
96            if v.starts_with("zh")
97                || v.starts_with("ja")
98                || v.starts_with("ko")
99                || v.contains("utf-8.zh")
100                || v.contains("utf-8.ja")
101                || v.contains("utf-8.ko")
102            {
103                return true;
104            }
105        }
106    }
107    false
108}
109
110// ============================================================
111// Public types
112// ============================================================
113
114/// Border style of the table.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub enum Style {
117    /// Header row, a single separator, then data rows.
118    Simple,
119    /// Full box drawing: top, header separator, row separators, bottom.
120    Boxed,
121}
122
123/// Horizontal alignment of a cell.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum Align {
126    /// Left align.
127    Left,
128    /// Right align.
129    Right,
130    /// Right align if the first whitespace-separated token parses as `f64`,
131    /// otherwise left align.
132    Auto,
133}
134
135/// ANSI foreground color.
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub enum Color {
138    /// ANSI color 30.
139    Black,
140    /// ANSI color 31.
141    Red,
142    /// ANSI color 32.
143    Green,
144    /// ANSI color 33.
145    Yellow,
146    /// ANSI color 34.
147    Blue,
148    /// ANSI color 35.
149    Magenta,
150    /// ANSI color 36.
151    Cyan,
152    /// ANSI color 37.
153    White,
154    /// ANSI color 90 (high-intensity black / gray).
155    BrightBlack,
156    /// ANSI color 91.
157    BrightRed,
158    /// ANSI color 92.
159    BrightGreen,
160    /// ANSI color 93.
161    BrightYellow,
162    /// ANSI color 94.
163    BrightBlue,
164    /// ANSI color 95.
165    BrightMagenta,
166    /// ANSI color 96.
167    BrightCyan,
168    /// ANSI color 97.
169    BrightWhite,
170}
171
172impl Color {
173    fn fg_code(self) -> u8 {
174        match self {
175            Color::Black => 30,
176            Color::Red => 31,
177            Color::Green => 32,
178            Color::Yellow => 33,
179            Color::Blue => 34,
180            Color::Magenta => 35,
181            Color::Cyan => 36,
182            Color::White => 37,
183            Color::BrightBlack => 90,
184            Color::BrightRed => 91,
185            Color::BrightGreen => 92,
186            Color::BrightYellow => 93,
187            Color::BrightBlue => 94,
188            Color::BrightMagenta => 95,
189            Color::BrightCyan => 96,
190            Color::BrightWhite => 97,
191        }
192    }
193}
194
195/// Table configuration.
196#[derive(Debug, Clone)]
197pub struct Table {
198    rows: Vec<Vec<String>>,
199    style: Style,
200    aligns: Vec<Align>,
201    max_cell_width: Option<usize>,
202    header_color: Option<Color>,
203    body_color: Option<Color>,
204    ambiguous_width: AmbiguousWidth,
205}
206
207impl Table {
208    /// Create a table from `rows`. The first row is treated as the header.
209    ///
210    /// Ambiguous-width characters default to [`AmbiguousWidth::Wide`]
211    /// (2 columns). Override with [`Table::ambiguous_width`] or
212    /// [`Table::cjk_context`].
213    pub fn new(rows: Vec<Vec<String>>) -> Self {
214        Self {
215            rows,
216            style: Style::Simple,
217            aligns: Vec::new(),
218            max_cell_width: None,
219            header_color: None,
220            body_color: None,
221            ambiguous_width: AmbiguousWidth::default(),
222        }
223    }
224
225    /// Create a table from an `ndarray::Array2<String>`.
226    pub fn from_array2(array: Array2<String>) -> Self {
227        let rows = array
228            .outer_iter()
229            .map(|row| row.iter().cloned().collect())
230            .collect();
231        Self::new(rows)
232    }
233
234    /// Set the border style. Default is [`Style::Simple`].
235    pub fn style(mut self, style: Style) -> Self {
236        self.style = style;
237        self
238    }
239
240    /// Set per-column alignment. Missing columns default to [`Align::Left`].
241    pub fn aligns(mut self, aligns: Vec<Align>) -> Self {
242        self.aligns = aligns;
243        self
244    }
245
246    /// Truncate data cells to at most `width` display columns.
247    pub fn max_cell_width(mut self, width: usize) -> Self {
248        self.max_cell_width = Some(width);
249        self
250    }
251
252    /// Set the header foreground color.
253    pub fn header_color(mut self, color: Color) -> Self {
254        self.header_color = Some(color);
255        self
256    }
257
258    /// Set the data-row foreground color.
259    pub fn body_color(mut self, color: Color) -> Self {
260        self.body_color = Some(color);
261        self
262    }
263
264    /// Set how ambiguous-width characters (`Φ`, `±`, `Ⅱ`, ...) are counted.
265    ///
266    /// Default is [`AmbiguousWidth::Wide`] (2 columns, CJK terminals).
267    /// Use [`AmbiguousWidth::Narrow`] for Western terminals, or
268    /// [`AmbiguousWidth::Auto`] to guess from locale environment variables.
269    pub fn ambiguous_width(mut self, mode: AmbiguousWidth) -> Self {
270        self.ambiguous_width = mode;
271        self
272    }
273
274    /// Convenience: set [`AmbiguousWidth::Narrow`] or [`AmbiguousWidth::Wide`].
275    pub fn cjk_context(self, cjk: bool) -> Self {
276        let mode = if cjk {
277            AmbiguousWidth::Wide
278        } else {
279            AmbiguousWidth::Narrow
280        };
281        self.ambiguous_width(mode)
282    }
283
284    /// Render the table to a `String`. Every line ends with `\n`.
285    pub fn render(&self) -> String {
286        if self.rows.is_empty() {
287            return String::new();
288        }
289        let aw = self.ambiguous_width.resolve();
290        let widths = self.column_widths(aw);
291        let mut out = String::new();
292
293        match self.style {
294            Style::Simple => {
295                out.push('│');
296                out.push_str(&self.render_row(&self.rows[0], &widths, true, aw));
297                out.push_str("│\n");
298                out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
299                out.push('\n');
300                for row in &self.rows[1..] {
301                    out.push('│');
302                    out.push_str(&self.render_row(row, &widths, false, aw));
303                    out.push_str("│\n");
304                }
305            }
306            Style::Boxed => {
307                out.push_str(&Self::horizontal(&widths, "┌", "┬", "┐", "─"));
308                out.push('\n');
309                out.push('│');
310                out.push_str(&self.render_row(&self.rows[0], &widths, true, aw));
311                out.push_str("│\n");
312                out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
313                out.push('\n');
314                for (i, row) in self.rows[1..].iter().enumerate() {
315                    out.push('│');
316                    out.push_str(&self.render_row(row, &widths, false, aw));
317                    out.push_str("│\n");
318                    if i + 1 < self.rows.len() - 1 {
319                        out.push_str(&Self::horizontal(&widths, "├", "┼", "┤", "─"));
320                        out.push('\n');
321                    }
322                }
323                out.push_str(&Self::horizontal(&widths, "└", "┴", "┘", "─"));
324                out.push('\n');
325            }
326        }
327        out
328    }
329}
330
331impl Table {
332    fn align_of(&self, col: usize) -> Align {
333        self.aligns.get(col).copied().unwrap_or(Align::Left)
334    }
335
336    fn column_count(&self) -> usize {
337        self.rows.iter().map(|r| r.len()).max().unwrap_or(0)
338    }
339
340    fn prepare_cell(&self, content: &str, aw: usize) -> (String, usize) {
341        let stripped = strip_ansi(content);
342        let trimmed = stripped.trim();
343        let truncated = match self.max_cell_width {
344            Some(max) => truncate_visible_with(trimmed, max, aw),
345            None => trimmed.to_string(),
346        };
347        let w = display_width_with(&truncated, aw);
348        (truncated, w)
349    }
350
351    fn column_widths(&self, aw: usize) -> Vec<usize> {
352        let cols = self.column_count();
353        let mut widths = vec![0usize; cols];
354        for (r, row) in self.rows.iter().enumerate() {
355            for (i, cell) in row.iter().enumerate() {
356                let w = if r == 0 {
357                    display_width_with(cell, aw)
358                } else {
359                    let (_, w) = self.prepare_cell(cell, aw);
360                    w
361                };
362                if w > widths[i] {
363                    widths[i] = w;
364                }
365            }
366        }
367        widths.into_iter().map(|w| w + 2).collect()
368    }
369
370    fn render_cell(&self, content: &str, width: usize, align: Align, aw: usize) -> String {
371        let (text, vis) = self.prepare_cell(content, aw);
372        let inner = width.saturating_sub(2);
373        let pad = inner.saturating_sub(vis);
374
375        let aligned = match align {
376            Align::Left => format!("{}{}", text, " ".repeat(pad)),
377            Align::Right => format!("{}{}", " ".repeat(pad), text),
378            Align::Auto => {
379                if is_numeric_like(&strip_ansi(content)) {
380                    format!("{}{}", " ".repeat(pad), text)
381                } else {
382                    format!("{}{}", text, " ".repeat(pad))
383                }
384            }
385        };
386
387        let padded = format!(" {} ", aligned);
388        colorize(&padded, self.body_color)
389    }
390
391    fn render_header_cell(&self, content: &str, width: usize, aw: usize) -> String {
392        let stripped = strip_ansi(content);
393        let vis = display_width_with(&stripped, aw);
394        let inner = width.saturating_sub(2);
395        let pad = inner.saturating_sub(vis);
396        let padded = format!(" {}{} ", stripped, " ".repeat(pad));
397        colorize(&padded, self.header_color)
398    }
399
400    fn render_row(
401        &self,
402        row: &[String],
403        widths: &[usize],
404        is_header: bool,
405        aw: usize,
406    ) -> String {
407        let mut cells = Vec::with_capacity(widths.len());
408        for (i, w) in widths.iter().enumerate() {
409            let content = row.get(i).map(String::as_str).unwrap_or("");
410            if is_header {
411                cells.push(self.render_header_cell(content, *w, aw));
412            } else {
413                let align = self.align_of(i);
414                cells.push(self.render_cell(content, *w, align, aw));
415            }
416        }
417        cells.join("│")
418    }
419
420    fn horizontal(widths: &[usize], left: &str, mid: &str, right: &str, fill: &str) -> String {
421        let segments: Vec<String> = widths.iter().map(|w| fill.repeat(*w)).collect();
422        format!("{}{}{}", left, segments.join(mid), right)
423    }
424}
425
426/// Convenience function: render a table directly.
427pub fn render_table(rows: Vec<Vec<String>>, style: Style) -> String {
428    Table::new(rows).style(style).render()
429}
430
431// ============================================================
432// Color
433// ============================================================
434
435fn colorize(s: &str, color: Option<Color>) -> String {
436    match color {
437        Some(c) => format!("\x1b[{}m{}\x1b[0m", c.fg_code(), s),
438        None => s.to_string(),
439    }
440}
441
442// ============================================================
443// Width
444// ============================================================
445
446/// Is `c` in the Unicode `East_Asian_Width=Ambiguous` category?
447fn is_ambiguous(c: char) -> bool {
448    matches!(
449        c,
450        '\u{0391}'..='\u{03A9}'
451        | '\u{03B1}'..='\u{03C9}'
452        | '±' | '×' | '÷' | '≤' | '≥' | '≠' | '≈' | '∞' | '√'
453        | '→' | '←' | '↑' | '↓' | '↔'
454        | 'Ⅰ' | 'Ⅱ' | 'Ⅲ' | 'Ⅳ' | 'Ⅴ' | 'Ⅵ' | 'Ⅶ' | 'Ⅷ' | 'Ⅸ' | 'Ⅹ'
455        | 'ⅰ' | 'ⅱ' | 'ⅲ' | 'ⅳ' | 'ⅴ' | 'ⅵ' | 'ⅶ' | 'ⅷ' | 'ⅸ' | 'ⅹ'
456        | '①'..='⑳'
457    )
458}
459
460/// Width of a single `char`, treating ambiguous characters as `aw` columns.
461fn char_width(c: char, aw: usize) -> usize {
462    if is_ambiguous(c) {
463        aw
464    } else {
465        UnicodeWidthChar::width(c).unwrap_or(0)
466    }
467}
468
469/// Display width of `s` with a given ambiguous-character width `aw`.
470fn display_width_with(s: &str, aw: usize) -> usize {
471    let stripped = strip_ansi(s);
472    stripped.chars().map(|c| char_width(c, aw)).sum()
473}
474
475/// Terminal display width of `s`, ignoring ANSI escape sequences.
476///
477/// Uses [`AmbiguousWidth::default`] (currently `Wide`).
478pub fn display_width(s: &str) -> usize {
479    display_width_with(s, AmbiguousWidth::default().resolve())
480}
481
482/// Pad `s` on the right with spaces up to `width` display columns.
483pub fn pad_right_with_spaces(s: &str, width: usize) -> String {
484    let w = display_width(s);
485    if w >= width {
486        return s.to_string();
487    }
488    let mut out = String::with_capacity(s.len() + (width - w));
489    out.push_str(s);
490    out.push_str(&" ".repeat(width - w));
491    out
492}
493
494/// Pad `s` on the left with spaces up to `width` display columns.
495pub fn pad_left_with_spaces(s: &str, width: usize) -> String {
496    let w = display_width(s);
497    if w >= width {
498        return s.to_string();
499    }
500    let mut out = String::with_capacity(s.len() + (width - w));
501    out.push_str(&" ".repeat(width - w));
502    out.push_str(s);
503    out
504}
505
506// ============================================================
507// ANSI
508// ============================================================
509
510/// Strip CSI-style ANSI escape sequences (e.g. `\x1b[...m`) from `s`.
511pub fn strip_ansi(s: &str) -> String {
512    let mut out = String::with_capacity(s.len());
513    let mut chars = s.chars().peekable();
514    while let Some(c) = chars.next() {
515        if c == '\x1b' {
516            if chars.peek() == Some(&'[') {
517                chars.next();
518                for c2 in chars.by_ref() {
519                    if c2.is_ascii_alphabetic() {
520                        break;
521                    }
522                }
523            }
524        } else {
525            out.push(c);
526        }
527    }
528    out
529}
530
531// ============================================================
532// Truncation
533// ============================================================
534
535/// Truncate `s` to at most `max_width` display columns.
536///
537/// Uses [`AmbiguousWidth::default`] (currently `Wide`). For an explicit
538/// choice, use [`truncate_visible_with`].
539pub fn truncate_visible(s: &str, max_width: usize) -> String {
540    truncate_visible_with(s, max_width, AmbiguousWidth::default().resolve())
541}
542
543/// Truncate `s` to at most `max_width` display columns, using `aw` for
544/// ambiguous characters.
545pub fn truncate_visible_with(s: &str, max_width: usize, aw: usize) -> String {
546    if max_width == 0 {
547        return String::new();
548    }
549    let vis = display_width_with(s, aw);
550    if vis <= max_width {
551        return s.to_string();
552    }
553    let suffix = "...";
554    let suffix_w = 3usize;
555    if max_width <= suffix_w {
556        return suffix.to_string();
557    }
558    let target = max_width - suffix_w;
559    let mut out = String::new();
560    let mut used = 0usize;
561    let mut chars = s.chars().peekable();
562    while let Some(c) = chars.next() {
563        if c == '\x1b' {
564            out.push(c);
565            if chars.peek() == Some(&'[') {
566                out.push(chars.next().unwrap());
567                for c2 in chars.by_ref() {
568                    out.push(c2);
569                    if c2.is_ascii_alphabetic() {
570                        break;
571                    }
572                }
573            }
574            continue;
575        }
576        let cw = char_width(c, aw);
577        if used + cw > target {
578            break;
579        }
580        out.push(c);
581        used += cw;
582    }
583    out.push_str(suffix);
584    out
585}
586
587// ============================================================
588// Numeric heuristic
589// ============================================================
590
591/// Return `true` if `s` looks like a number, for [`Align::Auto`].
592pub fn is_numeric_like(s: &str) -> bool {
593    let s = s.trim();
594    if s.is_empty() {
595        return false;
596    }
597    let head = s.split_whitespace().next().unwrap_or("");
598    head.parse::<f64>().is_ok()
599}
600
601// ============================================================
602// Tests
603// ============================================================
604
605#[cfg(test)]
606mod tests {
607    use super::*;
608    use unicode_width::UnicodeWidthStr;
609
610    #[test]
611    fn phi_is_ambiguous_width() {
612        let s = "Φ170";
613        assert_eq!(UnicodeWidthStr::width(s), 4);
614        assert_eq!(UnicodeWidthStr::width_cjk(s), 4);
615        assert_eq!(display_width_with(s, 2), 5);
616        assert_eq!(display_width_with(s, 1), 4);
617    }
618
619    #[test]
620    fn ambiguous_width_respects_context() {
621        assert_eq!(display_width_with("Φ", 2), 2);
622        assert_eq!(display_width_with("Φ", 1), 1);
623        assert_eq!(display_width_with("Φ170", 2), 5);
624        assert_eq!(display_width_with("Φ170", 1), 4);
625        assert_eq!(display_width_with("Φ8", 2), 3);
626        assert_eq!(display_width_with("Φ16  III", 2), 9);
627        assert_eq!(display_width_with("Φ16  III", 1), 8);
628    }
629
630    #[test]
631    fn default_ambiguous_width_is_wide() {
632        // 默认是 Wide。
633        assert_eq!(AmbiguousWidth::default(), AmbiguousWidth::Wide);
634        assert_eq!(display_width("Φ"), 2);
635        assert_eq!(display_width("Φ170"), 5);
636    }
637
638    #[test]
639    fn display_width_ascii_unchanged() {
640        assert_eq!(display_width("abc"), 3);
641        assert_eq!(display_width("170CD1"), 6);
642        assert_eq!(display_width("NUT-1"), 5);
643    }
644
645    #[test]
646    fn display_width_cjk_unchanged() {
647        assert_eq!(display_width("电杆"), 4);
648        assert_eq!(display_width("名称"), 4);
649        assert_eq!(display_width("电阻值设计定"), 12);
650    }
651
652    #[test]
653    fn display_width_strips_ansi() {
654        let colored = "\x1b[93m电杆\x1b[0m";
655        assert_eq!(display_width(colored), 4);
656    }
657
658    #[test]
659    fn phi_rows_align_default_wide() {
660        // 默认(Wide)下,含 Φ 的行应和其它行对齐。
661        let rows = vec![
662            vec!["名称".into(), "规格".into(), "材料".into()],
663            vec!["电杆".into(), "Φ170".into(), "".into()],
664            vec!["横担".into(), "03D103-133".into(), "2II2".into()],
665            vec!["接地线".into(), "Φ8".into(), "".into()],
666            vec!["拉线棒".into(), "03D103-187".into(), "Φ16  III".into()],
667        ];
668        let out = Table::new(rows).style(Style::Boxed).render();
669        for line in out.lines() {
670            if line.starts_with('│') {
671                assert_eq!(line.matches('│').count(), 4, "行: {:?}", line);
672            }
673        }
674    }
675
676    #[test]
677    fn phi_rows_align_narrow() {
678        let rows = vec![
679            vec!["名称".into(), "规格".into(), "材料".into()],
680            vec!["电杆".into(), "Φ170".into(), "".into()],
681            vec!["横担".into(), "03D103-133".into(), "2II2".into()],
682            vec!["接地线".into(), "Φ8".into(), "".into()],
683            vec!["拉线棒".into(), "03D103-187".into(), "Φ16  III".into()],
684        ];
685        let out = Table::new(rows)
686            .style(Style::Boxed)
687            .ambiguous_width(AmbiguousWidth::Narrow)
688            .render();
689        for line in out.lines() {
690            if line.starts_with('│') {
691                assert_eq!(line.matches('│').count(), 4, "行: {:?}", line);
692            }
693        }
694    }
695
696    #[test]
697    fn truncate_phi_consistent_wide() {
698        let s = "Φ170CD1XYZ";
699        let t = truncate_visible_with(s, 6, 2);
700        assert_eq!(t, "Φ1...");
701        assert_eq!(display_width_with(&t, 2), 6);
702    }
703
704    #[test]
705    fn truncate_phi_consistent_narrow() {
706        let s = "Φ170CD1XYZ";
707        let t = truncate_visible_with(s, 6, 1);
708        assert_eq!(t, "Φ17...");
709        assert_eq!(display_width_with(&t, 1), 6);
710    }
711
712    #[test]
713    fn truncate_visible_two_arg_uses_default_wide() {
714        // 两参数版本用默认(Wide):Φ(2) + 1(1) = 3 → "Φ1..."
715        let t = truncate_visible("Φ170CD1XYZ", 6);
716        assert_eq!(t, "Φ1...");
717    }
718
719    #[test]
720    fn truncate_ascii_unchanged() {
721        let s = "abcdefghij";
722        let t = truncate_visible_with(s, 7, 2);
723        assert_eq!(t, "abcd...");
724        assert_eq!(display_width_with(&t, 2), 7);
725    }
726
727    #[test]
728    fn truncate_no_overflow_returns_original() {
729        let s = "Φ8";
730        let t = truncate_visible_with(s, 10, 2);
731        assert_eq!(t, "Φ8");
732    }
733
734    #[test]
735    fn cjk_context_builder_sets_mode() {
736        let t = Table::new(vec![vec!["a".into()]]).cjk_context(true);
737        assert_eq!(t.ambiguous_width, AmbiguousWidth::Wide);
738        let t = Table::new(vec![vec!["a".into()]]).cjk_context(false);
739        assert_eq!(t.ambiguous_width, AmbiguousWidth::Narrow);
740    }
741}