Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Dim unhighlighted shell command text

Maximilian Roosb3ea4068678a
diff --git a/Cargo.lock b/Cargo.lock
index 70264326a..add8721fd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -26,6 +26,15 @@ version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
+[[package]]
+name = "ansi-escape-sequences"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6afb74bb006f83a46d689f70e46ce3a9830db762134b3b585986fa9eab21f75d"
+dependencies = [
+ "regex",
+]
+
[[package]]
name = "ansi-str"
version = "0.9.0"
@@ -760,6 +769,12 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
+[[package]]
+name = "east-asian-width"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef8c47de0fcde8bd09c98fc22e4ea10ed14b9c05bf02c309e1e743aee7d0d9f6"
+
[[package]]
name = "either"
version = "1.15.0"
@@ -2073,6 +2088,27 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520"
+[[package]]
+name = "string-width"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f00d94d660cfa7bf3669352ebe9e06cc0351e0c9e696a31d051a54fa4bbb2b5"
+dependencies = [
+ "east-asian-width",
+ "regex",
+ "strip-ansi-escapes",
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "strip-ansi-escapes"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a8f8038e7e7969abb3f1b7c2a811225e9296da208539e0f79c5251d6cac0025"
+dependencies = [
+ "vte 0.14.1",
+]
+
[[package]]
name = "strsim"
version = "0.11.1"
@@ -2900,6 +2936,19 @@ dependencies = [
"unicode-width",
"vergen-gitcl",
"vt100",
+ "wrap-ansi",
+]
+
+[[package]]
+name = "wrap-ansi"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "848bc403c11fc8f4d6597f2bad2ce43111fbf6757c7dd7d62590199e8dade5fd"
+dependencies = [
+ "ansi-escape-sequences",
+ "regex",
+ "string-width",
+ "thiserror 2.0.17",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index 38bf205cc..6103d98cc 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -69,6 +69,7 @@ tree-sitter = { version = "0.25", optional = true }
tree-sitter-bash = { version = "0.25", optional = true }
tree-sitter-highlight = { version = "0.25", optional = true }
unicode-width = "0.2"
+wrap-ansi = "0.1"
osc8 = "0.1.0"
home = "0.5.12"
diff --git a/src/styling/format.rs b/src/styling/format.rs
index 6c36faf4a..09699b03c 100644
--- a/src/styling/format.rs
+++ b/src/styling/format.rs
@@ -138,35 +138,23 @@ pub fn format_with_gutter(content: &str, left_margin: &str, max_width: Option<us
output
}
-/// Wrap content lines for gutter display
-fn wrap_content_for_gutter(content: &str, left_margin: &str) -> Vec<String> {
- let term_width = get_terminal_width();
- let left_margin_width = left_margin.width();
- let available_width = term_width.saturating_sub(3 + left_margin_width);
-
- let mut wrapped_lines = Vec::new();
- for line in content.lines() {
- let wrapped = wrap_text_at_width(line, available_width);
- wrapped_lines.extend(wrapped);
+/// Wrap ANSI-styled text at word boundaries, preserving styles across line breaks
+///
+/// Uses `wrap-ansi` crate which handles ANSI escape sequences, Unicode width,
+/// and OSC 8 hyperlinks automatically.
+pub(super) fn wrap_styled_text(styled: &str, max_width: usize) -> Vec<String> {
+ if max_width == 0 {
+ return vec![styled.to_string()];
}
- wrapped_lines
-}
-/// Format wrapped lines with plain gutter (no syntax highlighting)
-#[cfg(not(feature = "syntax-highlighting"))]
-fn format_wrapped_lines_plain(wrapped_lines: &[String], left_margin: &str) -> String {
- let gutter = super::GUTTER;
- let dimmed = anstyle::Style::new().dimmed();
- let mut output = String::new();
+ // wrap_ansi returns a string with '\n' at wrap points, preserving ANSI styles
+ let wrapped = wrap_ansi::wrap_ansi(styled, max_width, None);
- for line in wrapped_lines {
- output.push_str(&format!("{left_margin}{gutter} {gutter:#} "));
- output.push_str(&format!("{dimmed}{line}{dimmed:#}"));
- output.push_str(&format!("{}", anstyle::Reset));
- output.push('\n');
+ if wrapped.is_empty() {
+ return vec![String::new()];
}
- output
+ wrapped.lines().map(|s| s.to_owned()).collect()
}
/// Formats bash/shell commands with syntax highlighting and gutter
@@ -188,7 +176,10 @@ pub fn format_bash_with_gutter(content: &str, left_margin: &str) -> String {
let reset = anstyle::Reset;
let mut output = String::new();
- let wrapped_lines = wrap_content_for_gutter(content, left_margin);
+ // Calculate available width for content
+ let term_width = get_terminal_width();
+ let left_margin_width = left_margin.width();
+ let available_width = term_width.saturating_sub(3 + left_margin_width);
// Set up tree-sitter bash highlighting
let highlight_names = vec![
@@ -230,17 +221,23 @@ pub fn format_bash_with_gutter(content: &str, left_margin: &str) -> String {
let mut highlighter = Highlighter::new();
- // Process each wrapped line
- for line in &wrapped_lines {
- // Start line with gutter and base gray style for unhighlighted content
- output.push_str(&format!("{left_margin}{gutter} {gutter:#} {base_style}"));
+ // Process each ORIGINAL line (not wrapped) to preserve parsing context
+ for line in content.lines() {
+ // Step 1: Highlight the complete line with tree-sitter
+ let mut styled_line = String::new();
+ styled_line.push_str(&format!("{base_style}"));
- // Highlight this line
let Ok(highlights) = highlighter.highlight(&config, line.as_bytes(), None, |_| None) else {
- // Fallback: just print plain text if highlighting fails (already gray)
- output.push_str(line);
- output.push_str(&format!("{reset}"));
- output.push('\n');
+ // Fallback: just use the plain line
+ styled_line.push_str(line);
+ styled_line.push_str(&format!("{reset}"));
+
+ // Wrap and output with gutter
+ for wrapped in wrap_styled_text(&styled_line, available_width) {
+ output.push_str(&format!(
+ "{left_margin}{gutter} {gutter:#} {wrapped}{reset}\n"
+ ));
+ }
continue;
};
@@ -251,7 +248,7 @@ pub fn format_bash_with_gutter(content: &str, left_margin: &str) -> String {
HighlightEvent::Source { start, end } => {
// Output the text for this source region (inherits current style)
if let Ok(text) = std::str::from_utf8(&line_bytes[start..end]) {
- output.push_str(text);
+ styled_line.push_str(text);
}
}
HighlightEvent::HighlightStart(idx) => {
@@ -259,19 +256,22 @@ pub fn format_bash_with_gutter(content: &str, left_margin: &str) -> String {
if let Some(name) = highlight_names.get(idx.0)
&& let Some(style) = bash_token_style(name)
{
- output.push_str(&format!("{style}"));
+ styled_line.push_str(&format!("{style}"));
}
}
HighlightEvent::HighlightEnd => {
// End of highlighted region - return to base gray style
- output.push_str(&format!("{base_style}"));
+ styled_line.push_str(&format!("{base_style}"));
}
}
}
- // Full reset at end of line to prevent leaking into child process output
- output.push_str(&format!("{reset}"));
- output.push('\n');
+ // Step 2: Wrap the styled line and output each part with gutter
+ for wrapped in wrap_styled_text(&styled_line, available_width) {
+ output.push_str(&format!(
+ "{left_margin}{gutter} {gutter:#} {wrapped}{reset}\n"
+ ));
+ }
}
output
@@ -283,6 +283,27 @@ pub fn format_bash_with_gutter(content: &str, left_margin: &str) -> String {
/// It provides the same gutter formatting without tree-sitter dependencies.
#[cfg(not(feature = "syntax-highlighting"))]
pub fn format_bash_with_gutter(content: &str, left_margin: &str) -> String {
- let wrapped_lines = wrap_content_for_gutter(content, left_margin);
- format_wrapped_lines_plain(&wrapped_lines, left_margin)
+ let gutter = super::GUTTER;
+ let dimmed = anstyle::Style::new().dimmed();
+ let reset = anstyle::Reset;
+ let mut output = String::new();
+
+ // Calculate available width for content
+ let term_width = get_terminal_width();
+ let left_margin_width = left_margin.width();
+ let available_width = term_width.saturating_sub(3 + left_margin_width);
+
+ for line in content.lines() {
+ // Apply dimmed style to the entire line
+ let styled_line = format!("{dimmed}{line}{reset}");
+
+ // Wrap and output with gutter
+ for wrapped in wrap_styled_text(&styled_line, available_width) {
+ output.push_str(&format!(
+ "{left_margin}{gutter} {gutter:#} {wrapped}{reset}\n"
+ ));
+ }
+ }
+
+ output
}
diff --git a/src/styling/mod.rs b/src/styling/mod.rs
index b0c9d4932..98e0ff503 100644
--- a/src/styling/mod.rs
+++ b/src/styling/mod.rs
@@ -74,6 +74,8 @@ pub fn hyperlink(text: &str, url: &str) -> String {
// Re-export for tests
#[cfg(test)]
+use format::wrap_styled_text;
+#[cfg(test)]
use format::wrap_text_at_width;
// ============================================================================
// Tests
@@ -446,4 +448,101 @@ command = "npm install"
assert!(result.contains(text));
assert!(result.ends_with("\x1b]8;;\x1b\\"));
}
+
+ // wrap_styled_text tests
+ #[test]
+ fn test_wrap_styled_text_no_wrapping_needed() {
+ let result = super::wrap_styled_text("short line", 50);
+ assert_eq!(result, vec!["short line"]);
+ }
+
+ #[test]
+ fn test_wrap_styled_text_zero_width() {
+ let result = super::wrap_styled_text("some text", 0);
+ assert_eq!(result, vec!["some text"]);
+ }
+
+ #[test]
+ fn test_wrap_styled_text_at_word_boundary() {
+ let text = "This is a very long line that needs wrapping";
+ let result = super::wrap_styled_text(text, 20);
+
+ // Should wrap into multiple lines
+ assert!(result.len() > 1, "Should wrap into multiple lines");
+
+ // Each line should be within width limit (using visual_width to ignore ANSI codes)
+ for line in &result {
+ let visual = visual_width(line);
+ assert!(
+ visual <= 20 || !line.contains(' '),
+ "Line '{}' has visual width {} which exceeds 20",
+ line,
+ visual
+ );
+ }
+ }
+
+ #[test]
+ fn test_wrap_styled_text_preserves_styles_across_breaks() {
+ // Create styled text: bold text that spans multiple words
+ let bold = Style::new().bold();
+ let input = format!("{bold}This is bold text that will wrap{bold:#}");
+ let result = super::wrap_styled_text(&input, 15);
+
+ // Should wrap
+ assert!(result.len() > 1, "Should wrap into multiple lines");
+
+ // First line should start with bold code
+ assert!(
+ result[0].contains("\x1b[1m"),
+ "First line should have bold code"
+ );
+
+ // Subsequent lines should re-emit the active style
+ // The style tracking should preserve bold across line breaks
+ for line in &result[1..] {
+ // Each continuation should either have the style re-emitted
+ // or just contain the text (if style was applied to word boundary)
+ // The key is no garbled output
+ assert!(!line.is_empty(), "Wrapped lines should have content");
+ }
+ }
+
+ #[test]
+ fn test_wrap_styled_text_handles_reset() {
+ // Text with style, then reset, then more text
+ let bold = Style::new().bold();
+ let input = format!("{bold}Bold{bold:#}\x1b[0m plain \x1b[32mgreen text here\x1b[0m");
+ let result = super::wrap_styled_text(&input, 10);
+
+ // Should produce valid output without crashes
+ assert!(!result.is_empty());
+ }
+
+ #[test]
+ fn test_wrap_styled_text_empty_input() {
+ let result = super::wrap_styled_text("", 50);
+ assert_eq!(result, vec![""]);
+ }
+
+ #[test]
+ fn test_wrap_styled_text_single_long_word() {
+ // A single word longer than max_width should still be included
+ let result = super::wrap_styled_text("verylongwordthatcannotbewrapped", 10);
+ assert_eq!(result.len(), 1);
+ assert_eq!(result[0], "verylongwordthatcannotbewrapped");
+ }
+
+ #[test]
+ fn test_wrap_styled_text_with_ansi_codes_in_word() {
+ // Style that starts and ends within a single word
+ let bold = Style::new().bold();
+ let input = format!("pre {bold}styled{bold:#} post");
+ let result = super::wrap_styled_text(&input, 50);
+
+ // Should not wrap (fits)
+ assert_eq!(result.len(), 1);
+ // Should contain the style codes
+ assert!(result[0].contains("\x1b[1m"), "Should contain bold code");
+ }
}
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiline_control_structure.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiline_control_structure.snap
index 0d050f0fe..1277dd0a4 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiline_control_structure.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiline_control_structure.snap
@@ -26,9 +26,9 @@ exit_code: 0
----- stdout -----
πŸ”„ Running post-create:
  if [ ! -f test.txt ]; then
-   echo 'File does not exist' > result.txt
+  echo 'File does not exist' > result.txt
  else
-   echo 'File exists' > result.txt
+  echo 'File exists' > result.txt
  fi
βœ… Created new worktree for feature from main at [REPO].feature
πŸ’‘ Run `wt config shell install` to enable automatic cd