cli-truncate
Truncate strings to a terminal display width with an ellipsis — correctly
handling wide (CJK) characters (two columns) and ANSI escape sequences
(zero columns). A Rust take on Node's cli-truncate.
use ;
assert_eq!;
assert_eq!; // wide chars counted as 2
assert_eq!; // ANSI = zero width
// Position + custom ellipsis
assert_eq!;
assert_eq!;
assert_eq!;
Why cli-truncate?
unicode-truncate truncates by display width, but doesn't understand ANSI color
codes; the heavyweight console crate can, but pulls in a full terminal stack.
cli-truncate is the small, focused piece: truncate styled, wide-character text
to fit a column budget — for tables, status lines, log viewers, and TUIs.
[]
= "0.1"
API
| Item | Purpose |
|---|---|
truncate(text, max_width) |
Truncate at the end with a … ellipsis |
Options::new().position(..).ellipsis(..).truncate(text, max_width) |
Configurable truncation |
width(text) |
Display width in columns (ANSI-ignored, wide chars = 2) |
Position |
End (default), Start, Middle |
Behavior
- Output never exceeds
max_widthcolumns;max_width == 0yields"". An ellipsis wider thanmax_widthis itself clamped, so the bound always holds. - Escape sequences are recognized as zero width and never split across the cut:
CSI (
ESC [ … m, including the 8-bit0x9Bform), string sequences (OSC hyperlinks, DCS/SOS/PM/APC with theirST/BELterminators), and two-byte / nF escapes (ESC c,ESC ( B). - A reset (
\x1b[0m) is appended only when the kept text leaves a style open, so color can't "leak" past the cut and resets are never duplicated. - Other C0/C1 control characters (newline, tab, carriage return, NUL, …) have no defined column width and are dropped from truncated output, so they can't break single-line layout.
- For
Start/Middle, styling that began in the dropped region isn't carried over, and a combining mark whose base was dropped is not orphaned onto the ellipsis. - Truncation respects character boundaries, not grapheme clusters: a multi-codepoint cluster (a ZWJ emoji or a flag) may be cut between codepoints — the column budget is always honored regardless.
Contributors ✨
This project follows the all-contributors specification. Contributions of any kind are welcome — code, docs, bug reports, ideas, reviews! See the emoji key for how each contribution is recognized, and open a PR or issue to get involved.
Thanks goes to these wonderful people:
License
Licensed under either of Apache-2.0 or MIT at your option.