Skip to main content

uncurses/ansi/
truncate.rs

1//! Width-aware truncation and cutting for ANSI-decorated strings.
2//!
3//! ## Category
4//!
5//! This module shortens strings by terminal display columns while preserving
6//! escape sequences such as SGR resets and OSC hyperlinks. Escape bytes do not
7//! count toward width.
8//!
9//! ## Width conventions
10//!
11//! Width is computed by [`crate::ansi::text::tokenize`] using [`WidthMode`].
12//! Visible text is truncated only on token boundaries; escape sequences before,
13//! inside, or after the retained text are copied so terminal state remains
14//! attached to the result.
15//!
16//! ## Mode interaction
17//!
18//! Truncation does not emulate terminal modes. Mode-dependent sequence semantics
19//! are preserved as bytes but not interpreted.
20//!
21//! Sequence boundaries and widths come from [`crate::ansi::text`];
22//! which byte ends a control string, and when a byte in `0x80..=0x9F`
23//! is a C1 control rather than part of a character, are documented there.
24
25use super::text::{TokenKind, WidthMode, string_width, tokenize};
26
27#[inline]
28fn bs(b: &[u8]) -> &str {
29    // The tokenizer never splits a character: text tokens are whole grapheme
30    // clusters, and every sequence scanner steps a whole UTF-8 character at a
31    // time. Nothing enforced that, and when a scanner did split one - 0x9C is
32    // 8-bit ST and also a continuation byte, so an OSC title containing a
33    // check mark ended mid-character - the ill-formed bytes arrived here and
34    // this was undefined behaviour. Checked where checking is free.
35    debug_assert!(
36        std::str::from_utf8(b).is_ok(),
37        "token split a UTF-8 character: {b:?}"
38    );
39    // SAFETY: `b` is a token slice of `&str` input, taken on character
40    // boundaries, as asserted above.
41    unsafe { std::str::from_utf8_unchecked(b) }
42}
43
44/// Truncate `s` to at most `length` display columns, appending `tail` if truncation occurs.
45///
46/// ANSI escape sequences are preserved verbatim and do not count toward the width budget. When `length == 0`, this function returns an empty string.
47pub fn truncate(s: &str, length: usize, tail: &str) -> String {
48    truncate_mode(s, length, tail, WidthMode::default(), false)
49}
50
51/// Width-mode variant of [`truncate`].
52///
53/// `mode` and `eaw_wide` control grapheme width calculation. If the input already fits, it is returned unchanged; otherwise the visible prefix is shortened enough to fit `tail`, and trailing escape sequences are still copied.
54pub fn truncate_mode(
55    s: &str,
56    length: usize,
57    tail: &str,
58    mode: WidthMode,
59    eaw_wide: bool,
60) -> String {
61    if length == 0 {
62        return String::new();
63    }
64    if string_width(s.as_bytes(), mode, eaw_wide) <= length {
65        return s.to_string();
66    }
67    let tail_w = string_width(tail.as_bytes(), mode, eaw_wide);
68    let budget = length.saturating_sub(tail_w);
69
70    let mut out = String::new();
71    let mut used = 0usize;
72    let mut tail_inserted = false;
73    for tok in tokenize(s.as_bytes(), mode, eaw_wide) {
74        match tok.kind {
75            TokenKind::Escape => out.push_str(bs(tok.bytes)),
76            TokenKind::Control => {
77                if !tail_inserted {
78                    out.push_str(bs(tok.bytes));
79                }
80            }
81            TokenKind::Text => {
82                if tail_inserted {
83                    continue;
84                }
85                let w = usize::from(tok.width);
86                if used + w > budget {
87                    out.push_str(tail);
88                    tail_inserted = true;
89                    // Continue scanning to capture trailing escapes (e.g. SGR reset).
90                    continue;
91                }
92                out.push_str(bs(tok.bytes));
93                used += w;
94            }
95        }
96    }
97    if !tail_inserted {
98        out.push_str(tail);
99    }
100    out
101}
102
103/// Truncate `s` from the left until at most `length` display columns remain.
104///
105/// If truncation occurs, `prefix` is prepended after any leading escape sequences needed to preserve active terminal state.
106pub fn truncate_left(s: &str, length: usize, prefix: &str) -> String {
107    truncate_left_mode(s, length, prefix, WidthMode::default(), false)
108}
109
110/// Width-mode variant of [`truncate_left`].
111///
112/// `mode` and `eaw_wide` control grapheme width calculation. Escape sequences before the cut are retained before `prefix` so styling can carry into the visible suffix.
113pub fn truncate_left_mode(
114    s: &str,
115    length: usize,
116    prefix: &str,
117    mode: WidthMode,
118    eaw_wide: bool,
119) -> String {
120    let total = string_width(s.as_bytes(), mode, eaw_wide);
121    if total <= length {
122        return s.to_string();
123    }
124    let prefix_w = string_width(prefix.as_bytes(), mode, eaw_wide);
125    let drop = total.saturating_sub(length.saturating_sub(prefix_w));
126
127    let mut head_escapes = String::new();
128    let mut out = String::new();
129    let mut dropped = 0usize;
130    let mut dropping = true;
131    for tok in tokenize(s.as_bytes(), mode, eaw_wide) {
132        match tok.kind {
133            TokenKind::Escape => {
134                if dropping {
135                    head_escapes.push_str(bs(tok.bytes));
136                } else {
137                    out.push_str(bs(tok.bytes));
138                }
139            }
140            TokenKind::Control => {
141                if !dropping {
142                    out.push_str(bs(tok.bytes));
143                }
144            }
145            TokenKind::Text => {
146                let w = usize::from(tok.width);
147                if dropping {
148                    dropped += w;
149                    if dropped >= drop {
150                        dropping = false;
151                    }
152                } else {
153                    out.push_str(bs(tok.bytes));
154                }
155            }
156        }
157    }
158    let mut result = String::new();
159    // Preserve escapes encountered before the cut so style carries over.
160    result.push_str(&head_escapes);
161    result.push_str(prefix);
162    result.push_str(&out);
163    result
164}
165
166/// Remove `left` display columns from the start and `right` display columns from the end of `s`.
167///
168/// The result includes only whole grapheme clusters within the retained column interval.
169/// ANSI escape sequences are preserved and do not count toward either cut amount.
170pub fn cut(s: &str, left: usize, right: usize) -> String {
171    cut_mode(s, left, right, WidthMode::default(), false)
172}
173
174/// Width-mode variant of [`cut`].
175///
176/// `mode` and `eaw_wide` control grapheme width calculation. If the requested cuts leave no visible columns, the result is empty; otherwise trailing escape sequences are retained.
177pub fn cut_mode(s: &str, left: usize, right: usize, mode: WidthMode, eaw_wide: bool) -> String {
178    if left == 0 && right == 0 {
179        return s.to_string();
180    }
181    let total = string_width(s.as_bytes(), mode, eaw_wide);
182    if left >= total {
183        return String::new();
184    }
185    let keep_end = total.saturating_sub(right);
186    if keep_end <= left {
187        return String::new();
188    }
189    let mut out = String::new();
190    let mut col = 0usize;
191    for tok in tokenize(s.as_bytes(), mode, eaw_wide) {
192        match tok.kind {
193            TokenKind::Escape => out.push_str(bs(tok.bytes)),
194            TokenKind::Control => {
195                if col >= left && col < keep_end {
196                    out.push_str(bs(tok.bytes));
197                }
198            }
199            TokenKind::Text => {
200                let w = usize::from(tok.width);
201                if col >= left && col + w <= keep_end {
202                    out.push_str(bs(tok.bytes));
203                }
204                col += w;
205            }
206        }
207    }
208    out
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    #[test]
216    fn truncate_basic() {
217        assert_eq!(truncate("hello world", 5, ""), "hello");
218    }
219
220    #[test]
221    fn truncate_with_tail() {
222        assert_eq!(truncate("hello world", 8, "..."), "hello...");
223    }
224
225    #[test]
226    fn truncate_no_op() {
227        assert_eq!(truncate("hi", 5, "..."), "hi");
228    }
229
230    #[test]
231    fn truncate_preserves_ansi() {
232        let s = "\x1b[31mhello world\x1b[m";
233        let got = truncate(s, 5, "");
234        assert_eq!(got, "\x1b[31mhello\x1b[m");
235
236        let s = "\x1b[31ma世\x1b[m\u{301}b\n";
237        assert_eq!(truncate(s, 3, "…"), "\x1b[31ma…\x1b[m");
238    }
239
240    #[test]
241    fn truncate_wide_chars() {
242        assert_eq!(truncate("中文测试", 4, ""), "中文");
243        // Width-3 budget with 2-wide chars: only first fits.
244        assert_eq!(truncate("中文", 3, ""), "中");
245        assert_eq!(truncate("a世b", 3, "…"), "a…");
246        assert_eq!(truncate("a世b", 2, ""), "a");
247    }
248
249    #[test]
250    fn truncate_zero_length() {
251        assert_eq!(truncate("hello", 0, ""), "");
252        assert_eq!(truncate("hello", 0, "..."), "");
253    }
254
255    #[test]
256    fn truncate_left_basic() {
257        assert_eq!(truncate_left("hello world", 5, ""), "world");
258    }
259
260    #[test]
261    fn truncate_left_with_prefix() {
262        assert_eq!(truncate_left("hello world", 8, "..."), "...world");
263    }
264
265    #[test]
266    fn cut_basic() {
267        assert_eq!(cut("hello world", 2, 2), "llo wor");
268    }
269
270    #[test]
271    fn cut_wide_chars() {
272        for mode in [WidthMode::Wc, WidthMode::Grapheme] {
273            for (s, left, right, expected) in [
274                ("a世bc", 0, 3, "a"),
275                ("世ab", 1, 1, "a"),
276                ("a世bc", 1, 2, "世"),
277                ("世a", 1, 1, ""),
278            ] {
279                assert_eq!(
280                    cut_mode(s, left, right, mode, false),
281                    expected,
282                    "s={s:?}, left={left}, right={right}, mode={mode:?}"
283                );
284            }
285        }
286    }
287
288    #[test]
289    fn cut_controls_follow_original_columns() {
290        assert_eq!(cut("世a\n", 1, 0), "a");
291        assert_eq!(cut("世\na", 1, 0), "\na");
292    }
293
294    #[test]
295    fn cut_preserves_ansi() {
296        let s = "\x1b]8;;https://example.com\x1b\\\x1b[31ma世bc\x1b[m\x1b]8;;\x1b\\";
297        assert_eq!(
298            cut(s, 0, 3),
299            "\x1b]8;;https://example.com\x1b\\\x1b[31ma\x1b[m\x1b]8;;\x1b\\"
300        );
301    }
302
303    #[test]
304    fn cut_zero_zero_is_noop() {
305        assert_eq!(cut("hello", 0, 0), "hello");
306    }
307
308    #[test]
309    fn cut_too_wide() {
310        assert_eq!(cut("hi", 10, 0), "");
311    }
312
313    #[test]
314    fn truncate_preserves_osc_link() {
315        let s = "\x1b]8;;https://example.com\x1b\\link text\x1b]8;;\x1b\\";
316        let got = truncate(s, 4, "");
317        assert_eq!(got, "\x1b]8;;https://example.com\x1b\\link\x1b]8;;\x1b\\");
318
319        let s = "\x1b]8;;https://example.com\x1b\\a世b\x1b]8;;\x1b\\";
320        assert_eq!(
321            truncate(s, 3, "…"),
322            "\x1b]8;;https://example.com\x1b\\a…\x1b]8;;\x1b\\"
323        );
324    }
325}