Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Improve text wrapping with ANSI code awareness
Maximilian Roos3ca4b40cb5a8
diff --git a/src/styling/format.rs b/src/styling/format.rsindex c11fd0463..02c31ab63 100644--- a/src/styling/format.rs+++ b/src/styling/format.rs@@ -11,6 +11,53 @@ use super::highlighting::bash_token_style;/// Default terminal width fallback if detection failsconst DEFAULT_TERMINAL_WIDTH: usize = 80;+/// Strip ANSI escape codes from a string to get the visual content+///+/// Handles standard ANSI SGR (Select Graphic Rendition) codes: ESC[...m+///+/// # Scope+/// - Designed for git output (log, diff) which produces well-formed SGR sequences+/// - Only handles ESC[...m (SGR), not cursor movement or other ANSI codes+/// - Malformed sequences (ESC without [, or ESC[ without m) are preserved in output+fn strip_ansi_codes(s: &str) -> String {+ let mut result = String::with_capacity(s.len());+ let mut chars = s.chars().peekable();++ while let Some(ch) = chars.next() {+ if ch == '\x1b' && chars.peek() == Some(&'[') {+ // Start of ANSI escape sequence+ chars.next(); // consume '['++ // Skip until 'm' (SGR terminator) or end of string+ // Note: If sequence is incomplete (no 'm'), we'll consume rest of iterator+ // and result will be missing that content. This is acceptable for git output+ // which always produces well-formed sequences.+ let mut found_terminator = false;+ for next_ch in chars.by_ref() {+ if next_ch == 'm' {+ found_terminator = true;+ break;+ }+ }++ // If sequence was incomplete, we've consumed the rest of the string+ // This is a reasonable failure mode for malformed input+ if !found_terminator {+ break;+ }+ } else {+ result.push(ch);+ }+ }++ result+}++/// Calculate visual width of a string, ignoring ANSI escape codes+fn visual_width(s: &str) -> usize {+ strip_ansi_codes(s).width()+}+/// Get terminal width, defaulting to 80 if detection fails////// Checks COLUMNS environment variable first (for testing and scripts),@@ -32,17 +79,21 @@ fn get_terminal_width() -> usize {/// Wraps text at word boundaries to fit within the specified width////// # Arguments-/// * `text` - The text to wrap-/// * `max_width` - Maximum width for each line+/// * `text` - The text to wrap (may contain ANSI codes)+/// * `max_width` - Maximum visual width for each line////// # Returns/// A vector of wrapped lines+///+/// # Note+/// Width calculation ignores ANSI escape codes to handle colored output correctly.pub(super) fn wrap_text_at_width(text: &str, max_width: usize) -> Vec<String> {if max_width == 0 {return vec![text.to_string()];}- let text_width = text.width();+ // Use visual width (ignoring ANSI codes) for proper wrapping of colored text+ let text_width = visual_width(text);// If the line fits, return it as-isif text_width <= max_width {@@ -54,7 +105,7 @@ pub(super) fn wrap_text_at_width(text: &str, max_width: usize) -> Vec<String> {let mut current_width = 0;for word in text.split_whitespace() {- let word_width = word.width();+ let word_width = visual_width(word);// If this is the first word in the lineif current_line.is_empty() {diff --git a/src/styling/mod.rs b/src/styling/mod.rsindex b833715b6..37d2c951e 100644--- a/src/styling/mod.rs+++ b/src/styling/mod.rs@@ -350,4 +350,36 @@ command = "npm install""Style::new() and anstyle::Reset are NOT equivalent - always use anstyle::Reset");}++ #[test]+ fn test_wrap_text_with_ansi_codes() {+ use super::format::wrap_text_at_width;++ // Simulate a git log line with ANSI color codes+ // Visual content: "* 9452817 Clarify wt merge worktree removal behavior" (52 chars)+ // But with ANSI codes, the raw string is much longer+ let colored_text = "* \x1b[33m9452817\x1b[m Clarify wt merge worktree removal behavior";++ // Without ANSI stripping, this would wrap prematurely because the raw string+ // (with escape codes) is ~70 chars. With proper ANSI stripping, the visual+ // width is only ~52 chars, so it should NOT wrap at width 60.+ let result = wrap_text_at_width(colored_text, 60);++ assert_eq!(+ result.len(),+ 1,+ "Colored text should NOT wrap when visual width (52) < max_width (60)"+ );+ assert_eq!(+ result[0], colored_text,+ "Should return original text with ANSI codes intact"+ );++ // Now test that it DOES wrap when visual width exceeds max_width+ let result = wrap_text_at_width(colored_text, 30);+ assert!(+ result.len() > 1,+ "Should wrap into multiple lines when visual width (52) > max_width (30)"+ );+ }}diff --git a/tests/integration_tests/config_list.rs b/tests/integration_tests/config_list.rsindex 6deaa7a09..71deaafa4 100644--- a/tests/integration_tests/config_list.rs+++ b/tests/integration_tests/config_list.rs@@ -161,10 +161,10 @@ fn test_config_list_outside_git_repo() {success: trueexit_code: 0----- stdout ------ ⚪ Global Config: [TEMP_HOME]/.config/worktrunk/config.toml- worktree-path = "../{main-worktree}.{branch}"+ ⚪ Global Config: [1m[TEMP_HOME]/.config/worktrunk/config.toml[0m+ [40m [0m worktree-path = [32m"../{main-worktree}.{branch}"[0m- ⚪ Project Config: Not in a git repository+ ⚪ [2mProject Config: Not in a git repository[0m----- stderr -----"#);