Expand description
§slice-ansi — slice strings by terminal display column
Extract a substring covering a range of terminal display columns, correctly
handling wide (CJK) characters (two columns) and ANSI escape sequences
(zero columns). Styling active at the cut is re-applied to the slice and reset
at the end, so the result renders the same as that part of the original. A Rust
take on Node’s slice-ansi.
use slice_ansi::{slice, width};
assert_eq!(slice("hello", 1, 3), "el");
assert_eq!(slice("古池や蛙", 0, 4), "古池"); // wide chars
assert_eq!(slice("\u{1b}[31mhello\u{1b}[0m", 1, 3), "\u{1b}[31mel\u{1b}[0m");
assert_eq!(width("\u{1b}[31mhi\u{1b}[0m"), 2); // ANSI = zero width§Behavior
- Columns are half-open
[start, end);endis clamped to the string width andstart >= endyields"". Output width never exceedsend - start. - A wide character that straddles either boundary is excluded, so the result is never a broken half-glyph. Combining marks travel with their base character.
- SGR styling active at
startis re-emitted at the front of the slice, and a reset (\x1b[0m) is appended when styling is still open at the end — color can’t leak, and a reset already inside the slice isn’t duplicated. An OSC 8 hyperlink open at the cut is likewise re-opened and closed so links stay balanced. - Escape sequences (CSI, OSC, DCS/etc., two-byte/nF escapes, 8-bit C1) are recognized as zero width and never split.
- Limitations: attribute-off SGR codes (
39/49,22–29) aren’t collapsed, so a slice may carry a redundant (but correctly rendering) style; and a cut inside a multi-codepoint grapheme cluster (a ZWJ emoji) may split it.
Functions§
- slice
- Slice
textto the display columns[start, end), preserving ANSI styling. - slice_
from - Slice
textfrom display columnstartto the end of the string. - width
- The display width of
textin terminal columns, ignoring escape sequences and counting wide characters as two.