cli_truncate/lib.rs
1//! # cli-truncate — width-aware string truncation for terminals
2//!
3//! Truncate a string to a maximum terminal **display width** with an ellipsis,
4//! correctly accounting for **wide (CJK) characters** (which take two columns)
5//! and **ANSI escape sequences** (which take none). Like Node's `cli-truncate`.
6//!
7//! ```
8//! assert_eq!(cli_truncate::truncate("unicorn", 4), "uni…");
9//! assert_eq!(cli_truncate::truncate("古池や蛙", 6), "古池…"); // wide chars
10//! assert_eq!(cli_truncate::width("\u{1b}[31mhi\u{1b}[0m"), 2); // ANSI is zero-width
11//! ```
12//!
13//! ## Behavior
14//!
15//! - Output never exceeds `max_width` columns; `max_width == 0` yields `""`. If the
16//! ellipsis itself is wider than `max_width`, it is clamped (so the bound always holds).
17//! - Escape sequences are recognized and treated as zero width: CSI (`ESC [ … m`,
18//! incl. 8-bit `0x9B`), string sequences (OSC hyperlinks, DCS/SOS/PM/APC and their
19//! terminators), and two-byte / nF escapes (`ESC c`, `ESC ( B`). They are preserved
20//! intact and never split across the cut.
21//! - A reset (`\x1b[0m`) is appended only when the kept text leaves a style open, so
22//! color can't leak past the cut and resets are never duplicated.
23//! - Other C0/C1 control characters (newline, tab, carriage return, NUL, …) have no
24//! defined column width and are dropped from truncated output so they can't break
25//! single-line layout.
26//! - For `Start`/`Middle`, styling that began in the *dropped* region isn't carried
27//! over, and a combining mark whose base was dropped is not orphaned onto the ellipsis.
28//! - Truncation respects character boundaries, not grapheme clusters: a multi-codepoint
29//! cluster (a ZWJ emoji or flag) may be cut between codepoints. The column budget is
30//! always honored regardless.
31
32#![doc(html_root_url = "https://docs.rs/cli-truncate/0.1.0")]
33
34use unicode_width::UnicodeWidthChar;
35
36/// The SGR sequence that resets all styling to its default.
37const RESET: &str = "\u{1b}[0m";
38
39/// Where to remove characters when truncating.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
41pub enum Position {
42 /// Drop the start, keep the end: `"…corn"`.
43 Start,
44 /// Drop the middle, keep both ends: `"un…rn"`.
45 Middle,
46 /// Drop the end, keep the start: `"uni…"`. The default.
47 #[default]
48 End,
49}
50
51/// Truncation options: ellipsis string and [`Position`].
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct Options {
54 ellipsis: String,
55 position: Position,
56}
57
58impl Default for Options {
59 fn default() -> Self {
60 Self {
61 ellipsis: String::from("\u{2026}"),
62 position: Position::End,
63 }
64 }
65}
66
67impl Options {
68 /// Default options: a `…` ellipsis truncated at the [`Position::End`].
69 #[must_use]
70 pub fn new() -> Self {
71 Self::default()
72 }
73
74 /// Set the ellipsis string appended (or inserted) where text is removed.
75 #[must_use]
76 pub fn ellipsis(mut self, ellipsis: &str) -> Self {
77 ellipsis.clone_into(&mut self.ellipsis);
78 self
79 }
80
81 /// Set where characters are removed.
82 #[must_use]
83 pub fn position(mut self, position: Position) -> Self {
84 self.position = position;
85 self
86 }
87
88 /// Truncate `text` to `max_width` display columns with these options.
89 #[must_use]
90 pub fn truncate(&self, text: &str, max_width: usize) -> String {
91 if max_width == 0 {
92 return String::new();
93 }
94 if width(text) <= max_width {
95 return text.to_owned();
96 }
97
98 let toks = tokenize(text);
99 let ellipsis_width = width(&self.ellipsis);
100
101 // The ellipsis alone doesn't fit: emit a width-clamped ellipsis, no source text.
102 if ellipsis_width >= max_width {
103 return clamp_visible(&self.ellipsis, max_width);
104 }
105 let avail = max_width - ellipsis_width;
106
107 match self.position {
108 Position::End => {
109 let cut = prefix_cut(&toks, avail);
110 let mut out = String::new();
111 let mut open = false;
112 emit(&mut out, &toks[..cut], &mut open);
113 push_tracked(&mut out, &self.ellipsis, &mut open);
114 close(&mut out, open);
115 out
116 }
117 Position::Start => {
118 let keep = drop_leading_zero_width(&toks, suffix_start(&toks, avail));
119 let mut out = String::new();
120 let mut open = false;
121 push_tracked(&mut out, &self.ellipsis, &mut open);
122 emit(&mut out, &toks[keep..], &mut open);
123 close(&mut out, open);
124 out
125 }
126 Position::Middle => {
127 let left = avail / 2;
128 let right = avail - left;
129 let cut = prefix_cut(&toks, left);
130 let keep = drop_leading_zero_width(&toks, suffix_start(&toks, right).max(cut));
131 let mut out = String::new();
132 let mut open = false;
133 emit(&mut out, &toks[..cut], &mut open);
134 push_tracked(&mut out, &self.ellipsis, &mut open);
135 emit(&mut out, &toks[keep..], &mut open);
136 close(&mut out, open);
137 out
138 }
139 }
140 }
141}
142
143/// Truncate `text` to `max_width` display columns, dropping the end and adding a
144/// `…` ellipsis. Shorthand for [`Options::new`]`().truncate(text, max_width)`.
145#[must_use]
146pub fn truncate(text: &str, max_width: usize) -> String {
147 Options::new().truncate(text, max_width)
148}
149
150/// The display width of `text` in terminal columns, ignoring escape sequences and
151/// control characters and counting wide characters as two.
152#[must_use]
153pub fn width(text: &str) -> usize {
154 let chars: Vec<char> = text.chars().collect();
155 let mut total = 0;
156 let mut i = 0;
157 while i < chars.len() {
158 let (scanned, next) = scan(&chars, i);
159 if let Scanned::Visible(c) = scanned {
160 total += char_width(c);
161 }
162 i = next;
163 }
164 total
165}
166
167// ---------------------------------------------------------------------------
168// Tokens
169// ---------------------------------------------------------------------------
170
171/// A parsed token: a zero-width escape sequence (preserved verbatim) or a visible
172/// char with its column width. Control characters are dropped during tokenization.
173enum Tok {
174 Esc(String),
175 Ch(char, usize),
176}
177
178/// Tokenize `text`, preserving escape sequences and dropping control characters.
179fn tokenize(text: &str) -> Vec<Tok> {
180 let chars: Vec<char> = text.chars().collect();
181 let mut toks = Vec::new();
182 let mut i = 0;
183 while i < chars.len() {
184 let (scanned, next) = scan(&chars, i);
185 match scanned {
186 Scanned::Escape(seq) => toks.push(Tok::Esc(seq)),
187 Scanned::Visible(c) => toks.push(Tok::Ch(c, char_width(c))),
188 Scanned::Control => {}
189 }
190 i = next;
191 }
192 toks
193}
194
195/// Display width of a single visible char (zero-width chars → 0).
196fn char_width(c: char) -> usize {
197 UnicodeWidthChar::width(c).unwrap_or(0)
198}
199
200// ---------------------------------------------------------------------------
201// Escape / control scanner (single source of truth for width() and tokenize())
202// ---------------------------------------------------------------------------
203
204/// The classification of the token starting at a given index.
205enum Scanned {
206 /// A complete escape sequence (zero display width), preserved verbatim.
207 Escape(String),
208 /// A visible character.
209 Visible(char),
210 /// A C0/C1 control character with no defined column width.
211 Control,
212}
213
214/// Scan one token starting at `chars[i]`, returning it and the index just past it.
215/// Always advances (`next > i`).
216fn scan(chars: &[char], i: usize) -> (Scanned, usize) {
217 let c = chars[i];
218 if c == '\u{1b}' {
219 return scan_escape(chars, i);
220 }
221 // 8-bit C1 introducers behave like their 7-bit ESC-prefixed forms.
222 match c {
223 '\u{9b}' => return scan_csi(chars, i + 1, i),
224 '\u{90}' | '\u{9d}' | '\u{98}' | '\u{9e}' | '\u{9f}' => {
225 return scan_string_sequence(chars, i + 1, i);
226 }
227 _ => {}
228 }
229 if c.is_control() {
230 return (Scanned::Control, i + 1);
231 }
232 (Scanned::Visible(c), i + 1)
233}
234
235/// Scan a 7-bit escape beginning with `ESC` at `chars[i]`.
236fn scan_escape(chars: &[char], i: usize) -> (Scanned, usize) {
237 match chars.get(i + 1).copied() {
238 // Control Sequence Introducer.
239 Some('[') => scan_csi(chars, i + 2, i),
240 // String sequences: OSC / DCS / SOS / PM / APC.
241 Some(']' | 'P' | 'X' | '^' | '_') => scan_string_sequence(chars, i + 2, i),
242 // nF escape: intermediate bytes (0x20–0x2F) then a final byte (0x30–0x7E).
243 Some(c) if ('\u{20}'..='\u{2f}').contains(&c) => {
244 let mut j = i + 2;
245 while j < chars.len() && ('\u{20}'..='\u{2f}').contains(&chars[j]) {
246 j += 1;
247 }
248 if j < chars.len() && ('\u{30}'..='\u{7e}').contains(&chars[j]) {
249 j += 1;
250 }
251 (Scanned::Escape(slice(chars, i, j)), j)
252 }
253 // Two-byte Fe/Fs escape: ESC followed by a single final byte (0x30–0x7E).
254 Some(c) if ('\u{30}'..='\u{7e}').contains(&c) => {
255 (Scanned::Escape(slice(chars, i, i + 2)), i + 2)
256 }
257 // Lone ESC or ESC + an unexpected byte: treat the ESC as a zero-width sequence.
258 _ => (Scanned::Escape(slice(chars, i, i + 1)), i + 1),
259 }
260}
261
262/// Scan a CSI body (params 0x30–0x3F, intermediates 0x20–0x2F, final 0x40–0x7E),
263/// starting at `body` and reporting the sequence from `start`.
264fn scan_csi(chars: &[char], body: usize, start: usize) -> (Scanned, usize) {
265 let mut j = body;
266 while j < chars.len() && ('\u{30}'..='\u{3f}').contains(&chars[j]) {
267 j += 1;
268 }
269 while j < chars.len() && ('\u{20}'..='\u{2f}').contains(&chars[j]) {
270 j += 1;
271 }
272 if j < chars.len() && ('\u{40}'..='\u{7e}').contains(&chars[j]) {
273 j += 1;
274 }
275 (Scanned::Escape(slice(chars, start, j)), j)
276}
277
278/// Scan a string sequence (OSC/DCS/SOS/PM/APC) up to and including its terminator —
279/// `BEL` (0x07), 8-bit `ST` (0x9C), or 7-bit `ST` (`ESC \`).
280fn scan_string_sequence(chars: &[char], body: usize, start: usize) -> (Scanned, usize) {
281 let mut j = body;
282 while j < chars.len() {
283 let c = chars[j];
284 if c == '\u{07}' || c == '\u{9c}' {
285 j += 1;
286 break;
287 }
288 if c == '\u{1b}' && chars.get(j + 1) == Some(&'\\') {
289 j += 2;
290 break;
291 }
292 j += 1;
293 }
294 (Scanned::Escape(slice(chars, start, j)), j)
295}
296
297/// Collect `chars[start..end]` into a `String`.
298fn slice(chars: &[char], start: usize, end: usize) -> String {
299 chars[start..end].iter().collect()
300}
301
302// ---------------------------------------------------------------------------
303// Emission helpers
304// ---------------------------------------------------------------------------
305
306/// Index just past the last visible char that fits within `avail` columns. Escape
307/// tokens do not advance the cut, so trailing escapes that style only dropped text
308/// are excluded.
309fn prefix_cut(toks: &[Tok], avail: usize) -> usize {
310 let mut used = 0;
311 let mut cut = 0;
312 for (idx, t) in toks.iter().enumerate() {
313 if let Tok::Ch(_, w) = t {
314 if used + w > avail {
315 break;
316 }
317 used += w;
318 cut = idx + 1;
319 }
320 }
321 cut
322}
323
324/// Index of the earliest token such that `toks[i..]` has visible width ≤ `avail`.
325fn suffix_start(toks: &[Tok], avail: usize) -> usize {
326 let mut used = 0;
327 let mut keep_from = toks.len();
328 for (idx, t) in toks.iter().enumerate().rev() {
329 match t {
330 Tok::Ch(_, w) => {
331 if used + w > avail {
332 break;
333 }
334 used += w;
335 keep_from = idx;
336 }
337 Tok::Esc(_) => keep_from = idx,
338 }
339 }
340 keep_from
341}
342
343/// Advance past leading zero-width chars so a kept suffix never starts with a
344/// combining mark (or ZWJ) whose base character was dropped.
345fn drop_leading_zero_width(toks: &[Tok], mut from: usize) -> usize {
346 while let Some(Tok::Ch(_, 0)) = toks.get(from) {
347 from += 1;
348 }
349 from
350}
351
352/// Append a token slice to `out`, tracking whether a style is left open.
353fn emit(out: &mut String, toks: &[Tok], open: &mut bool) {
354 for t in toks {
355 match t {
356 Tok::Ch(c, _) => out.push(*c),
357 Tok::Esc(s) => {
358 out.push_str(s);
359 update_style(open, s);
360 }
361 }
362 }
363}
364
365/// Append a raw string to `out`, tracking any style its escape sequences set.
366fn push_tracked(out: &mut String, s: &str, open: &mut bool) {
367 out.push_str(s);
368 for t in tokenize(s) {
369 if let Tok::Esc(seq) = t {
370 update_style(open, &seq);
371 }
372 }
373}
374
375/// Append a reset if a non-default style is still open.
376fn close(out: &mut String, open: bool) {
377 if open {
378 out.push_str(RESET);
379 }
380}
381
382/// Update the "style open" flag from an SGR sequence (non-SGR escapes are ignored).
383fn update_style(open: &mut bool, seq: &str) {
384 if let Some(is_reset) = sgr_is_reset(seq) {
385 *open = !is_reset;
386 }
387}
388
389/// For an SGR sequence (`CSI … m`), `Some(true)` if it resets all attributes,
390/// `Some(false)` otherwise; `None` if `seq` is not an SGR sequence.
391fn sgr_is_reset(seq: &str) -> Option<bool> {
392 let body = match seq.strip_prefix('\u{1b}') {
393 Some(rest) => rest.strip_prefix('[')?,
394 None => seq.strip_prefix('\u{9b}')?,
395 };
396 let params = body.strip_suffix('m')?;
397 Some(
398 params
399 .split(';')
400 .all(|p| p.is_empty() || p.bytes().all(|b| b == b'0')),
401 )
402}
403
404/// Keep escapes plus visible chars from `s` up to `max` columns, closing any open
405/// style. Used when the ellipsis alone exceeds `max_width`.
406fn clamp_visible(s: &str, max: usize) -> String {
407 let mut out = String::new();
408 let mut used = 0;
409 let mut open = false;
410 for t in tokenize(s) {
411 match t {
412 Tok::Ch(c, w) => {
413 if used + w > max {
414 break;
415 }
416 out.push(c);
417 used += w;
418 }
419 Tok::Esc(seq) => {
420 out.push_str(&seq);
421 update_style(&mut open, &seq);
422 }
423 }
424 }
425 close(&mut out, open);
426 out
427}