console-table
A small, dependency-light Rust library for rendering aligned console tables.
It is Unicode-aware (CJK characters count as 2 columns), handles
ambiguous-width characters like Φ predictably, supports optional per-cell
truncation, ANSI foreground colors, and two border styles.
Table of contents
- Features
- Installation
- Quick start
- Ambiguous-width characters
- Before and after
- API overview
- Design notes
- Windows note
- FAQ
- License
Features
- Unicode / CJK-aware alignment — uses
unicode-widthso that Chinese, Japanese, Korean, fullwidth, and zero-width characters are measured by their real terminal display width, not bycharcount. - Predictable ambiguous-width handling — characters like
Φ,±,Ⅱ,①have UnicodeEast_Asian_Width=Ambiguousand render as 1 or 2 columns depending on the terminal. By default they are counted as 2 columns, which matches CJK terminals. See Ambiguous-width characters to override. - Two border styles —
Style::Simple(header separator only) andStyle::Boxed(full box drawing). - Per-column alignment —
Align::Left,Align::Right, orAlign::Auto(numbers right-aligned, everything else left-aligned). - Truncation — cap any data cell at
max_cell_width; overflow becomes ASCII.... Headers are never truncated. - ANSI colors — optional
header_colorandbody_colorfrom a small built-in palette. - ANSI-safe width math — existing ANSI sequences inside cell text are stripped before width is measured, so colored input does not break layout.
- Only one dependency —
unicode-width.
Installation
Add this to your Cargo.toml:
[]
= "0.2"
{Align, Color, Style, Table};
{
= vec![
"#".into(), "source".into(), "latency".into()],
"1".into(), "rsproxy (ByteDance)".into(), "57 ms".into()],
"2".into(), "tuna (Tsinghua)".into(), "16 ms".into()],
"8".into(), "cqu (Chongqing)".into(), "failed".into()],
];
= Table::new(rows)
.style(Style::Boxed)
.aligns(vec![Align::Right, Align::Left, Align::Auto])
.max_cell_width(40)
.header_color(Color::BrightCyan)
.body_color(Color::White);
"{}", table.render());
}
colors not shown):
┌──────┬─────────────────────┬──────────┐
│ # │ source │ latency │
├──────┼─────────────────────┼──────────┤
│ 1 │ rsproxy (ByteDance) │ 57 ms │
│ 2 │ tuna (Tsinghua) │ 16 ms │
│ 8 │ cqu (Chongqing) │ failed │
└──────┴─────────────────────┴──────────┘
=Ambiguous. The most common one
(U+03A6, Greek capital Phi), but the category also
, ×, ÷, ≤, Ⅱ, ① and others.
depending on the terminal software, the font,
not on the operating system language. For example:
renders as
e.g. Windows cmd.exe with a CJK font) 2 columns
default narrow) 1 column
wide setting) 2 columns
ambiguous characters are
AmbiguousWidth::Wide). This is a fixed
not a guess. If your terminal renders Φ as 1 column, override it:
{AmbiguousWidth, Table};
// Your terminal renders Φ as 1 column:
= Table::new(rows).cjk_context(false);
// equivalently:
= Table::new(rows).ambiguous_width(AmbiguousWidth::Narrow);
counted as When to use
Wide (default) 2 columns CJK terminals, Windows cmd.exe with a CJK font, most Chinese/Japanese/Korean consoles
Narrow 1 column Western terminals, Windows Terminal default, VS Code, iTerm2
Auto guessed from LANG/LC_ALL/LC_CTYPE You want locale-based guessing; not reliable, see below
LC_ALL, and LC_CTYPE for a CJK locale prefix
(zh, ja, ko). But the environment locale does not determine how the
=en_US.UTF-8 (English environment), but the terminal still renders Φ
1 column) and the table misaligns,
2 columns) stays aligned.
the default is Wide.
opt in explicitly:
{AmbiguousWidth, Table};
= Table::new(rows).ambiguous_width(AmbiguousWidth::Auto);
under both modes and see which one aligns:
{Style, Table};
= vec![
"名称".into(), "规格".into(), "材料".into()],
"电杆".into(), "Φ170".into(), "".into()],
"横担".into(), "03D103-133".into(), "2II2".into()],
];
"--- Wide ---");
new(rows.clone()).style(Style::Boxed).cjk_context(true).render()
);
"--- Narrow ---");
new(rows).style(Style::Boxed).cjk_context(false).render()
);
aligned is the mode your terminal needs.
(Wide). If you need an explicit mode outside of Table, use the _with
{display_width, truncate_visible};
// 5 (Φ = 2)
6); // "Φ1..." (Φ = 2)
the _with functions take the ambiguous width directly:
{display_width_with, truncate_visible_with};
1); // 4 (Φ = 1, Narrow)
6, 1); // "Φ17..."
display_width_with and truncate_visible_with are public but
rendered three ways. The first two use plain format! and
the third uses console-table and stays
= ["序号", "镜像源", "平均延迟", "可用", "serde最新版"];
= [
["1", "rsproxy (字节跳动)", "57 ms", "是", "1.0.229"],
[ "tuna (清华)", "16 ms", "是", "1.0.229"],
[ "cqu (重大)", "失败", "否", "-"],
];
manual format!
{:<20} pads by char count, so Chinese characters
(which occupy 2 terminal columns each) collapse the columns.
&[&str; 5], data: &[[&str; 5]; 3]) {
headers[1], headers[2], headers[3], headers[4]
);
"{}", "-".repeat(60));
row[1], row[2], row[3], row[4]
);
}
}
序号 镜像源 平均延迟 可用 serde最新版
rsproxy (字节跳动) 57 ms 是 1.0.229
tuna (清华) 16 ms 是 1.0.229
cqu (重大) 失败 否 -
manual width handling
you need your own display-width function, a fixed width
and manual padding. It works, but it is a lot of boilerplate, and every
&str) -> usize {
.map(|c| {
= c as u32;
0x1100..=0x115F).contains(&cp)
|| (0x2E80..=0xA4CF).contains(&cp)
|| (0xAC00..=0xD7A3).contains(&cp)
|| (0xF900..=0xFAFF).contains(&cp)
|| (0xFE30..=0xFE4F).contains(&cp)
|| (0xFF00..=0xFF60).contains(&cp)
|| (0xFFE0..=0xFFE6).contains(&cp)
{
} else {
}
})
.sum()
}
&[&str; 5], data: &[[&str; 5]; 3]) {
= [4usize, 22, 12, 8, 14];
= |cells: &[&str]| {
= String::new();
i, cell) in cells.iter().enumerate() {
= display_width(cell);
widths[i] {
" ".repeat(widths[i] - w));
}
}
};
"{}", fmt_row(headers));
"{}", "-".repeat(70));
"{}", fmt_row(row));
}
}
序号 镜像源 平均延迟 可用 serde最新版
rsproxy (字节跳动) 57 ms 是 1.0.229
tuna (清华) 16 ms 是 1.0.229
cqu (重大) 失败 否 -
but no borders, no per-column alignment, no truncation, no colors.
console-table
{Align, Color, Style, Table};
= vec![
"序号".into(), "镜像源".into(), "平均延迟".into(), "可用".into(), "serde最新版".into()],
"1".into(), "rsproxy (字节跳动)".into(), "57 ms".into(), "是".into(), "1.0.229".into()],
"2".into(), "tuna (清华)".into(), "16 ms".into(), "是".into(), "1.0.229".into()],
"8".into(), "cqu (重大)".into(), "失败".into(), "否".into(), "-".into()],
];
= Table::new(rows)
.style(Style::Boxed)
.aligns(vec![
Right, // 序号
Left, // 镜像源
Auto, // 平均延迟:数字右对齐,"失败" 左对齐
Left, // 可用
Left, // serde最新版
])
.header_color(Color::BrightCyan)
.body_color(Color::White);
"{}", table.render());
┌──────┬────────────────────┬──────────┬──────┬─────────────┐
│ 序号 │ 镜像源 │ 平均延迟 │ 可用 │ serde最新版 │
├──────┼────────────────────┼──────────┼──────┼─────────────┤
│ 1 │ rsproxy (字节跳动) │ 57 ms │ 是 │ 1.0.229 │
│ 2 │ tuna (清华) │ 16 ms │ 是 │ 1.0.229 │
│ 8 │ cqu (重大) │ 失败 │ 否 │ - │
└──────┴────────────────────┴──────────┴──────┴─────────────┘
with truncation
...
= rows.clone();
push("地址".to_string());
= [
"sparse+https://rsproxy.cn/index/",
"sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/",
"sparse+https://mirrors.cqu.edu.cn/crates.io-index/",
];
i, url) in urls.iter().enumerate() {
1].push((*url).to_string());
}
= Table::new(rows_with_url)
.style(Style::Boxed)
.aligns(vec![
Right, Align::Left, Align::Auto,
Left, Align::Left, Align::Left,
])
.max_cell_width(40)
.header_color(Color::BrightCyan)
.body_color(Color::White);
"{}", table.render());
┌──────┬────────────────────┬──────────┬──────┬─────────────┬──────────────────────────────────────────┐
│ 序号 │ 镜像源 │ 平均延迟 │ 可用 │ serde最新版 │ 地址 │
├──────┼────────────────────┼──────────┼──────┼─────────────┼──────────────────────────────────────────┤
│ 1 │ rsproxy (字节跳动) │ 57 ms │ 是 │ 1.0.229 │ sparse+https://rsproxy.cn/index/ │
│ 2 │ tuna (清华) │ 16 ms │ 是 │ 1.0.229 │ sparse+https://mirrors.tuna.tsinghua.edu… │
│ 8 │ cqu (重大) │ 失败 │ 否 │ - │ sparse+https://mirrors.cqu.edu.cn/crates… │
└──────┴────────────────────┴──────────┴──────┴─────────────┴──────────────────────────────────────────┘
manual width fn console-table
✓ ✓
✗ ✓
✗ ✓
✗ ✓
✗ ✓
✗ ✓
✗ ✓
6 ~30 ~10
new(rows) Create a table. The first row is treated as the header. Rows may have different lengths; missing cells are treated as empty.
.style(Style) Style::Simple (default) or Style::Boxed.
.aligns(Vec<Align>) Per-column alignment. Missing columns default to Align::Left.
.max_cell_width(usize) Truncate data cells to at most this display width. Headers are not truncated.
.header_color(Color) Foreground color for the header row.
.body_color(Color) Foreground color for data rows.
.ambiguous_width(AmbiguousWidth) How to count ambiguous-width characters. Default Wide.
.cjk_context(bool) Shorthand for .ambiguous_width(Wide) / .ambiguous_width(Narrow).
.render() -> String Render the table. Every line ends with \n.
counted as Description
default) 2 columns Matches CJK terminals.
opt in only if you have verified it.
a single separator, then data rows.
header separator, row separators, and bottom border.
otherwise left align.
Red, Green, Yellow, Blue, Magenta, Cyan, White
BrightRed, BrightGreen, BrightYellow,
BrightMagenta, BrightCyan, BrightWhite
style) Convenience: Table::new(rows).style(style).render().
str) -> usize Terminal display width, ignoring ANSI sequences. Uses the default Wide mode.
str, aw: usize) Same, with explicit ambiguous width (1 or 2).
str, usize) -> String Truncate to a display width, appending ASCII .... Uses the default Wide mode.
str, usize, aw: usize) Same, with explicit ambiguous width (1 or 2).
str) -> String Remove CSI-style ANSI escape sequences.
str, usize) Pad on the right by display width.
str, usize) Pad on the left by display width.
str) -> bool Heuristic used by Align::Auto.
not assumed. Every column is
including the header) + 2,
2 reserves one space of padding on each side.
Φ, ±, Ⅱ, ① and
matching CJK terminals.
if your terminal renders them as 1.
... instead of …. The single-character ellipsis … (U+2026) renders
which breaks alignment.
.. is always exactly 3 columns.
so colored cells never widen a column.
they are removed and replaced by body_color (or no color). Do not mix
and data rows, so the table stays rectangular even when the
prefer disabling colors yourself:
io::IsTerminal;
= Table::new(rows);
= if std::io::stdout().is_terminal() {
BrightCyan).body_color(Color::White)
} else {
};
x1b[...m sequences.
. Windows Terminal defaults to narrow for
one column). If you are rendering into Windows
you may want .cjk_context(false). If you are rendering into
keep the default Wide. See
Φ, ±, Ⅱ, ① and similar are 1 or 2
Wide). If your
call .cjk_context(false). See
(U+2026) as 2
and a few render it as 1. This library uses ASCII ... for
check that your terminal uses a font where
and that
.cjk_context(...) matches your terminal.
=en_US.UTF-8 and still render
Φ as 2 columns (CJK console with a CJK font). Auto would guess Narrow
while the fixed default Wide stays correct. Auto is opt-in
and any ANSI codes
and truncating them can hide useful
apply truncate_visible to the
new.
returns a String. Printing is up to the caller.
Version 2.0
(LICENSE-APACHE or
/www.apache.org/licenses/LICENSE-2.0)
(LICENSE-MIT or
/opensource.org/licenses/MIT)
any contribution intentionally submitted
as defined in the Apache-2.0 license, shall be
without any additional terms or conditions.
## 主要改动
| 位置 | 改动 |
|------|------|
| 顶部简介 | 加"handles ambiguous-width characters like `Φ` predictably" |
| Features | 新增 **Predictable ambiguous-width handling** 一条 |
| Installation | 版本从 `0.1` → `0.2`(默认行为变了,算破坏性) |
| 新增章节 | **Ambiguous-width characters**:解释 `Φ` 类字符、终端差异表、三种模式、为什么 `Auto` 不是默认、如何自测 |
| Before and after 汇总表 | 加一行 "Ambiguous-width handling" |
| API overview | `Table` 加 `.ambiguous_width()`、`.cjk_context()`;新增 `AmbiguousWidth` 枚举表;Free functions 加 `display_width_with`、`truncate_visible_with` |
| Design notes | 加 **Ambiguous characters default to 2 columns** 一条 |
| Windows note | 加 Windows Terminal vs `cmd.exe` 的 `Φ` 差异提示 |
| FAQ | 更新"为什么错位",加"为什么 `Auto` 不是默认" |
## 一句话
> README 新增了 **Ambiguous-width characters** 章节,明确说明 `Φ` 类字符在终端里是 1 还是 2 列**不取决于操作系统语言**,本库**默认 `Wide`(2 列)**,并给出 `.cjk_context(false)` / `.ambiguous_width(Auto)` 的覆盖方式,以及"怎么自测终端需要哪种模式"的示例。API overview、Design notes、FAQ、Windows note 同步更新。