Skip to main content

vtcode_commons/
formatting.rs

1//! Unified formatting utilities for UI and logging
2
3/// Format file size in human-readable form (KB, MB, GB, etc.)
4pub fn format_size(size: u64) -> String {
5    const KB: u64 = 1024;
6    const MB: u64 = KB * 1024;
7    const GB: u64 = MB * 1024;
8
9    if size >= GB {
10        format!("{:.1}GB", size as f64 / GB as f64)
11    } else if size >= MB {
12        format!("{:.1}MB", size as f64 / MB as f64)
13    } else if size >= KB {
14        format!("{:.1}KB", size as f64 / KB as f64)
15    } else {
16        format!("{size}B")
17    }
18}
19
20/// Indent a block of text with the given prefix
21pub fn indent_block(text: &str, indent: &str) -> String {
22    if indent.is_empty() || text.is_empty() {
23        return text.to_string();
24    }
25    let mut indented = String::with_capacity(text.len() + indent.len() * text.lines().count());
26    for (idx, line) in text.split('\n').enumerate() {
27        if idx > 0 {
28            indented.push('\n');
29        }
30        if !line.is_empty() {
31            indented.push_str(indent);
32        }
33        indented.push_str(line);
34    }
35    indented
36}
37
38/// Truncate text to a maximum length (in chars) with an optional ellipsis.
39pub fn truncate_text(text: &str, max_len: usize, ellipsis: &str) -> String {
40    if text.chars().count() <= max_len {
41        return text.to_string();
42    }
43
44    let mut truncated = text.chars().take(max_len).collect::<String>();
45    truncated.push_str(ellipsis);
46    truncated
47}
48
49/// Truncate text to `max_len` chars, reserving room for `ellipsis` so the
50/// returned string never exceeds `max_len` chars.
51///
52/// This differs from [`truncate_text`], which appends the ellipsis *after*
53/// taking `max_len` chars (yielding up to `max_len + ellipsis.len()` chars).
54/// Use this when the total rendered width must stay within a hard budget.
55///
56/// ```
57/// # use vtcode_commons::formatting::truncate_within;
58/// assert_eq!(truncate_within("hello world", 8, "..."), "hello...");
59/// assert_eq!(truncate_within("hi", 8, "..."), "hi");
60/// assert_eq!(truncate_within("hello", 3, "…"), "he…");
61/// ```
62pub fn truncate_within(text: &str, max_len: usize, ellipsis: &str) -> String {
63    if text.chars().count() <= max_len {
64        return text.to_string();
65    }
66    let keep = max_len.saturating_sub(ellipsis.chars().count());
67    let mut truncated = text.chars().take(keep).collect::<String>();
68    truncated.push_str(ellipsis);
69    truncated
70}
71
72/// Truncate `text` to at most `max_len` chars, keeping a head and a tail joined by
73/// a single `…` so context from both ends is preserved.
74///
75/// Control characters are replaced with spaces before truncation so the result is
76/// safe to render in a terminal/TUI. When the text already fits it is returned
77/// unchanged (after sanitization).
78///
79/// This is the canonical middle-truncation helper, shared so the same logic is not
80/// re-implemented per crate.
81pub fn truncate_middle(text: &str, max_len: usize) -> String {
82    if max_len == 0 {
83        return String::new();
84    }
85    let sanitized: String = text
86        .chars()
87        .map(|c| if matches!(c, '\n' | '\r' | '\t') { ' ' } else { c })
88        .collect();
89    let char_count = sanitized.chars().count();
90    if char_count <= max_len {
91        return sanitized;
92    }
93    if max_len <= 1 {
94        return "…".to_string();
95    }
96    let head_len = max_len / 2;
97    let tail_len = max_len.saturating_sub(head_len + 1);
98
99    let head: String = sanitized.chars().take(head_len).collect();
100    let mut result = String::with_capacity(head.len() + tail_len + 1);
101    result.push_str(&head);
102    result.push('…');
103    if tail_len > 0 {
104        let mut tail_rev: Vec<char> = sanitized.chars().rev().take(tail_len).collect();
105        tail_rev.reverse();
106        let tail: String = tail_rev.into_iter().collect();
107        result.push_str(&tail);
108    }
109    result
110}
111
112/// Truncate a file path in the middle, preferring to break at path separators.
113///
114/// Keeps a head and a tail joined by `…`, choosing break points at `/` so the most
115/// recognizable parts of the path (directories / file name) are preserved. This is
116/// the path-aware sibling of [`truncate_middle`], shared so the same display logic
117/// is not re-implemented per crate.
118pub fn truncate_path_middle(path: &str, max_len: usize) -> String {
119    if max_len == 0 {
120        return String::new();
121    }
122    let char_count = path.chars().count();
123    if char_count <= max_len {
124        return path.to_string();
125    }
126    if max_len <= 1 {
127        return "…".to_string();
128    }
129
130    // Try to find a good break point at a path separator
131    let head_budget = max_len / 2;
132    let tail_budget = max_len.saturating_sub(head_budget + 1);
133
134    // Find the last '/' in the head portion
135    // Collect chars directly into a String — `String: FromIterator<char>`,
136    // so the intermediate `Vec<char>` of the prior two-step collect is redundant.
137    let head_str: String = path.chars().take(head_budget).collect();
138    let head_break = head_str.rfind('/').unwrap_or(head_budget);
139
140    // Find the first '/' in the tail portion (from the end)
141    let tail_chars: Vec<char> = path.chars().rev().take(tail_budget).collect();
142    let tail_str: String = tail_chars.iter().rev().collect();
143    let tail_break_from_end = tail_str.find('/').map(|pos| tail_str.len() - pos).unwrap_or(tail_budget);
144
145    let head: String = path.chars().take(head_break).collect();
146    let tail: String = path
147        .chars()
148        .rev()
149        .take(tail_break_from_end)
150        .collect::<Vec<_>>()
151        .into_iter()
152        .rev()
153        .collect();
154
155    format!("{head}…{tail}")
156}
157
158/// Truncate `value` to `max_chars` chars by keeping a head and a tail joined by
159/// `marker`, preserving context from both ends of the text.
160///
161/// Returns `(text, was_truncated)`. When the budget is too small to fit the
162/// marker plus meaningful context, falls back to a head-only prefix with a
163/// ` [truncated]` suffix, respecting the `max_chars` budget.
164///
165/// ```
166/// # use vtcode_commons::formatting::head_tail_truncate;
167/// let (out, truncated) = head_tail_truncate("short", 64, " ... ");
168/// assert_eq!(out, "short");
169/// assert!(!truncated);
170/// ```
171pub fn head_tail_truncate(value: &str, max_chars: usize, marker: &str) -> (String, bool) {
172    const SUFFIX: &str = " [truncated]";
173
174    let total_chars = value.chars().count();
175    if total_chars <= max_chars {
176        return (value.to_string(), false);
177    }
178
179    let marker_chars = marker.chars().count();
180    if max_chars <= marker_chars + 16 {
181        let suffix_len = SUFFIX.chars().count();
182        let truncated = if max_chars > suffix_len {
183            let available = max_chars - suffix_len;
184            let mut result = value.chars().take(available).collect::<String>();
185            result.push_str(SUFFIX);
186            result
187        } else {
188            value.chars().take(max_chars).collect::<String>()
189        };
190        return (truncated, true);
191    }
192
193    let available = max_chars.saturating_sub(marker_chars);
194    let head_chars = (available * 2) / 3;
195    let tail_chars = available.saturating_sub(head_chars);
196    let head = value.chars().take(head_chars).collect::<String>();
197    let tail = value.chars().skip(total_chars.saturating_sub(tail_chars)).collect::<String>();
198    let mut truncated = String::with_capacity(max_chars + 20);
199    truncated.push_str(&head);
200    truncated.push_str(marker);
201    truncated.push_str(&tail);
202    (truncated, true)
203}
204
205/// Word-wrap `text` into lines, allowing `first_width` chars on the first line
206/// and `continuation_width` chars on subsequent lines. Wrapping prefers
207/// whitespace boundaries and is UTF-8 safe (widths count chars, not bytes).
208///
209/// Returns an empty vec for blank input. Words longer than the width are split
210/// at the width boundary rather than overflowing.
211///
212/// ```
213/// # use vtcode_commons::formatting::wrap_text_words;
214/// let lines = wrap_text_words("the quick brown fox", 9, 9);
215/// assert_eq!(lines, vec!["the quick", "brown fox"]);
216/// assert!(wrap_text_words("   ", 5, 5).is_empty());
217/// ```
218pub fn wrap_text_words(text: &str, first_width: usize, continuation_width: usize) -> Vec<String> {
219    let trimmed = text.trim();
220    if trimmed.is_empty() {
221        return Vec::new();
222    }
223
224    let mut result = Vec::new();
225    let mut remaining = trimmed;
226    let mut width = first_width.max(1);
227
228    while remaining.chars().count() > width {
229        let split = split_at_word_boundary(remaining, width);
230        let (head, tail) = remaining.split_at(split);
231        let head = head.trim();
232        if head.is_empty() {
233            break;
234        }
235        result.push(head.to_string());
236        remaining = tail.trim_start();
237        if remaining.is_empty() {
238            break;
239        }
240        width = continuation_width.max(1);
241    }
242
243    if !remaining.is_empty() {
244        result.push(remaining.to_string());
245    }
246    result
247}
248
249fn split_at_word_boundary(input: &str, width: usize) -> usize {
250    let mut last_space: Option<usize> = None;
251    for (seen, (idx, ch)) in input.char_indices().enumerate() {
252        if seen > width {
253            break;
254        }
255        if ch.is_whitespace() {
256            last_space = Some(idx);
257        }
258    }
259    match last_space {
260        Some(pos) => pos,
261        None => byte_index_for_char_count(input, width),
262    }
263}
264
265fn byte_index_for_char_count(input: &str, chars: usize) -> usize {
266    if chars == 0 {
267        return 0;
268    }
269    let mut seen = 0usize;
270    for (idx, ch) in input.char_indices() {
271        seen += 1;
272        if seen == chars {
273            return idx + ch.len_utf8();
274        }
275    }
276    input.len()
277}
278
279/// Truncate a string so that the retained prefix is at most `max_bytes` bytes,
280/// rounded down to the nearest UTF-8 char boundary.  Returns the truncated
281/// prefix with `suffix` appended, or the original string when it already fits.
282pub fn truncate_byte_budget(text: &str, max_bytes: usize, suffix: &str) -> String {
283    if text.len() <= max_bytes {
284        return text.to_string();
285    }
286    let mut end = max_bytes.min(text.len());
287    while end > 0 && !text.is_char_boundary(end) {
288        end -= 1;
289    }
290    format!("{}{suffix}", &text[..end])
291}
292
293/// Collapse consecutive whitespace into single spaces, trimming leading/trailing.
294///
295/// ```
296/// # use vtcode_commons::formatting::collapse_whitespace;
297/// assert_eq!(collapse_whitespace("  hello   world  "), "hello world");
298/// assert_eq!(collapse_whitespace(""), "");
299/// ```
300#[inline]
301pub fn collapse_whitespace(text: &str) -> String {
302    let mut result = String::with_capacity(text.len());
303    let mut pending_space = false;
304    for ch in text.chars() {
305        if ch.is_whitespace() {
306            pending_space = true;
307        } else {
308            if pending_space && !result.is_empty() {
309                result.push(' ');
310            }
311            result.push(ch);
312            pending_space = false;
313        }
314    }
315    result
316}
317
318/// Clean reasoning text by trimming trailing whitespace on each line and
319/// removing blank lines.
320///
321/// ```
322/// # use vtcode_commons::formatting::clean_reasoning_text;
323/// assert_eq!(clean_reasoning_text("line1\n\n\nline2\n"), "line1\nline2");
324/// assert_eq!(clean_reasoning_text(""), "");
325/// ```
326pub fn clean_reasoning_text(text: &str) -> String {
327    text.lines()
328        .map(str::trim_end)
329        .filter(|line| !line.trim().is_empty())
330        .collect::<Vec<_>>()
331        .join("\n")
332}
333
334/// Compact reasoning text for on-screen display.
335///
336/// Unlike [`clean_reasoning_text`], which removes *all* blank lines, this
337/// collapses runs of two or more blank/whitespace-only lines into a single
338/// blank line so paragraph structure is preserved while "blank-line spam"
339/// from the model is removed. Leading/trailing whitespace on every line is
340/// trimmed and leading/trailing blank lines of the whole block are dropped.
341///
342/// ```
343/// # use vtcode_commons::formatting::compact_reasoning_text;
344/// assert_eq!(compact_reasoning_text("line1\n\n\n\nline2\n"), "line1\n\nline2");
345/// assert_eq!(compact_reasoning_text("  a  \n\n\n  b  \n"), "a\n\nb");
346/// assert_eq!(compact_reasoning_text("\n\n\n"), "");
347/// assert_eq!(compact_reasoning_text(""), "");
348/// ```
349pub fn compact_reasoning_text(text: &str) -> String {
350    let mut out: Vec<&str> = Vec::with_capacity(text.lines().count());
351    let mut prev_blank = false;
352    for line in text.lines() {
353        let trimmed = line.trim();
354        let is_blank = trimmed.is_empty();
355        if is_blank {
356            if prev_blank {
357                continue;
358            }
359            out.push("");
360            prev_blank = true;
361        } else {
362            out.push(trimmed);
363            prev_blank = false;
364        }
365    }
366    while out.first().is_some_and(|l| l.trim().is_empty()) {
367        out.remove(0);
368    }
369    while out.last().is_some_and(|l| l.trim().is_empty()) {
370        out.pop();
371    }
372    out.join("\n")
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    #[test]
380    fn truncate_byte_budget_ascii() {
381        assert_eq!(truncate_byte_budget("hello world", 5, "..."), "hello...");
382        assert_eq!(truncate_byte_budget("hi", 10, "..."), "hi");
383    }
384
385    #[test]
386    fn truncate_byte_budget_cjk_no_panic() {
387        // 'こ' = 3 bytes, 'ん' = 3 bytes → "こんにちは" = 15 bytes
388        let jp = "こんにちは";
389        // Cutting at 5 bytes lands inside 'ん' (bytes 3..6); must round down to 3.
390        assert_eq!(truncate_byte_budget(jp, 5, "…"), "こ…");
391        // Cutting at 6 lands on boundary
392        assert_eq!(truncate_byte_budget(jp, 6, "…"), "こん…");
393    }
394
395    #[test]
396    fn truncate_byte_budget_mixed_ascii_cjk() {
397        let mixed = "AB日本語CD";
398        // A=1, B=1, 日=3, 本=3, 語=3, C=1, D=1 → 13 bytes total
399        assert_eq!(truncate_byte_budget(mixed, 4, ".."), "AB.."); // mid-日 rounds to 2
400        assert_eq!(truncate_byte_budget(mixed, 5, ".."), "AB日.."); // 2+3=5 exact
401    }
402
403    #[test]
404    fn truncate_byte_budget_emoji() {
405        let emoji = "👋🌍"; // 4 bytes each = 8 bytes
406        assert_eq!(truncate_byte_budget(emoji, 5, "!"), "👋!");
407    }
408
409    #[test]
410    fn truncate_byte_budget_zero() {
411        assert_eq!(truncate_byte_budget("abc", 0, "..."), "...");
412    }
413
414    #[test]
415    fn compact_reasoning_text_collapses_blank_runs() {
416        assert_eq!(compact_reasoning_text("line1\n\n\n\nline2\n"), "line1\n\nline2");
417        assert_eq!(compact_reasoning_text("a\n\n\n\n\n\nb"), "a\n\nb");
418    }
419
420    #[test]
421    fn compact_reasoning_text_preserves_single_paragraph_breaks() {
422        assert_eq!(compact_reasoning_text("para one\n\npara two\n"), "para one\n\npara two");
423    }
424
425    #[test]
426    fn compact_reasoning_text_trims_trailing_whitespace() {
427        assert_eq!(compact_reasoning_text("  a  \n\n\n  b  \n"), "a\n\nb");
428    }
429
430    #[test]
431    fn compact_reasoning_text_strips_leading_trailing_blanks() {
432        assert_eq!(compact_reasoning_text("\n\n\nmid\n\n\n"), "mid");
433        assert_eq!(compact_reasoning_text("\n\n\n"), "");
434        assert_eq!(compact_reasoning_text(""), "");
435    }
436
437    #[test]
438    fn wrap_text_words_basic_and_continuation_width() {
439        assert_eq!(wrap_text_words("the quick brown fox", 9, 9), vec!["the quick", "brown fox"]);
440        // First line wider than continuation lines.
441        assert_eq!(wrap_text_words("alpha beta gamma delta", 11, 5), vec!["alpha beta", "gamma", "delta"]);
442    }
443
444    #[test]
445    fn wrap_text_words_blank_and_unicode() {
446        assert!(wrap_text_words("   ", 5, 5).is_empty());
447        // Must not panic on multi-byte chars and counts chars, not bytes.
448        let wrapped = wrap_text_words("あいう えお かきく", 3, 3);
449        assert_eq!(wrapped, vec!["あいう", "えお", "かきく"]);
450    }
451
452    #[test]
453    fn truncate_within_reserves_ellipsis_budget() {
454        // Matches former runner::orchestration::truncate_chars behavior.
455        assert_eq!(truncate_within("hello world", 8, "..."), "hello...");
456        assert_eq!(truncate_within("hi", 8, "..."), "hi");
457        // Single-char ellipsis reserves exactly one char (former snapshots /
458        // session_archive behavior).
459        assert_eq!(truncate_within("abcdef", 4, "…"), "abc…");
460    }
461
462    #[test]
463    fn truncate_within_counts_chars() {
464        let jp = "あいうえお"; // 5 chars
465        assert_eq!(truncate_within(jp, 5, "…"), jp);
466        assert_eq!(truncate_within(jp, 3, "…"), "あい…");
467    }
468
469    #[test]
470    fn head_tail_truncate_keeps_both_ends() {
471        let value = "0123456789".repeat(10); // 100 chars
472        let (out, truncated) = head_tail_truncate(&value, 40, " ... [truncated] ... ");
473        assert!(truncated);
474        assert!(out.chars().count() <= 40);
475        assert!(out.starts_with("012"));
476        assert!(out.contains("[truncated]"));
477        assert!(out.ends_with('9'));
478    }
479
480    #[test]
481    fn head_tail_truncate_passes_through_when_short() {
482        let (out, truncated) = head_tail_truncate("short", 64, " ... ");
483        assert_eq!(out, "short");
484        assert!(!truncated);
485    }
486
487    #[test]
488    fn head_tail_truncate_small_budget_falls_back_to_prefix() {
489        let marker = " ... [truncated] ... ";
490        // max_chars <= marker_chars + 16 triggers the prefix fallback.
491        // When max_chars (5) <= suffix_len (12), return just the prefix without suffix.
492        let (out, truncated) = head_tail_truncate("abcdefghij", 5, marker);
493        assert!(truncated);
494        assert_eq!(out, "abcde");
495
496        // When max_chars allows room for suffix, include it in the fallback branch.
497        // Use max_chars=17 which is <= 21+16=37 (triggers fallback).
498        let long_text = "abcdefghijklmnopqrstuvwxyz";
499        let (out2, truncated2) = head_tail_truncate(long_text, 17, marker);
500        assert!(truncated2);
501        assert_eq!(out2, "abcde [truncated]");
502        assert_eq!(out2.chars().count(), 17);
503    }
504
505    #[test]
506    fn truncate_text_counts_chars_not_bytes() {
507        let jp = "あいうえお"; // 5 chars, 15 bytes
508        assert_eq!(truncate_text(jp, 3, "…"), "あいう…");
509        assert_eq!(truncate_text(jp, 5, "…"), "あいうえお");
510    }
511
512    #[test]
513    fn truncate_middle_keeps_both_ends() {
514        assert_eq!(truncate_middle("short", 80), "short");
515        assert_eq!(truncate_middle("abcdefghij", 5), "ab…ij");
516        assert_eq!(truncate_middle("a b c", 80), "a b c");
517        // Zero/one-char budgets.
518        assert_eq!(truncate_middle("abc", 0), "");
519        assert_eq!(truncate_middle("abc", 1), "…");
520        // Control characters are sanitized to spaces before truncating.
521        assert_eq!(truncate_middle("a\nb\tc", 80), "a b c");
522    }
523
524    #[test]
525    fn truncate_path_middle_breaks_at_separator() {
526        assert_eq!(truncate_path_middle("src/lib.rs", 80), "src/lib.rs");
527        assert_eq!(truncate_path_middle("foo/bar/baz/qux", 12), "foo…/qux");
528        assert_eq!(truncate_path_middle("abc", 0), "");
529    }
530}