slice_ansi/lib.rs
1//! # slice-ansi — slice strings by terminal display column
2//!
3//! Extract a substring covering a range of terminal **display columns**, correctly
4//! handling **wide (CJK) characters** (two columns) and **ANSI escape sequences**
5//! (zero columns). Styling active at the cut is re-applied to the slice and reset
6//! at the end, so the result renders the same as that part of the original. A Rust
7//! take on Node's [`slice-ansi`](https://www.npmjs.com/package/slice-ansi).
8//!
9//! ```
10//! use slice_ansi::{slice, width};
11//! assert_eq!(slice("hello", 1, 3), "el");
12//! assert_eq!(slice("古池や蛙", 0, 4), "古池"); // wide chars
13//! assert_eq!(slice("\u{1b}[31mhello\u{1b}[0m", 1, 3), "\u{1b}[31mel\u{1b}[0m");
14//! assert_eq!(width("\u{1b}[31mhi\u{1b}[0m"), 2); // ANSI = zero width
15//! ```
16//!
17//! ## Behavior
18//!
19//! - Columns are half-open `[start, end)`; `end` is clamped to the string width and
20//! `start >= end` yields `""`. Output width never exceeds `end - start`.
21//! - A wide character that straddles either boundary is excluded, so the result is
22//! never a broken half-glyph. Combining marks travel with their base character.
23//! - SGR styling active at `start` is re-emitted at the front of the slice, and a
24//! reset (`\x1b[0m`) is appended when styling is still open at the end — color
25//! can't leak, and a reset already inside the slice isn't duplicated. An OSC 8
26//! hyperlink open at the cut is likewise re-opened and closed so links stay balanced.
27//! - Escape sequences (CSI, OSC, DCS/etc., two-byte/nF escapes, 8-bit C1) are
28//! recognized as zero width and never split.
29//! - Limitations: attribute-off SGR codes (`39`/`49`, `22`–`29`) aren't collapsed,
30//! so a slice may carry a redundant (but correctly rendering) style; and a cut
31//! *inside* a multi-codepoint grapheme cluster (a ZWJ emoji) may split it.
32
33#![no_std]
34#![doc(html_root_url = "https://docs.rs/slice-ansi/0.1.0")]
35
36extern crate alloc;
37
38use alloc::string::{String, ToString};
39use alloc::vec::Vec;
40use unicode_width::UnicodeWidthChar;
41
42/// The SGR sequence that resets all styling to its default.
43const RESET: &str = "\u{1b}[0m";
44/// The OSC 8 sequence that closes an open hyperlink.
45const OSC8_CLOSE: &str = "\u{1b}]8;;\u{1b}\\";
46
47/// The display width of `text` in terminal columns, ignoring escape sequences and
48/// counting wide characters as two.
49#[must_use]
50pub fn width(text: &str) -> usize {
51 let chars: Vec<char> = text.chars().collect();
52 let mut total = 0;
53 let mut i = 0;
54 while i < chars.len() {
55 let (scanned, next) = scan(&chars, i);
56 if let Scanned::Visible(c) = scanned {
57 total += char_width(c);
58 }
59 i = next;
60 }
61 total
62}
63
64/// Slice `text` to the display columns `[start, end)`, preserving ANSI styling.
65///
66/// `end` is clamped to the string's display width; `start >= end` returns `""`.
67///
68/// ```
69/// assert_eq!(slice_ansi::slice("hello", 1, 4), "ell");
70/// ```
71#[must_use]
72pub fn slice(text: &str, start: usize, end: usize) -> String {
73 if start >= end {
74 return String::new();
75 }
76
77 let toks = tokenize(text);
78
79 // Locate the visible glyphs fully inside [start, end), and the SGR + hyperlink
80 // state at the first kept glyph (so styling opened before the slice carries in).
81 let mut col = 0;
82 let mut sgr: Vec<String> = Vec::new();
83 let mut link: Option<String> = None;
84 let mut lo: Option<usize> = None;
85 let mut hi = 0;
86 let mut sgr_at_lo: Vec<String> = Vec::new();
87 let mut link_at_lo: Option<String> = None;
88 for (idx, t) in toks.iter().enumerate() {
89 match t {
90 Tok::Esc(s) => {
91 update_sgr(&mut sgr, s);
92 update_link(&mut link, s);
93 }
94 Tok::Ch(_, w) => {
95 let (cs, ce) = (col, col + w);
96 if cs >= end {
97 break;
98 }
99 if cs >= start && ce <= end {
100 if lo.is_none() {
101 lo = Some(idx);
102 sgr_at_lo.clone_from(&sgr);
103 link_at_lo.clone_from(&link);
104 }
105 hi = idx + 1;
106 }
107 col = ce;
108 }
109 }
110 }
111
112 let Some(lo) = lo else {
113 return String::new();
114 };
115
116 let mut out = String::new();
117 if let Some(l) = &link_at_lo {
118 out.push_str(l);
119 }
120 for code in &sgr_at_lo {
121 out.push_str(code);
122 }
123 let mut open_sgr = sgr_at_lo;
124 let mut open_link = link_at_lo;
125 for t in &toks[lo..hi] {
126 match t {
127 Tok::Esc(s) => {
128 out.push_str(s);
129 update_sgr(&mut open_sgr, s);
130 update_link(&mut open_link, s);
131 }
132 Tok::Ch(s, _) => out.push_str(s),
133 }
134 }
135 if !open_sgr.is_empty() {
136 out.push_str(RESET);
137 }
138 if open_link.is_some() {
139 out.push_str(OSC8_CLOSE);
140 }
141 out
142}
143
144/// Slice `text` from display column `start` to the end of the string.
145///
146/// ```
147/// assert_eq!(slice_ansi::slice_from("hello", 2), "llo");
148/// ```
149#[must_use]
150pub fn slice_from(text: &str, start: usize) -> String {
151 slice(text, start, width(text))
152}
153
154// ---------------------------------------------------------------------------
155// SGR / hyperlink state tracking
156// ---------------------------------------------------------------------------
157
158/// Update the active SGR stack from an escape. A reset parameter anywhere in the
159/// sequence clears the stack; a sequence that also sets styles after its last reset
160/// is kept (it self-resets on re-emit); other SGR sequences are pushed.
161fn update_sgr(active: &mut Vec<String>, seq: &str) {
162 let Some(params) = sgr_params(seq) else {
163 return;
164 };
165 let mut last_reset = None;
166 let mut count = 0;
167 for (i, p) in params.split(';').enumerate() {
168 if is_reset_param(p) {
169 last_reset = Some(i);
170 }
171 count = i + 1;
172 }
173 match last_reset {
174 Some(idx) => {
175 active.clear();
176 if idx + 1 < count {
177 active.push(seq.to_string());
178 }
179 }
180 None => active.push(seq.to_string()),
181 }
182}
183
184/// Whether an SGR parameter is a reset (empty, or all zeros).
185fn is_reset_param(p: &str) -> bool {
186 p.is_empty() || p.bytes().all(|b| b == b'0')
187}
188
189/// The parameter substring of an SGR sequence (`CSI … m`), or `None` if not SGR.
190fn sgr_params(seq: &str) -> Option<&str> {
191 let body = match seq.strip_prefix('\u{1b}') {
192 Some(rest) => rest.strip_prefix('[')?,
193 None => seq.strip_prefix('\u{9b}')?,
194 };
195 body.strip_suffix('m')
196}
197
198/// Update the active hyperlink from an escape: an OSC 8 open sets it, a close
199/// clears it, and any other escape leaves it unchanged.
200fn update_link(link: &mut Option<String>, seq: &str) {
201 match osc8_kind(seq) {
202 Some(true) => *link = Some(seq.to_string()),
203 Some(false) => *link = None,
204 None => {}
205 }
206}
207
208/// Classify an OSC 8 hyperlink sequence: `Some(true)` if it opens a link (non-empty
209/// URI), `Some(false)` if it closes one (empty URI), `None` if not an OSC 8 sequence.
210fn osc8_kind(seq: &str) -> Option<bool> {
211 let body = match seq.strip_prefix('\u{1b}') {
212 Some(rest) => rest.strip_prefix(']')?,
213 None => seq.strip_prefix('\u{9d}')?,
214 };
215 let body = body.strip_prefix("8;")?;
216 let body = body
217 .strip_suffix('\u{07}')
218 .or_else(|| body.strip_suffix("\u{1b}\\"))
219 .or_else(|| body.strip_suffix('\u{9c}'))?;
220 let uri = body.split_once(';')?.1;
221 Some(!uri.is_empty())
222}
223
224// ---------------------------------------------------------------------------
225// Tokens
226// ---------------------------------------------------------------------------
227
228/// A parsed token: a zero-width escape sequence (preserved verbatim) or a visible
229/// glyph (a base char plus any trailing combining marks) with its column width.
230enum Tok {
231 Esc(String),
232 Ch(String, usize),
233}
234
235/// Tokenize `text`, preserving escape sequences, dropping control characters, and
236/// folding trailing zero-width chars (combining marks, ZWJ) into the preceding glyph.
237fn tokenize(text: &str) -> Vec<Tok> {
238 let chars: Vec<char> = text.chars().collect();
239 let mut toks = Vec::new();
240 let mut i = 0;
241 while i < chars.len() {
242 let (scanned, next) = scan(&chars, i);
243 match scanned {
244 Scanned::Escape(seq) => {
245 toks.push(Tok::Esc(seq));
246 i = next;
247 }
248 Scanned::Control => i = next,
249 Scanned::Visible(c) => {
250 let w = char_width(c);
251 let mut glyph = String::new();
252 glyph.push(c);
253 i = next;
254 // Absorb following zero-width visible chars into this glyph.
255 while i < chars.len() {
256 let (sc, nx) = scan(&chars, i);
257 match sc {
258 Scanned::Visible(c2) if char_width(c2) == 0 => {
259 glyph.push(c2);
260 i = nx;
261 }
262 _ => break,
263 }
264 }
265 toks.push(Tok::Ch(glyph, w));
266 }
267 }
268 }
269 toks
270}
271
272/// Display width of a single visible char (zero-width chars → 0).
273fn char_width(c: char) -> usize {
274 UnicodeWidthChar::width(c).unwrap_or(0)
275}
276
277// ---------------------------------------------------------------------------
278// Escape / control scanner (single source of truth for width() and tokenize())
279// ---------------------------------------------------------------------------
280
281/// The classification of the token starting at a given index.
282enum Scanned {
283 /// A complete escape sequence (zero display width), preserved verbatim.
284 Escape(String),
285 /// A visible character.
286 Visible(char),
287 /// A C0/C1 control character with no defined column width.
288 Control,
289}
290
291/// Scan one token starting at `chars[i]`, returning it and the index just past it.
292/// Always advances (`next > i`).
293fn scan(chars: &[char], i: usize) -> (Scanned, usize) {
294 let c = chars[i];
295 if c == '\u{1b}' {
296 return scan_escape(chars, i);
297 }
298 match c {
299 '\u{9b}' => return scan_csi(chars, i + 1, i),
300 '\u{90}' | '\u{9d}' | '\u{98}' | '\u{9e}' | '\u{9f}' => {
301 return scan_string_sequence(chars, i + 1, i);
302 }
303 _ => {}
304 }
305 if c.is_control() {
306 return (Scanned::Control, i + 1);
307 }
308 (Scanned::Visible(c), i + 1)
309}
310
311/// Scan a 7-bit escape beginning with `ESC` at `chars[i]`.
312fn scan_escape(chars: &[char], i: usize) -> (Scanned, usize) {
313 match chars.get(i + 1).copied() {
314 Some('[') => scan_csi(chars, i + 2, i),
315 Some(']' | 'P' | 'X' | '^' | '_') => scan_string_sequence(chars, i + 2, i),
316 Some(c) if ('\u{20}'..='\u{2f}').contains(&c) => {
317 let mut j = i + 2;
318 while j < chars.len() && ('\u{20}'..='\u{2f}').contains(&chars[j]) {
319 j += 1;
320 }
321 if j < chars.len() && ('\u{30}'..='\u{7e}').contains(&chars[j]) {
322 j += 1;
323 }
324 (Scanned::Escape(collect(chars, i, j)), j)
325 }
326 Some(c) if ('\u{30}'..='\u{7e}').contains(&c) => {
327 (Scanned::Escape(collect(chars, i, i + 2)), i + 2)
328 }
329 _ => (Scanned::Escape(collect(chars, i, i + 1)), i + 1),
330 }
331}
332
333/// Scan a CSI body (params 0x30–0x3F, intermediates 0x20–0x2F, final 0x40–0x7E),
334/// starting at `body` and reporting the sequence from `start`.
335fn scan_csi(chars: &[char], body: usize, start: usize) -> (Scanned, usize) {
336 let mut j = body;
337 while j < chars.len() && ('\u{30}'..='\u{3f}').contains(&chars[j]) {
338 j += 1;
339 }
340 while j < chars.len() && ('\u{20}'..='\u{2f}').contains(&chars[j]) {
341 j += 1;
342 }
343 if j < chars.len() && ('\u{40}'..='\u{7e}').contains(&chars[j]) {
344 j += 1;
345 }
346 (Scanned::Escape(collect(chars, start, j)), j)
347}
348
349/// Scan a string sequence (OSC/DCS/SOS/PM/APC) up to and including its terminator —
350/// `BEL` (0x07), 8-bit `ST` (0x9C), or 7-bit `ST` (`ESC \`).
351fn scan_string_sequence(chars: &[char], body: usize, start: usize) -> (Scanned, usize) {
352 let mut j = body;
353 while j < chars.len() {
354 let c = chars[j];
355 if c == '\u{07}' || c == '\u{9c}' {
356 j += 1;
357 break;
358 }
359 if c == '\u{1b}' && chars.get(j + 1) == Some(&'\\') {
360 j += 2;
361 break;
362 }
363 j += 1;
364 }
365 (Scanned::Escape(collect(chars, start, j)), j)
366}
367
368/// Collect `chars[start..end]` into a `String`.
369fn collect(chars: &[char], start: usize, end: usize) -> String {
370 chars[start..end].iter().collect()
371}