Skip to content

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

feat(help): chop wt list example tables to width instead of wrapping (#3125)

Maximilian Roosa8aad444cab9
diff --git a/src/md_help.rs b/src/md_help.rs
index 02dcdeb1f..b3ac418d4 100644
--- a/src/md_help.rs
+++ b/src/md_help.rs
@@ -6,7 +6,8 @@ use termimad::{CompoundStyle, MadSkin, TableBorderChars};
use unicode_width::UnicodeWidthStr;
use worktrunk::styling::{
- DEFAULT_HELP_WIDTH, format_bash_with_gutter, format_toml, format_with_gutter, wrap_styled_text,
+ DEFAULT_HELP_WIDTH, format_bash_with_gutter, format_bash_with_gutter_chopped, format_toml,
+ format_with_gutter, wrap_styled_text,
};
/// Table border style matching our help text format:
@@ -49,6 +50,10 @@ pub(crate) fn render_markdown_in_help_with_width(help: &str, width: Option<usize
let mut code_block_lang = String::new();
let mut code_block_lines: Vec<&str> = Vec::new();
let mut table_lines: Vec<&str> = Vec::new();
+ // Set by a `<!-- wt list … -->` marker; consumed by the next code block.
+ // Tags captured `wt list` output (pre-formatted tables) so it is chopped to
+ // terminal width like real `wt list`, not word-wrapped (which shears columns).
+ let mut chop_next_block = false;
let lines: Vec<&str> = help.lines().collect();
let mut i = 0;
@@ -57,8 +62,17 @@ pub(crate) fn render_markdown_in_help_with_width(help: &str, width: Option<usize
let line = lines[i];
let trimmed = line.trim_start();
- // Skip HTML comments (expansion markers for web docs, see readme_sync.rs)
+ // HTML comments are expansion markers for web docs (see readme_sync.rs) and
+ // don't render. A `<!-- wt list … -->` marker tags the captured `wt list`
+ // output that immediately follows, so the next code block is chopped (below).
if trimmed.starts_with("<!--") && trimmed.ends_with("-->") {
+ let inner = trimmed
+ .trim_start_matches("<!--")
+ .trim_end_matches("-->")
+ .trim();
+ if inner.starts_with("wt list") {
+ chop_next_block = true;
+ }
i += 1;
continue;
}
@@ -83,7 +97,13 @@ pub(crate) fn render_markdown_in_help_with_width(help: &str, width: Option<usize
.map(|l| l.strip_prefix("$ ").unwrap_or(l))
.collect::<Vec<_>>()
.join("\n");
- format_bash_with_gutter(&stripped)
+ // Captured `wt list` tables (chop_next_block) are chopped to
+ // width; hand-authored command sessions still word-wrap.
+ if chop_next_block {
+ format_bash_with_gutter_chopped(&stripped)
+ } else {
+ format_bash_with_gutter(&stripped)
+ }
}
"bash" | "sh" => format_bash_with_gutter(&content),
_ => {
@@ -101,6 +121,8 @@ pub(crate) fn render_markdown_in_help_with_width(help: &str, width: Option<usize
result.push_str(&formatted);
result.push('\n');
in_code_block = false;
+ // A marker applies only to the block right after it.
+ chop_next_block = false;
}
i += 1;
continue;
diff --git a/src/styling/format.rs b/src/styling/format.rs
index 77300d6ec..9a2b1d0c9 100644
--- a/src/styling/format.rs
+++ b/src/styling/format.rs
@@ -8,7 +8,21 @@ use super::highlighting::bash_token_style;
use tree_sitter_highlight::{HighlightConfiguration, HighlightEvent, Highlighter};
// Import canonical implementations from parent module
-use super::{terminal_width, visual_width};
+use super::{terminal_width, truncate_visible, visual_width};
+
+/// How a gutter line that exceeds the available width is fitted.
+///
+/// `Wrap` word-wraps onto continuation lines — the right choice for commands and
+/// config, where every token must stay readable. `Chop` truncates with an
+/// ellipsis, preserving horizontal alignment — the right choice for pre-formatted
+/// tabular output (e.g. captured `wt list` tables in help text), where wrapping
+/// would shear the columns apart and a paste is never intended.
+#[cfg(feature = "syntax-highlighting")]
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub(crate) enum LineFit {
+ Wrap,
+ Chop,
+}
/// Width overhead added by format_with_gutter()
///
@@ -244,7 +258,11 @@ fn unique_template_placeholders(content: &str) -> (String, String) {
}
#[cfg(feature = "syntax-highlighting")]
-fn format_bash_with_gutter_impl(content: &str, width_override: Option<usize>) -> String {
+fn format_bash_with_gutter_impl(
+ content: &str,
+ width_override: Option<usize>,
+ fit: LineFit,
+) -> String {
// Normalize line endings: CRLF to LF, and trim trailing newlines.
// Trailing newlines would create spurious blank gutter lines because
// style restoration after newlines produces `\n[DIM]` which becomes
@@ -415,8 +433,22 @@ fn format_bash_with_gutter_impl(content: &str, width_override: Option<usize>) ->
.or_else(|| line.strip_suffix(dim_open.as_str()))
.unwrap_or(line)
})
- .flat_map(|line| wrap_styled_text(line, available_width))
- .map(|wrapped| format!("{gutter} {gutter:#} {wrapped}{reset}"))
+ .flat_map(|line| match fit {
+ LineFit::Wrap => wrap_styled_text(line, available_width),
+ LineFit::Chop => {
+ // truncate_visible ends a chopped line with a bare `…\x1b[0m`. Re-dim
+ // the ellipsis so it matches the dimmed block instead of rendering at
+ // full brightness, and drop its reset — the gutter map below appends
+ // the single trailing reset that every line gets.
+ let chopped = truncate_visible(line, available_width);
+ let chopped = match chopped.strip_suffix("…\u{1b}[0m") {
+ Some(head) => format!("{head}{dim}…"),
+ None => chopped,
+ };
+ vec![chopped]
+ }
+ })
+ .map(|fitted| format!("{gutter} {gutter:#} {fitted}{reset}"))
.collect::<Vec<_>>()
.join("\n")
}
@@ -437,15 +469,27 @@ fn format_bash_with_gutter_impl(content: &str, width_override: Option<usize>) ->
/// ```
#[cfg(feature = "syntax-highlighting")]
pub fn format_bash_with_gutter(content: &str) -> String {
- format_bash_with_gutter_impl(content, None)
+ format_bash_with_gutter_impl(content, None, LineFit::Wrap)
+}
+
+/// Like [`format_bash_with_gutter`], but truncates over-wide lines instead of
+/// wrapping them. For pre-formatted tabular output where alignment matters more
+/// than seeing every column (captured `wt list` tables in `--help`).
+#[cfg(feature = "syntax-highlighting")]
+pub fn format_bash_with_gutter_chopped(content: &str) -> String {
+ format_bash_with_gutter_impl(content, None, LineFit::Chop)
}
/// Test-only helper to force a specific terminal width for deterministic output.
///
/// This avoids env var mutation which is unsafe in parallel tests.
#[cfg(all(test, feature = "syntax-highlighting"))]
-pub(crate) fn format_bash_with_gutter_at_width(content: &str, width: usize) -> String {
- format_bash_with_gutter_impl(content, Some(width))
+pub(crate) fn format_bash_with_gutter_at_width(
+ content: &str,
+ width: usize,
+ fit: LineFit,
+) -> String {
+ format_bash_with_gutter_impl(content, Some(width), fit)
}
/// Format bash commands with gutter (fallback without syntax highlighting)
@@ -457,6 +501,25 @@ pub fn format_bash_with_gutter(content: &str) -> String {
format_with_gutter(content, None)
}
+/// Chopping counterpart to [`format_bash_with_gutter`] for the no-highlighting
+/// fallback build. Mirrors [`format_with_gutter`]'s gutter, truncating each line.
+#[cfg(not(feature = "syntax-highlighting"))]
+pub fn format_bash_with_gutter_chopped(content: &str) -> String {
+ let gutter = super::GUTTER;
+ let term_width = terminal_width().unwrap_or(usize::MAX);
+ let available_width = term_width.saturating_sub(2);
+ content
+ .lines()
+ .map(|line| {
+ format!(
+ "{gutter} {gutter:#} {}",
+ truncate_visible(line, available_width)
+ )
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
#[cfg(test)]
mod tests {
use insta::assert_snapshot;
@@ -571,20 +634,51 @@ mod tests {
#[test]
#[cfg(feature = "syntax-highlighting")]
fn test_format_bash_with_gutter() {
- assert_snapshot!(format_bash_with_gutter_at_width("echo hello", 80), @"  echo hello");
+ assert_snapshot!(format_bash_with_gutter_at_width("echo hello", 80, LineFit::Wrap), @"  echo hello");
assert_snapshot!(
- format_bash_with_gutter_at_width("echo line1\necho line2", 80),
+ format_bash_with_gutter_at_width("echo line1\necho line2", 80, LineFit::Wrap),
@"
  echo line1
  echo line2
"
);
assert_snapshot!(
- format_bash_with_gutter_at_width("npm install && cargo build --release", 100),
+ format_bash_with_gutter_at_width("npm install && cargo build --release", 100, LineFit::Wrap),
@"  npm install && cargo build --release"
);
}
+ /// `LineFit::Chop` truncates an over-wide line to a single gutter line ending in
+ /// a dimmed ellipsis (one trailing reset, no full-brightness `…`); `LineFit::Wrap`
+ /// of the same content spills onto continuation lines instead. A line that fits
+ /// is untouched — Chop and Wrap agree.
+ #[test]
+ #[cfg(feature = "syntax-highlighting")]
+ fn test_format_bash_with_gutter_chop() {
+ let wide = "echo one two three four five six seven eight";
+
+ // Chop: one line, dimmed ellipsis, single trailing reset.
+ assert_snapshot!(
+ format_bash_with_gutter_at_width(wide, 30, LineFit::Chop),
+ @"  echo one two three four fiv…"
+ );
+
+ // Wrap: the same content continues onto a second gutter line.
+ assert_snapshot!(
+ format_bash_with_gutter_at_width(wide, 30, LineFit::Wrap),
+ @"
+   echo one two three four five
+    six seven eight
+ "
+ );
+
+ // A line that fits is identical under Chop and Wrap.
+ assert_eq!(
+ format_bash_with_gutter_at_width("echo hi", 80, LineFit::Chop),
+ format_bash_with_gutter_at_width("echo hi", 80, LineFit::Wrap),
+ );
+ }
+
/// Regression: tree-sitter identifies `&&` as operators even at line ends.
#[test]
#[cfg(feature = "syntax-highlighting")]
@@ -639,7 +733,7 @@ mod tests {
use ansi_str::AnsiStr;
let cmd = r#"if [ "{{ target }}" = "main" ]; then git pull && git push; fi"#;
- let result = format_bash_with_gutter_at_width(cmd, 120);
+ let result = format_bash_with_gutter_at_width(cmd, 120, LineFit::Wrap);
assert_snapshot!(result.ansi_strip(), @r#" if [ "{{ target }}" = "main" ]; then git pull && git push; fi"#);
}
@@ -696,7 +790,7 @@ mod tests {
// Path with `WTC` embedded (the actual failure shape seen on Windows CI).
let path = r"D:\tmp\.tmpOuiWTC\repo/../repo.feature";
- let stripped = format_bash_with_gutter_at_width(path, 120)
+ let stripped = format_bash_with_gutter_at_width(path, 120, LineFit::Wrap)
.ansi_strip()
.into_owned();
assert!(stripped.contains("WTC"), "{stripped}");
@@ -704,7 +798,7 @@ mod tests {
// Same with `WTO`.
let path = "echo /a/b/WTO/c";
- let stripped = format_bash_with_gutter_at_width(path, 120)
+ let stripped = format_bash_with_gutter_at_width(path, 120, LineFit::Wrap)
.ansi_strip()
.into_owned();
assert!(stripped.contains("WTO"), "{stripped}");
@@ -720,13 +814,13 @@ mod tests {
#[cfg(feature = "syntax-highlighting")]
fn test_trailing_cr_is_normalized() {
assert_eq!(
- format_bash_with_gutter_at_width("echo hello\r", 80),
- format_bash_with_gutter_at_width("echo hello", 80),
+ format_bash_with_gutter_at_width("echo hello\r", 80, LineFit::Wrap),
+ format_bash_with_gutter_at_width("echo hello", 80, LineFit::Wrap),
);
// The failure shape: last line ends in a highlighted token.
assert_eq!(
- format_bash_with_gutter_at_width("function wt\n wt $argv\nend\r", 80),
- format_bash_with_gutter_at_width("function wt\n wt $argv\nend", 80),
+ format_bash_with_gutter_at_width("function wt\n wt $argv\nend\r", 80, LineFit::Wrap),
+ format_bash_with_gutter_at_width("function wt\n wt $argv\nend", 80, LineFit::Wrap),
);
}
}
diff --git a/src/styling/mod.rs b/src/styling/mod.rs
index 275c3ca7a..f93783296 100644
--- a/src/styling/mod.rs
+++ b/src/styling/mod.rs
@@ -31,7 +31,10 @@ pub use anstyle::Style as AnstyleStyle;
// Re-export our public types
pub use constants::*;
-pub use format::{GUTTER_OVERHEAD, format_bash_with_gutter, format_with_gutter, wrap_styled_text};
+pub use format::{
+ GUTTER_OVERHEAD, format_bash_with_gutter, format_bash_with_gutter_chopped, format_with_gutter,
+ wrap_styled_text,
+};
pub use highlighting::format_toml;
pub use hyperlink::{Stream, hyperlink_stdout, strip_osc8_hyperlinks, supports_hyperlinks};
pub use line::{StyledLine, StyledString, truncate_visible};
@@ -192,7 +195,7 @@ mod tests {
use insta::assert_snapshot;
#[cfg(feature = "syntax-highlighting")]
- use super::format::format_bash_with_gutter_at_width;
+ use super::format::{LineFit, format_bash_with_gutter_at_width};
use super::*;
use anstyle::Style;
use unicode_width::UnicodeWidthStr;
@@ -639,7 +642,7 @@ command = "npm install"
let command = "cp -cR {{ repo_root }}/target/debug/.fingerprint {{ repo_root }}/target/debug/build {{ worktree }}/target/debug/";
// Use explicit width for deterministic output (avoids env var mutation in parallel tests)
- let result = format_bash_with_gutter_at_width(command, 80);
+ let result = format_bash_with_gutter_at_width(command, 80, LineFit::Wrap);
// Snapshot the raw output to verify ANSI codes are consistent
assert_snapshot!(result);
@@ -670,7 +673,7 @@ cp -cR {{ repo_root }}/target/debug/.fingerprint {{ repo_root }}/target/debug/bu
}}/target/debug/"#;
// Use explicit width for deterministic output (avoids env var mutation in parallel tests)
- let result = format_bash_with_gutter_at_width(multiline_command, 80);
+ let result = format_bash_with_gutter_at_width(multiline_command, 80, LineFit::Wrap);
// Snapshot the output - each line should have consistent dim styling
assert_snapshot!(result);
diff --git a/tests/integration_tests/help.rs b/tests/integration_tests/help.rs
index 01eb6a117..ffbe777c6 100644
--- a/tests/integration_tests/help.rs
+++ b/tests/integration_tests/help.rs
@@ -214,9 +214,11 @@ fn test_help_md_subcommand() {
});
}
-/// Verifies that markdown tables remain intact (no mid-row breaks) even when
-/// table width exceeds terminal width. Tables should extend past 80 columns
-/// rather than wrap incorrectly.
+/// Verifies width handling when help is narrower than its content:
+/// - Markdown tables stay intact (no mid-row breaks), extending past 80 columns.
+/// - Captured `wt list` example tables (`<!-- wt list … -->` blocks) are chopped
+/// to width with an ellipsis — like real `wt list` — instead of word-wrapping,
+/// while hand-authored command sessions (the `jq` examples) still wrap.
#[test]
fn test_help_list_narrow_terminal() {
help_settings().bind(|| {
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
index 5aee37db3..5c58adc05 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
@@ -100,50 +100,34 @@ List all worktrees:
  wt list
   Branch Status HEAD± main↕ Remote⇅ Commit Age Message
-  @ feature-api + ↕⇡ +54 -5 ↑4 ↓1 ⇡3 6814f02a 30m Add API 
-  tests
-  ^ main ^⇅ ⇡1 ⇣1 41ee0834 4d Merge 
-  fix-auth: hardened to…
-  + fix-auth ↕| ↑2 ↓1 | b772e68b 5h Add 
-  secure token storage
-  + fix-typos _| | 41ee0834 4d Merge 
-  fix-auth: hardened to…
+  @ feature-api + ↕⇡ +54 -5 ↑4 ↓1 ⇡3 6814f02a 30m Add API…
+  ^ main ^⇅ ⇡1 ⇣1 41ee0834 4d Merge f…
+  + fix-auth ↕| ↑2 ↓1 | b772e68b 5h Add sec…
+  + fix-typos _| | 41ee0834 4d Merge f…
  
  ○ Showing 4 worktrees, 1 with changes, 2 ahead, 1 column hidden
Include CI status, line diffs, and LLM summaries:
  wt list --full
-   Branch Status HEAD± main↕ main…± Summary 
-   Remote⇅ CI Commit
-  @ feature-api + ↕⇡ +54 -5 ↑4 ↓1 +234 -24 Refactor API to REST 
-  architecture with middleware ⇡3 #412 6814f02a
-  ^ main ^⇅ 
-   ⇡1 ⇣1 # 41ee0834
-  + fix-auth ↕| ↑2 ↓1 +25 -11 Harden auth with 
-  constant-time token validation | #408 b772e68b
-  + fix-typos _| 
-   | #410 41ee0834
+   Branch Status HEAD± main↕ main…± Summary …
+  @ feature-api + ↕⇡ +54 -5 ↑4 ↓1 +234 -24 Refactor API to REST …
+  ^ main ^⇅ …
+  + fix-auth ↕| ↑2 ↓1 +25 -11 Harden auth with cons…
+  + fix-typos _| …
  
  ○ Showing 4 worktrees, 1 with changes, 2 ahead, 3 columns hidden
Include branches that don't have worktrees:
  wt list --branches --full
-   Branch Status HEAD± main↕ main…± Summary 
-   Remote⇅ CI Commit
-  @ feature-api + ↕⇡ +54 -5 ↑4 ↓1 +234 -24 Refactor API to REST 
-  architecture with middleware ⇡3 #412 6814f02a
-  ^ main ^⇅ 
-   ⇡1 ⇣1 # 41ee0834
-  + fix-auth ↕| ↑2 ↓1 +25 -11 Harden auth with 
-  constant-time token validation | #408 b772e68b
-  + fix-typos _| 
-   | #410 41ee0834
-  / exp /↕ ↑2 ↓1 +137 Explore GraphQL schema
-   and resolvers 96379229
-  / wip /↕ ↑1 ↓1 +33 Start API 
-  documentation b40716dc
+   Branch Status HEAD± main↕ main…± Summary …
+  @ feature-api + ↕⇡ +54 -5 ↑4 ↓1 +234 -24 Refactor API to REST …
+  ^ main ^⇅ …
+  + fix-auth ↕| ↑2 ↓1 +25 -11 Harden auth with cons…
+  + fix-typos _| …
+  / exp /↕ ↑2 ↓1 +137 Explore GraphQL schem…
+  / wip /↕ ↑1 ↓1 +33 Start API documentati…
  
  ○ Showing 4 worktrees, 2 branches, 1 with changes, 4 ahead, 3 columns hidden