Expand description
§cli-truncate — width-aware string truncation for terminals
Truncate a string to a maximum terminal display width with an ellipsis,
correctly accounting for wide (CJK) characters (which take two columns)
and ANSI escape sequences (which take none). Like Node’s cli-truncate.
assert_eq!(cli_truncate::truncate("unicorn", 4), "uni…");
assert_eq!(cli_truncate::truncate("古池や蛙", 6), "古池…"); // wide chars
assert_eq!(cli_truncate::width("\u{1b}[31mhi\u{1b}[0m"), 2); // ANSI is zero-width§Behavior
- Output never exceeds
max_widthcolumns;max_width == 0yields"". If the ellipsis itself is wider thanmax_width, it is clamped (so the bound always holds). - Escape sequences are recognized and treated as zero width: CSI (
ESC [ … m, incl. 8-bit0x9B), string sequences (OSC hyperlinks, DCS/SOS/PM/APC and their terminators), and two-byte / nF escapes (ESC c,ESC ( B). They are preserved intact and never split across the cut. - 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 flag) may be cut between codepoints. The column budget is always honored regardless.
Structs§
Enums§
- Position
- Where to remove characters when truncating.
Functions§
- truncate
- Truncate
texttomax_widthdisplay columns, dropping the end and adding a…ellipsis. Shorthand forOptions::new().truncate(text, max_width). - width
- The display width of
textin terminal columns, ignoring escape sequences and control characters and counting wide characters as two.