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    let head_chars: Vec<char> = path.chars().take(head_budget).collect();
136    let head_str: String = head_chars.iter().collect();
137    let head_break = head_str.rfind('/').unwrap_or(head_budget);
138
139    // Find the first '/' in the tail portion (from the end)
140    let tail_chars: Vec<char> = path.chars().rev().take(tail_budget).collect();
141    let tail_str: String = tail_chars.iter().rev().collect();
142    let tail_break_from_end = tail_str.find('/').map(|pos| tail_str.len() - pos).unwrap_or(tail_budget);
143
144    let head: String = path.chars().take(head_break).collect();
145    let tail: String = path
146        .chars()
147        .rev()
148        .take(tail_break_from_end)
149        .collect::<Vec<_>>()
150        .into_iter()
151        .rev()
152        .collect();
153
154    format!("{head}…{tail}")
155}
156
157/// Truncate `value` to `max_chars` chars by keeping a head and a tail joined by
158/// `marker`, preserving context from both ends of the text.
159///
160/// Returns `(text, was_truncated)`. When the budget is too small to fit the
161/// marker plus meaningful context, falls back to a head-only prefix with a
162/// ` [truncated]` suffix, respecting the `max_chars` budget.
163///
164/// ```
165/// # use vtcode_commons::formatting::head_tail_truncate;
166/// let (out, truncated) = head_tail_truncate("short", 64, " ... ");
167/// assert_eq!(out, "short");
168/// assert!(!truncated);
169/// ```
170pub fn head_tail_truncate(value: &str, max_chars: usize, marker: &str) -> (String, bool) {
171    const SUFFIX: &str = " [truncated]";
172
173    let total_chars = value.chars().count();
174    if total_chars <= max_chars {
175        return (value.to_string(), false);
176    }
177
178    let marker_chars = marker.chars().count();
179    if max_chars <= marker_chars + 16 {
180        let suffix_len = SUFFIX.chars().count();
181        let truncated = if max_chars > suffix_len {
182            let available = max_chars - suffix_len;
183            let mut result = value.chars().take(available).collect::<String>();
184            result.push_str(SUFFIX);
185            result
186        } else {
187            value.chars().take(max_chars).collect::<String>()
188        };
189        return (truncated, true);
190    }
191
192    let available = max_chars.saturating_sub(marker_chars);
193    let head_chars = (available * 2) / 3;
194    let tail_chars = available.saturating_sub(head_chars);
195    let head = value.chars().take(head_chars).collect::<String>();
196    let tail = value.chars().skip(total_chars.saturating_sub(tail_chars)).collect::<String>();
197    let mut truncated = String::with_capacity(max_chars + 20);
198    truncated.push_str(&head);
199    truncated.push_str(marker);
200    truncated.push_str(&tail);
201    (truncated, true)
202}
203
204/// Word-wrap `text` into lines, allowing `first_width` chars on the first line
205/// and `continuation_width` chars on subsequent lines. Wrapping prefers
206/// whitespace boundaries and is UTF-8 safe (widths count chars, not bytes).
207///
208/// Returns an empty vec for blank input. Words longer than the width are split
209/// at the width boundary rather than overflowing.
210///
211/// ```
212/// # use vtcode_commons::formatting::wrap_text_words;
213/// let lines = wrap_text_words("the quick brown fox", 9, 9);
214/// assert_eq!(lines, vec!["the quick", "brown fox"]);
215/// assert!(wrap_text_words("   ", 5, 5).is_empty());
216/// ```
217pub fn wrap_text_words(text: &str, first_width: usize, continuation_width: usize) -> Vec<String> {
218    let trimmed = text.trim();
219    if trimmed.is_empty() {
220        return Vec::new();
221    }
222
223    let mut result = Vec::new();
224    let mut remaining = trimmed;
225    let mut width = first_width.max(1);
226
227    while remaining.chars().count() > width {
228        let split = split_at_word_boundary(remaining, width);
229        let (head, tail) = remaining.split_at(split);
230        let head = head.trim();
231        if head.is_empty() {
232            break;
233        }
234        result.push(head.to_string());
235        remaining = tail.trim_start();
236        if remaining.is_empty() {
237            break;
238        }
239        width = continuation_width.max(1);
240    }
241
242    if !remaining.is_empty() {
243        result.push(remaining.to_string());
244    }
245    result
246}
247
248fn split_at_word_boundary(input: &str, width: usize) -> usize {
249    let mut last_space: Option<usize> = None;
250    for (seen, (idx, ch)) in input.char_indices().enumerate() {
251        if seen > width {
252            break;
253        }
254        if ch.is_whitespace() {
255            last_space = Some(idx);
256        }
257    }
258    match last_space {
259        Some(pos) => pos,
260        None => byte_index_for_char_count(input, width),
261    }
262}
263
264fn byte_index_for_char_count(input: &str, chars: usize) -> usize {
265    if chars == 0 {
266        return 0;
267    }
268    let mut seen = 0usize;
269    for (idx, ch) in input.char_indices() {
270        seen += 1;
271        if seen == chars {
272            return idx + ch.len_utf8();
273        }
274    }
275    input.len()
276}
277
278/// Truncate a string so that the retained prefix is at most `max_bytes` bytes,
279/// rounded down to the nearest UTF-8 char boundary.  Returns the truncated
280/// prefix with `suffix` appended, or the original string when it already fits.
281pub fn truncate_byte_budget(text: &str, max_bytes: usize, suffix: &str) -> String {
282    if text.len() <= max_bytes {
283        return text.to_string();
284    }
285    let mut end = max_bytes.min(text.len());
286    while end > 0 && !text.is_char_boundary(end) {
287        end -= 1;
288    }
289    format!("{}{suffix}", &text[..end])
290}
291
292/// Collapse consecutive whitespace into single spaces, trimming leading/trailing.
293///
294/// ```
295/// # use vtcode_commons::formatting::collapse_whitespace;
296/// assert_eq!(collapse_whitespace("  hello   world  "), "hello world");
297/// assert_eq!(collapse_whitespace(""), "");
298/// ```
299#[inline]
300pub fn collapse_whitespace(text: &str) -> String {
301    let mut result = String::with_capacity(text.len());
302    let mut pending_space = false;
303    for ch in text.chars() {
304        if ch.is_whitespace() {
305            pending_space = true;
306        } else {
307            if pending_space && !result.is_empty() {
308                result.push(' ');
309            }
310            result.push(ch);
311            pending_space = false;
312        }
313    }
314    result
315}
316
317/// Clean reasoning text by trimming trailing whitespace on each line and
318/// removing blank lines.
319///
320/// ```
321/// # use vtcode_commons::formatting::clean_reasoning_text;
322/// assert_eq!(clean_reasoning_text("line1\n\n\nline2\n"), "line1\nline2");
323/// assert_eq!(clean_reasoning_text(""), "");
324/// ```
325pub fn clean_reasoning_text(text: &str) -> String {
326    text.lines()
327        .map(str::trim_end)
328        .filter(|line| !line.trim().is_empty())
329        .collect::<Vec<_>>()
330        .join("\n")
331}
332
333/// Compact reasoning text for on-screen display.
334///
335/// Unlike [`clean_reasoning_text`], which removes *all* blank lines, this
336/// collapses runs of two or more blank/whitespace-only lines into a single
337/// blank line so paragraph structure is preserved while "blank-line spam"
338/// from the model is removed. Leading/trailing whitespace on every line is
339/// trimmed and leading/trailing blank lines of the whole block are dropped.
340///
341/// ```
342/// # use vtcode_commons::formatting::compact_reasoning_text;
343/// assert_eq!(compact_reasoning_text("line1\n\n\n\nline2\n"), "line1\n\nline2");
344/// assert_eq!(compact_reasoning_text("  a  \n\n\n  b  \n"), "a\n\nb");
345/// assert_eq!(compact_reasoning_text("\n\n\n"), "");
346/// assert_eq!(compact_reasoning_text(""), "");
347/// ```
348pub fn compact_reasoning_text(text: &str) -> String {
349    let mut out: Vec<&str> = Vec::with_capacity(text.lines().count());
350    let mut prev_blank = false;
351    for line in text.lines() {
352        let trimmed = line.trim();
353        let is_blank = trimmed.is_empty();
354        if is_blank {
355            if prev_blank {
356                continue;
357            }
358            out.push("");
359            prev_blank = true;
360        } else {
361            out.push(trimmed);
362            prev_blank = false;
363        }
364    }
365    while out.first().is_some_and(|l| l.trim().is_empty()) {
366        out.remove(0);
367    }
368    while out.last().is_some_and(|l| l.trim().is_empty()) {
369        out.pop();
370    }
371    out.join("\n")
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377
378    #[test]
379    fn truncate_byte_budget_ascii() {
380        assert_eq!(truncate_byte_budget("hello world", 5, "..."), "hello...");
381        assert_eq!(truncate_byte_budget("hi", 10, "..."), "hi");
382    }
383
384    #[test]
385    fn truncate_byte_budget_cjk_no_panic() {
386        // 'こ' = 3 bytes, 'ん' = 3 bytes → "こんにちは" = 15 bytes
387        let jp = "こんにちは";
388        // Cutting at 5 bytes lands inside 'ん' (bytes 3..6); must round down to 3.
389        assert_eq!(truncate_byte_budget(jp, 5, "…"), "こ…");
390        // Cutting at 6 lands on boundary
391        assert_eq!(truncate_byte_budget(jp, 6, "…"), "こん…");
392    }
393
394    #[test]
395    fn truncate_byte_budget_mixed_ascii_cjk() {
396        let mixed = "AB日本語CD";
397        // A=1, B=1, 日=3, 本=3, 語=3, C=1, D=1 → 13 bytes total
398        assert_eq!(truncate_byte_budget(mixed, 4, ".."), "AB.."); // mid-日 rounds to 2
399        assert_eq!(truncate_byte_budget(mixed, 5, ".."), "AB日.."); // 2+3=5 exact
400    }
401
402    #[test]
403    fn truncate_byte_budget_emoji() {
404        let emoji = "👋🌍"; // 4 bytes each = 8 bytes
405        assert_eq!(truncate_byte_budget(emoji, 5, "!"), "👋!");
406    }
407
408    #[test]
409    fn truncate_byte_budget_zero() {
410        assert_eq!(truncate_byte_budget("abc", 0, "..."), "...");
411    }
412
413    #[test]
414    fn compact_reasoning_text_collapses_blank_runs() {
415        assert_eq!(compact_reasoning_text("line1\n\n\n\nline2\n"), "line1\n\nline2");
416        assert_eq!(compact_reasoning_text("a\n\n\n\n\n\nb"), "a\n\nb");
417    }
418
419    #[test]
420    fn compact_reasoning_text_preserves_single_paragraph_breaks() {
421        assert_eq!(compact_reasoning_text("para one\n\npara two\n"), "para one\n\npara two");
422    }
423
424    #[test]
425    fn compact_reasoning_text_trims_trailing_whitespace() {
426        assert_eq!(compact_reasoning_text("  a  \n\n\n  b  \n"), "a\n\nb");
427    }
428
429    #[test]
430    fn compact_reasoning_text_strips_leading_trailing_blanks() {
431        assert_eq!(compact_reasoning_text("\n\n\nmid\n\n\n"), "mid");
432        assert_eq!(compact_reasoning_text("\n\n\n"), "");
433        assert_eq!(compact_reasoning_text(""), "");
434    }
435
436    #[test]
437    fn wrap_text_words_basic_and_continuation_width() {
438        assert_eq!(wrap_text_words("the quick brown fox", 9, 9), vec!["the quick", "brown fox"]);
439        // First line wider than continuation lines.
440        assert_eq!(wrap_text_words("alpha beta gamma delta", 11, 5), vec!["alpha beta", "gamma", "delta"]);
441    }
442
443    #[test]
444    fn wrap_text_words_blank_and_unicode() {
445        assert!(wrap_text_words("   ", 5, 5).is_empty());
446        // Must not panic on multi-byte chars and counts chars, not bytes.
447        let wrapped = wrap_text_words("あいう えお かきく", 3, 3);
448        assert_eq!(wrapped, vec!["あいう", "えお", "かきく"]);
449    }
450
451    #[test]
452    fn truncate_within_reserves_ellipsis_budget() {
453        // Matches former runner::orchestration::truncate_chars behavior.
454        assert_eq!(truncate_within("hello world", 8, "..."), "hello...");
455        assert_eq!(truncate_within("hi", 8, "..."), "hi");
456        // Single-char ellipsis reserves exactly one char (former snapshots /
457        // session_archive behavior).
458        assert_eq!(truncate_within("abcdef", 4, "…"), "abc…");
459    }
460
461    #[test]
462    fn truncate_within_counts_chars() {
463        let jp = "あいうえお"; // 5 chars
464        assert_eq!(truncate_within(jp, 5, "…"), jp);
465        assert_eq!(truncate_within(jp, 3, "…"), "あい…");
466    }
467
468    #[test]
469    fn head_tail_truncate_keeps_both_ends() {
470        let value = "0123456789".repeat(10); // 100 chars
471        let (out, truncated) = head_tail_truncate(&value, 40, " ... [truncated] ... ");
472        assert!(truncated);
473        assert!(out.chars().count() <= 40);
474        assert!(out.starts_with("012"));
475        assert!(out.contains("[truncated]"));
476        assert!(out.ends_with('9'));
477    }
478
479    #[test]
480    fn head_tail_truncate_passes_through_when_short() {
481        let (out, truncated) = head_tail_truncate("short", 64, " ... ");
482        assert_eq!(out, "short");
483        assert!(!truncated);
484    }
485
486    #[test]
487    fn head_tail_truncate_small_budget_falls_back_to_prefix() {
488        let marker = " ... [truncated] ... ";
489        // max_chars <= marker_chars + 16 triggers the prefix fallback.
490        // When max_chars (5) <= suffix_len (12), return just the prefix without suffix.
491        let (out, truncated) = head_tail_truncate("abcdefghij", 5, marker);
492        assert!(truncated);
493        assert_eq!(out, "abcde");
494
495        // When max_chars allows room for suffix, include it in the fallback branch.
496        // Use max_chars=17 which is <= 21+16=37 (triggers fallback).
497        let long_text = "abcdefghijklmnopqrstuvwxyz";
498        let (out2, truncated2) = head_tail_truncate(long_text, 17, marker);
499        assert!(truncated2);
500        assert_eq!(out2, "abcde [truncated]");
501        assert_eq!(out2.chars().count(), 17);
502    }
503
504    #[test]
505    fn truncate_text_counts_chars_not_bytes() {
506        let jp = "あいうえお"; // 5 chars, 15 bytes
507        assert_eq!(truncate_text(jp, 3, "…"), "あいう…");
508        assert_eq!(truncate_text(jp, 5, "…"), "あいうえお");
509    }
510
511    #[test]
512    fn truncate_middle_keeps_both_ends() {
513        assert_eq!(truncate_middle("short", 80), "short");
514        assert_eq!(truncate_middle("abcdefghij", 5), "ab…ij");
515        assert_eq!(truncate_middle("a b c", 80), "a b c");
516        // Zero/one-char budgets.
517        assert_eq!(truncate_middle("abc", 0), "");
518        assert_eq!(truncate_middle("abc", 1), "…");
519        // Control characters are sanitized to spaces before truncating.
520        assert_eq!(truncate_middle("a\nb\tc", 80), "a b c");
521    }
522
523    #[test]
524    fn truncate_path_middle_breaks_at_separator() {
525        assert_eq!(truncate_path_middle("src/lib.rs", 80), "src/lib.rs");
526        assert_eq!(truncate_path_middle("foo/bar/baz/qux", 12), "foo…/qux");
527        assert_eq!(truncate_path_middle("abc", 0), "");
528    }
529}