Skip to main content

vtcode_commons/
preview.rs

1#![expect(
2    clippy::indexing_slicing,
3    clippy::string_slice,
4    reason = "Preview counts and UTF-8 offsets are computed from source lengths and boundary helpers."
5)]
6
7//! Shared preview formatting helpers.
8
9use crate::display_width::char_display_width_or;
10pub use crate::display_width::display_width;
11
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub struct HeadTailPreview<'a, T> {
14    pub head: &'a [T],
15    pub tail: &'a [T],
16    pub hidden_count: usize,
17    total: usize,
18}
19
20#[derive(Clone, Debug, Eq, PartialEq)]
21pub struct TextLineExcerpt<'a> {
22    pub head: Vec<&'a str>,
23    pub tail: Vec<&'a str>,
24    pub hidden_count: usize,
25    pub total: usize,
26}
27
28pub fn truncate_to_display_width(text: &str, max_width: usize) -> &str {
29    if max_width == 0 {
30        return "";
31    }
32    if display_width(text) <= max_width {
33        return text;
34    }
35
36    let mut consumed_width = 0usize;
37    for (idx, ch) in text.char_indices() {
38        let char_width = char_display_width_or(ch, 0);
39        if consumed_width + char_width > max_width {
40            return &text[..idx];
41        }
42        consumed_width += char_width;
43    }
44
45    text
46}
47
48pub fn truncate_with_ellipsis(text: &str, max_width: usize, ellipsis: &str) -> String {
49    if max_width == 0 {
50        return String::new();
51    }
52    if display_width(text) <= max_width {
53        return text.to_string();
54    }
55
56    let ellipsis_width = display_width(ellipsis);
57    if ellipsis_width >= max_width {
58        return truncate_to_display_width(ellipsis, max_width).to_string();
59    }
60
61    let truncated = truncate_to_display_width(text, max_width - ellipsis_width);
62    format!("{truncated}{ellipsis}")
63}
64
65pub fn pad_to_display_width(text: &str, width: usize, pad_char: char) -> String {
66    let current = display_width(text);
67    if current >= width {
68        return text.to_string();
69    }
70
71    let padding = pad_char.to_string().repeat(width - current);
72    format!("{text}{padding}")
73}
74
75pub fn suffix_for_display_width(value: &str, max_width: usize) -> &str {
76    if display_width(value) <= max_width {
77        return value;
78    }
79    if max_width == 0 {
80        return "";
81    }
82
83    let mut consumed_width = 0usize;
84    let mut start_idx = value.len();
85    for (idx, ch) in value.char_indices().rev() {
86        let char_width = char_display_width_or(ch, 0);
87        if consumed_width + char_width > max_width {
88            break;
89        }
90        consumed_width += char_width;
91        start_idx = idx;
92    }
93
94    &value[start_idx..]
95}
96
97pub fn format_hidden_lines_summary(hidden: usize) -> String {
98    if hidden == 1 {
99        "… +1 line".to_string()
100    } else {
101        format!("… +{hidden} lines")
102    }
103}
104
105fn split_head_tail_preview<'a, T>(items: &'a [T], head: usize, tail: usize) -> HeadTailPreview<'a, T> {
106    let total = items.len();
107    if total <= head.saturating_add(tail) {
108        return HeadTailPreview {
109            head: items,
110            tail: &items[total..],
111            hidden_count: 0,
112            total,
113        };
114    }
115
116    let head_count = head.min(total);
117    let tail_count = tail.min(total.saturating_sub(head_count));
118    let hidden_count = total.saturating_sub(head_count + tail_count);
119
120    HeadTailPreview {
121        head: &items[..head_count],
122        tail: &items[total - tail_count..],
123        hidden_count,
124        total,
125    }
126}
127
128pub fn split_head_tail_preview_with_limit<'a, T>(
129    items: &'a [T],
130    limit: usize,
131    preferred_head: usize,
132) -> HeadTailPreview<'a, T> {
133    if limit == 0 {
134        return HeadTailPreview {
135            head: &items[..0],
136            tail: &items[..0],
137            hidden_count: items.len(),
138            total: items.len(),
139        };
140    }
141
142    if items.len() <= limit {
143        return HeadTailPreview {
144            head: items,
145            tail: &items[items.len()..],
146            hidden_count: 0,
147            total: items.len(),
148        };
149    }
150
151    let (head, tail) = summary_window(limit, preferred_head);
152    split_head_tail_preview(items, head, tail)
153}
154
155pub fn summary_window(limit: usize, preferred_head: usize) -> (usize, usize) {
156    if limit <= 2 {
157        return (0, limit);
158    }
159
160    let head = preferred_head.min((limit - 1) / 2).max(1);
161    let tail = limit.saturating_sub(head + 1).max(1);
162    (head, tail)
163}
164
165pub fn excerpt_text_lines<'a>(text: &'a str, head: usize, tail: usize) -> TextLineExcerpt<'a> {
166    let lines: Vec<&str> = text.lines().collect();
167    let total = lines.len();
168    if total <= head.saturating_add(tail) {
169        return TextLineExcerpt {
170            head: lines,
171            tail: Vec::new(),
172            hidden_count: 0,
173            total,
174        };
175    }
176
177    let head_count = head.min(total);
178    let tail_count = tail.min(total.saturating_sub(head_count));
179    let hidden_count = total.saturating_sub(head_count + tail_count);
180
181    TextLineExcerpt {
182        head: lines[..head_count].to_vec(),
183        tail: lines[total - tail_count..].to_vec(),
184        hidden_count,
185        total,
186    }
187}
188
189pub fn excerpt_text_lines_with_limit<'a>(text: &'a str, limit: usize, preferred_head: usize) -> TextLineExcerpt<'a> {
190    let lines: Vec<&str> = text.lines().collect();
191    let preview = split_head_tail_preview_with_limit(lines.as_slice(), limit, preferred_head);
192
193    TextLineExcerpt {
194        head: preview.head.to_vec(),
195        tail: preview.tail.to_vec(),
196        hidden_count: preview.hidden_count,
197        total: preview.total,
198    }
199}
200
201fn format_hidden_bytes_summary(hidden: usize) -> String {
202    format!("… [{hidden} bytes omitted] …")
203}
204
205pub fn condense_text_bytes(content: &str, head_bytes: usize, tail_bytes: usize) -> String {
206    let byte_len = content.len();
207    let max_inline = head_bytes + tail_bytes;
208    if byte_len <= max_inline {
209        return content.to_string();
210    }
211
212    let head_end = content.floor_char_boundary(head_bytes);
213    let tail_start_raw = byte_len.saturating_sub(tail_bytes);
214    let tail_start = content.ceil_char_boundary(tail_start_raw);
215
216    let omitted = byte_len.saturating_sub(head_end).saturating_sub(byte_len - tail_start);
217
218    format!("{}\n\n{}\n\n{}", &content[..head_end], format_hidden_bytes_summary(omitted), &content[tail_start..])
219}
220
221/// Bound model-facing error echoes of text the caller already sent
222/// (old_str, patch context, snippets). Threshold is deliberately high:
223/// typical edit mismatches are mid-string whitespace/indent issues, so most
224/// real payloads must stay intact. Only pathological multi-KB pastes are
225/// reduced to a head/tail.
226pub fn condense_error_echo(text: &str) -> String {
227    if text.len() > 2_000 {
228        condense_text_bytes(text, 800, 800)
229    } else {
230        text.to_string()
231    }
232}
233
234pub fn tail_preview_text(content: &str, tail_bytes: usize, max_lines: usize) -> String {
235    if content.is_empty() {
236        return String::new();
237    }
238
239    let tail_start = content.ceil_char_boundary(content.len().saturating_sub(tail_bytes));
240    let tail_slice = &content[tail_start..];
241
242    let mut line_start = 0usize;
243    if max_lines > 0 {
244        let mut seen = 0usize;
245        for (idx, b) in tail_slice.as_bytes().iter().enumerate().rev() {
246            if *b == b'\n' {
247                seen += 1;
248                if seen >= max_lines {
249                    line_start = idx.saturating_add(1);
250                    break;
251                }
252            }
253        }
254    }
255
256    let preview = &tail_slice[line_start..];
257    let omitted = tail_start.saturating_add(line_start);
258    if omitted == 0 {
259        return preview.to_string();
260    }
261
262    format!("{}\n{}", format_hidden_bytes_summary(omitted), preview)
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268
269    #[test]
270    fn truncate_to_display_width_respects_wide_chars() {
271        let value = "表表表";
272        assert_eq!(truncate_to_display_width(value, 5), "表表");
273    }
274
275    #[test]
276    fn truncate_with_ellipsis_respects_width_budget() {
277        assert_eq!(truncate_with_ellipsis("abcdef", 4, "…"), "abc…");
278    }
279
280    #[test]
281    fn pad_to_display_width_handles_wide_chars() {
282        let padded = pad_to_display_width("表", 4, ' ');
283        assert_eq!(display_width(padded.as_str()), 4);
284    }
285
286    #[test]
287    fn preview_padding_credits_halfwidth_sound_marks() {
288        // The shared helper must agree with the TUI: `ガ` renders in two
289        // cells, so a width-3 budget leaves exactly one space, not two.
290        assert_eq!(pad_to_display_width("ガ", 3, ' '), "ガ ");
291        assert_eq!(truncate_to_display_width("aガ", 2), "aカ");
292    }
293
294    #[test]
295    fn preview_width_math_follows_ambiguous_width_verdict() {
296        // nextest isolates this process, so the one-time verdict override
297        // cannot affect other tests. Truncation used to strip two ambiguous
298        // glyphs here because it bypassed the TUI's CJK width table.
299        crate::terminal_capabilities::set_ambiguous_width(crate::ui_protocol::AmbiguousWidthMode::Wide);
300        assert_eq!(display_width("│││"), 6);
301        assert_eq!(truncate_to_display_width("│││", 2), "│");
302        assert_eq!(pad_to_display_width("│", 3, ' '), "│ ");
303    }
304
305    #[test]
306    fn suffix_for_display_width_preserves_tail() {
307        assert_eq!(suffix_for_display_width("hello/world.rs", 8), "world.rs");
308    }
309
310    #[test]
311    fn split_head_tail_preview_preserves_hidden_count() {
312        let items = [1, 2, 3, 4, 5, 6, 7];
313        let preview = split_head_tail_preview(&items, 2, 2);
314        assert_eq!(preview.head, &[1, 2]);
315        assert_eq!(preview.tail, &[6, 7]);
316        assert_eq!(preview.hidden_count, 3);
317        assert_eq!(preview.total, 7);
318    }
319
320    #[test]
321    fn split_head_tail_preview_keeps_short_input_intact() {
322        let items = [1, 2, 3];
323        let preview = split_head_tail_preview(&items, 2, 2);
324        assert_eq!(preview.head, &[1, 2, 3]);
325        assert!(preview.tail.is_empty());
326        assert_eq!(preview.hidden_count, 0);
327    }
328
329    #[test]
330    fn split_head_tail_preview_with_limit_preserves_total_and_gap() {
331        let items = [1, 2, 3, 4, 5, 6, 7];
332        let preview = split_head_tail_preview_with_limit(&items, 6, 3);
333        assert_eq!(preview.head, &[1, 2]);
334        assert_eq!(preview.tail, &[5, 6, 7]);
335        assert_eq!(preview.hidden_count, 2);
336        assert_eq!(preview.total, 7);
337    }
338
339    #[test]
340    fn summary_window_reserves_gap_row() {
341        assert_eq!(summary_window(6, 3), (2, 3));
342        assert_eq!(summary_window(2, 3), (0, 2));
343    }
344
345    #[test]
346    fn hidden_lines_summary_matches_existing_copy() {
347        assert_eq!(format_hidden_lines_summary(1), "… +1 line");
348        assert_eq!(format_hidden_lines_summary(4), "… +4 lines");
349    }
350
351    #[test]
352    fn excerpt_text_lines_builds_head_tail_vectors() {
353        let preview = excerpt_text_lines("l1\nl2\nl3\nl4\nl5\nl6", 2, 2);
354        assert_eq!(preview.head, vec!["l1", "l2"]);
355        assert_eq!(preview.tail, vec!["l5", "l6"]);
356        assert_eq!(preview.hidden_count, 2);
357        assert_eq!(preview.total, 6);
358    }
359
360    #[test]
361    fn condense_text_bytes_respects_utf8_boundaries() {
362        let mut content = "a".repeat(7);
363        content.push('é');
364        content.push_str("bbbbbbbb");
365
366        let preview = condense_text_bytes(&content, 8, 4);
367        assert!(preview.contains("bytes omitted"));
368        assert!(preview.is_char_boundary(0));
369    }
370
371    #[test]
372    fn tail_preview_text_keeps_last_lines_only() {
373        let input = (0..20).map(|index| format!("line-{index}")).collect::<Vec<_>>().join("\n");
374
375        let preview = tail_preview_text(&input, 40, 3);
376        assert!(preview.contains("bytes omitted"));
377        assert!(preview.contains("line-19"));
378        assert!(!preview.contains("line-1\n"));
379    }
380}