Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Add colored markdown help via `termimad`
Maximilian Roos807c70a242ac
diff --git a/Cargo.lock b/Cargo.lockindex a49043d98..ecec26b96 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -342,7 +342,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b30fa8254caad766fc03cb0ccae691e14bf3bd72bfff27f72802ce729551b3d6"dependencies = ["async-trait",- "convert_case",+ "convert_case 0.6.0","json5","pathdiff","ron",@@ -409,6 +409,24 @@ dependencies = ["unicode-segmentation",]+[[package]]+name = "convert_case"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb402b8d4c85569410425650ce3eddc7d698ed96d39a73f941b08fb63082f1e7"+dependencies = [+ "unicode-segmentation",+]++[[package]]+name = "coolor"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "980c2afde4af43d6a05c5be738f9eae595cff86dce1f38f88b95058a98c027f3"+dependencies = [+ "crossterm",+]+[[package]]name = "core-foundation-sys"version = "0.8.7"@@ -457,6 +475,32 @@ dependencies = ["itertools",]+[[package]]+name = "crokey"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "51360853ebbeb3df20c76c82aecf43d387a62860f1a59ba65ab51f00eea85aad"+dependencies = [+ "crokey-proc_macros",+ "crossterm",+ "once_cell",+ "serde",+ "strict",+]++[[package]]+name = "crokey-proc_macros"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3bf1a727caeb5ee5e0a0826a97f205a9cf84ee964b0b48239fef5214a00ae439"+dependencies = [+ "crossterm",+ "proc-macro2",+ "quote",+ "strict",+ "syn",+]+[[package]]name = "crossbeam"version = "0.8.4"@@ -513,6 +557,33 @@ version = "0.8.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"+[[package]]+name = "crossterm"+version = "0.29.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"+dependencies = [+ "bitflags 2.10.0",+ "crossterm_winapi",+ "derive_more",+ "document-features",+ "mio",+ "parking_lot",+ "rustix",+ "signal-hook",+ "signal-hook-mio",+ "winapi",+]++[[package]]+name = "crossterm_winapi"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"+dependencies = [+ "winapi",+]+[[package]]name = "crunchy"version = "0.2.4"@@ -628,6 +699,27 @@ dependencies = ["syn",]+[[package]]+name = "derive_more"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678"+dependencies = [+ "derive_more-impl",+]++[[package]]+name = "derive_more-impl"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3"+dependencies = [+ "convert_case 0.7.1",+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "dev-detach"version = "0.1.0"@@ -705,6 +797,15 @@ dependencies = ["const-random",]+[[package]]+name = "document-features"+version = "0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"+dependencies = [+ "litrs",+]+[[package]]name = "downcast-rs"version = "1.2.1"@@ -1143,6 +1244,29 @@ dependencies = ["serde",]+[[package]]+name = "lazy-regex"+version = "3.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "191898e17ddee19e60bccb3945aa02339e81edd4a8c50e21fd4d48cdecda7b29"+dependencies = [+ "lazy-regex-proc_macros",+ "once_cell",+ "regex",+]++[[package]]+name = "lazy-regex-proc_macros"+version = "3.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c35dc8b0da83d1a9507e12122c80dea71a9c7c613014347392483a83ea593e04"+dependencies = [+ "proc-macro2",+ "quote",+ "regex",+ "syn",+]+[[package]]name = "lazy_static"version = "1.5.0"@@ -1171,6 +1295,12 @@ version = "0.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"+[[package]]+name = "litrs"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"+[[package]]name = "lock_api"version = "0.4.14"@@ -1201,6 +1331,27 @@ dependencies = ["serde",]+[[package]]+name = "minimad"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9c5d708226d186590a7b6d4a9780e2bdda5f689e0d58cd17012a298efd745d2"+dependencies = [+ "once_cell",+]++[[package]]+name = "mio"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873"+dependencies = [+ "libc",+ "log",+ "wasi",+ "windows-sys 0.61.2",+]+[[package]]name = "nix"version = "0.28.0"@@ -1307,6 +1458,16 @@ version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8b2d2086a3a477709f0208181e65857a9c062064ab2b3bb9abaf64f17d148bf3"+[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]+[[package]]name = "parking_lot_core"version = "0.9.12"@@ -1876,6 +2037,36 @@ version = "1.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"+[[package]]+name = "signal-hook"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"+dependencies = [+ "libc",+ "signal-hook-registry",+]++[[package]]+name = "signal-hook-mio"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"+dependencies = [+ "libc",+ "mio",+ "signal-hook",+]++[[package]]+name = "signal-hook-registry"+version = "1.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2a4719bff48cee6b39d12c020eeb490953ad2443b7055bd0b21fca26bd8c28b"+dependencies = [+ "libc",+]+[[package]]name = "similar"version = "2.7.0"@@ -1954,6 +2145,12 @@ version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520"+[[package]]+name = "strict"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f42444fea5b87a39db4218d9422087e66a85d0e7a0963a439b07bcdf91804006"+[[package]]name = "strip-ansi-escapes"version = "0.2.1"@@ -2038,6 +2235,22 @@ dependencies = ["winapi",]+[[package]]+name = "termimad"+version = "0.34.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68ff5ca043d65d4ea43b65cdb4e3aba119657d0d12caf44f93212ec3168a8e20"+dependencies = [+ "coolor",+ "crokey",+ "crossbeam",+ "lazy-regex",+ "minimad",+ "serde",+ "thiserror 2.0.17",+ "unicode-width 0.1.14",+]+[[package]]name = "terminal_size"version = "0.4.3"@@ -2826,6 +3039,7 @@ dependencies = ["strum","synoptic","tempfile",+ "termimad","terminal_size","toml","tree-sitter",diff --git a/Cargo.toml b/Cargo.tomlindex f8a9f379a..ca07e8a3e 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -60,6 +60,7 @@ strip-ansi-escapes = "0.2"strum = { version = "0.27", features = ["derive"] }synoptic = "2"terminal_size = "0.4"+termimad = "0.34"toml = { version = "0.9", features = ["preserve_order"] }# All three crates must use the same version series to avoid native library conflicts# These are optional dependencies controlled by the "syntax-highlighting" feature.diff --git a/TERMIMAD-COLORS.md b/TERMIMAD-COLORS.mdnew file mode 100644index 000000000..e8a4bf5dd--- /dev/null+++ b/TERMIMAD-COLORS.md@@ -0,0 +1,634 @@+# Termimad ANSI Color Output Investigation++## Goal++Render CLI help text with markdown formatting (headers, bold, code blocks) as ANSI-colored output for terminal display. We want `wt merge --help` to show:+- **Bold text** in a distinct color (yellow/bright)+- `inline code` in a different color (magenta)+- ## Headers in another color (green)+- ```code blocks``` with syntax highlighting or distinct styling++The help text should be piped through a pager (like `less -R`) and display with proper formatting.++## Current Architecture++### Dependencies+```toml+# Cargo.toml+termimad = "0.34"+clap = { version = "4.5", features = ["derive", "unstable-ext"] }+terminal_size = "0.4"+```++### Code Structure++**src/md_help.rs** - Renders markdown to ANSI using termimad:+```rust+use clap::{Command, builder::StyledStr};+use termimad::MadSkin;++/// Render markdown to an ANSI-colored string suitable for terminal output+fn md_to_ansi(md: &str, skin: &MadSkin) -> String {+ // Use text() with explicit width instead of term_text() to force ANSI generation+ let width = terminal_size::terminal_size()+ .map(|(w, _)| w.0 as usize)+ .unwrap_or(80);++ let fmt_text = skin.text(md, Some(width));++ // Try using format!() instead of to_string()+ let rendered = format!("{}", fmt_text);++ // Debug: Check if ANSI codes are present+ if rendered.contains('\x1b') {+ eprintln!("[DEBUG] Markdown rendered WITH ANSI codes ({} bytes)", rendered.len());+ } else {+ eprintln!("[DEBUG] Markdown rendered WITHOUT ANSI codes ({} bytes)", rendered.len());+ eprintln!("[DEBUG] First 100 chars: {:?}", &rendered.chars().take(100).collect::<String>());+ }++ rendered+}++pub fn apply_markdown_to_command(cmd: &mut Command) {+ use termimad::crossterm::style::Color::*;++ let mut skin = MadSkin::default();++ // Configure explicit colors for different markdown elements+ skin.bold.set_fg(Yellow);+ skin.italic.set_fg(Cyan);+ skin.headers[0].set_fg(Green); // # headers+ skin.headers[1].set_fg(Green); // ## headers+ skin.inline_code.set_fg(Magenta);+ skin.code_block.set_fg(Magenta);++ eprintln!("[DEBUG] Skin configured with explicit colors");++ // rewrite the "sections" for this command+ if let Some(s) = cmd.get_before_long_help() {+ let rendered = md_to_ansi(&styled_to_plain(s), &skin);+ *cmd = std::mem::take(cmd).before_long_help(rendered);+ }+ if let Some(s) = cmd.get_long_about() {+ let rendered = md_to_ansi(&styled_to_plain(s), &skin);+ *cmd = std::mem::take(cmd).long_about(rendered);+ }+ // ... (similar for after_long_help and arg help)++ // recurse into subcommands+ for sub in cmd.get_subcommands_mut() {+ apply_markdown_to_command(sub);+ }+}+```++**src/main.rs** - Integration point:+```rust+fn maybe_handle_help_with_pager() -> bool {+ use clap::error::ErrorKind;++ let mut cmd = Cli::command();++ // Render markdown (long_about / arg docs) to ANSI before parsing+ md_help::apply_markdown_to_command(&mut cmd);++ match cmd.try_get_matches_from_mut(std::env::args()) {+ Ok(_) => false,+ Err(err) => {+ match err.kind() {+ ErrorKind::DisplayHelp => {+ // Re-resolve which subcommand's help user asked for+ let target = help_resolver::resolve_target_command(&mut cmd, std::env::args());+ let help = target.render_long_help().to_string();+ if let Err(e) = help_pager::show_help_in_pager(&help) {+ log::debug!("Pager invocation failed: {}", e);+ eprintln!("{}", help);+ }+ process::exit(0);+ }+ // ... version handling+ }+ }+ }+}+```++**Example markdown in src/cli.rs**:+```rust+/// Merge worktree into target branch+#[command(long_about = r#"Merge worktree into target branch++## OPERATION++The merge operation follows a strict order designed for **fail-fast execution**:++1. **Validate branches**+ Verifies current branch exists (not detached HEAD) and determines target branch+ (defaults to repository's default branch).++2. **Auto-commit uncommitted changes**+ If working tree has uncommitted changes, stages changes and commits with LLM-generated+ message. By default stages all changes (`git add -A`). Use `--tracked-only` to stage only+ tracked files (`git add -u`).++... (more markdown)+"#)]+Merge {+ // ... args+}+```++## What We've Tried++### Attempt 1: Using `term_text()` (original approach)+```rust+fn md_to_ansi(md: &str, skin: &MadSkin) -> String {+ skin.term_text(md).to_string()+}+```++**Result:**+```+[DEBUG] Markdown rendered WITHOUT ANSI codes (25 bytes)+[DEBUG] First 100 chars: "Change working directory\n"+```++**Observation:** No ANSI codes (`\x1b` escape sequences) in output. The markdown markers (`**`, `##`, `` ` ``) are removed, but no color codes are added.++### Attempt 2: Using `text()` with explicit width+**Hypothesis:** Maybe `term_text()` auto-detects TTY and disables colors. Try `text()` with explicit width.++```rust+fn md_to_ansi(md: &str, skin: &MadSkin) -> String {+ let width = terminal_size::terminal_size()+ .map(|(w, _)| w.0 as usize)+ .unwrap_or(80);++ skin.text(md, Some(width)).to_string()+}+```++**Result:**+```+[DEBUG] Markdown rendered WITHOUT ANSI codes (25 bytes)+```++**Observation:** Still no ANSI codes.++### Attempt 3: Configuring MadSkin with explicit colors+**Hypothesis:** Maybe we need to explicitly configure colors instead of relying on defaults.++```rust+pub fn apply_markdown_to_command(cmd: &mut Command) {+ use termimad::crossterm::style::Color::*;++ let mut skin = MadSkin::default();++ skin.bold.set_fg(Yellow);+ skin.italic.set_fg(Cyan);+ skin.headers[0].set_fg(Green);+ skin.headers[1].set_fg(Green);+ skin.inline_code.set_fg(Magenta);+ skin.code_block.set_fg(Magenta);++ // ... use this skin for rendering+}+```++**Result:**+```+[DEBUG] Skin configured with explicit colors+[DEBUG] Markdown rendered WITHOUT ANSI codes (25 bytes)+[DEBUG] Markdown rendered WITHOUT ANSI codes (29 bytes)+```++**Observation:** Skin is configured, but still no ANSI output.++### Attempt 4: Using `format!()` instead of `to_string()`+**Hypothesis:** Maybe the `Display` trait implementation differs from `to_string()`.++```rust+fn md_to_ansi(md: &str, skin: &MadSkin) -> String {+ let fmt_text = skin.text(md, Some(width));+ format!("{}", fmt_text) // Instead of fmt_text.to_string()+}+```++**Result:**+```+[DEBUG] Markdown rendered WITHOUT ANSI codes (25 bytes)+```++**Observation:** No difference.++### Attempt 5: Environment variable `CLICOLOR_FORCE`+**Hypothesis:** Maybe termimad respects standard color environment variables.++```bash+CLICOLOR_FORCE=1 cargo run --quiet -- merge --help 2>&1 | grep "DEBUG.*ANSI"+```++**Result:**+```+[DEBUG] Markdown rendered WITHOUT ANSI codes (25 bytes)+```++**Observation:** Environment variable has no effect.++### Attempt 6: Using `inline()` for single lines+**Hypothesis:** Maybe `text()` strips colors but `inline()` doesn't.++(Not yet tested - but worth trying for argument help text which is often single-line)++## What We've Discovered++### Markdown Processing Works+The markdown **is** being processed by termimad:+- `**bold**` markers are removed+- `##` headers are removed+- `` `code` `` backticks are removed+- Text is wrapped to appropriate width++**Example input:**+```markdown+## OPERATION++The merge operation follows a strict order designed for **fail-fast execution**:+```++**Actual output:**+```+OPERATION++The merge operation follows a strict order designed for fail-fast execution:+```++The structural elements are processed correctly, just without ANSI color codes.++### ANSI Detection Always Fails+Despite trying multiple methods, the debug check `rendered.contains('\x1b')` **always returns false**. This strongly suggests termimad is:++1. Detecting it's not connected to a TTY+2. Stripping all ANSI codes before returning the string+3. Returning plain text with markdown formatting removed++### The TTY Context+When we run:+```bash+cargo run -- merge --help+```++The help is being generated in `maybe_handle_help_with_pager()`, which runs **before** the pager is spawned. At this point:+- stdout might not be a TTY (cargo captures it)+- The code hasn't yet spawned the pager+- Termimad likely detects this and strips colors++Later, we pipe the result through a pager:+```rust+help_pager::show_help_in_pager(&help)+```++But by then, the ANSI codes are already gone.++## Assumptions (Unproven)++### Assumption 1: Termimad detects TTY at render time+**Status:** LIKELY TRUE based on observed behavior++**Evidence:**+- No ANSI codes appear regardless of method used+- Crossterm (termimad's backend) likely checks `std::io::stdout().is_terminal()`+- Similar to how `anstream` works in our codebase++**Load-bearing:** If true, we need to either:+- Force TTY detection to return true+- Bypass termimad's color stripping+- Use a different rendering approach++### Assumption 2: `text()` and `term_text()` both strip colors when not TTY+**Status:** APPEARS TRUE++**Evidence:**+- Both methods produce identical output (no ANSI codes)+- Explicit width in `text()` doesn't bypass TTY detection++**Load-bearing:** If true, `inline()` might also strip colors. Need to test.++### Assumption 3: MadSkin color configuration only affects TTY output+**Status:** APPEARS TRUE++**Evidence:**+- Configuring colors had no effect on output+- Colors are being set on the skin, but not appearing in output++**Load-bearing:** If true, skin configuration is irrelevant for our use case unless we can force TTY detection.++### Assumption 4: Termimad uses crossterm for TTY detection+**Status:** DOCUMENTED TRUE++From termimad README:+> "termimad uses crossterm as backend for styling and event"++**Load-bearing:** If crossterm is the backend, we might be able to:+- Set crossterm environment variables+- Use crossterm APIs directly+- Understand TTY detection mechanism++### Assumption 5: There's no official API to force color output+**Status:** APPEARS TRUE based on documentation search++**Evidence:**+- No method like `.force_colors(true)` in docs+- No environment variable mentioned in docs+- GitHub/docs.rs search found no TTY override mechanism++**Load-bearing:** If true, we might need to:+- Fork termimad and modify it+- Use a different library+- Implement our own markdown→ANSI converter++### Assumption 6: The issue is in rendering, not in pager+**Status:** TRUE - confirmed by debug output++**Evidence:**+- Debug statements show no ANSI codes **before** pager is invoked+- Problem is in `md_to_ansi()`, not in `show_help_in_pager()`++## Open Questions for Research++### Question 1: How does termimad/crossterm detect TTY?+**Research needed:**+- Check crossterm source code or documentation+- Look for `is_terminal()`, `isatty()`, or similar+- Understand what environment variables or APIs it checks++**Why it matters:** If we know the detection mechanism, we can override it.++**Specific searches:**+- "crossterm force colors"+- "crossterm TTY detection bypass"+- "crossterm CLICOLOR_FORCE"+- Check crossterm GitHub issues for similar problems++### Question 2: Does termimad have an API to force color output?+**Research needed:**+- Read termimad source code (not just docs)+- Check for undocumented methods or features+- Look at GitHub issues/PRs for color-forcing mechanisms++**Why it matters:** There might be an official way we haven't found.++**Specific searches:**+- termimad GitHub issues: "force colors"+- termimad GitHub issues: "TTY"+- termimad source: search for `isatty`, `is_terminal`, color detection logic++### Question 3: How do other Rust CLIs solve this problem?+**Research needed:**+- Find Rust CLIs that use termimad for help text+- See if any have solved the "render ANSI before paging" problem+- Check if they use different libraries++**Why it matters:** We might be solving a problem others have already solved.++**Specific searches:**+- GitHub code search: `termimad + pager`+- GitHub code search: `termimad + clap`+- Rust CLI tools using markdown help (ripgrep, bat, fd, etc.)++### Question 4: Is there a crossterm-level override?+**Research needed:**+- Check if crossterm respects `NO_COLOR=0` to force colors+- Look for crossterm APIs that bypass TTY detection+- Check crossterm's `SetColorSupport` or similar APIs++**Why it matters:** If crossterm has the capability, termimad might expose it.++**Specific searches:**+- "crossterm force color output"+- crossterm documentation: color support detection+- crossterm source: `colored()`, `supports_color()`++### Question 5: What is the FmtText/FmtInline implementation?+**Research needed:**+- Read termimad source for `FmtText` and `FmtInline` structs+- Check their `Display` implementation+- See if they have alternate formatting methods++**Why it matters:** The `Display` impl might have different code paths we're not aware of.++**Specific code to examine:**+- termimad/src/fmt_text.rs or similar+- Look for `impl Display for FmtText`+- Check for methods like `to_colored_string()`, `render()`, etc.++### Question 6: Does `inline()` behave differently than `text()`?+**Research needed:**+- Test `skin.inline()` for single-line content+- Compare its output to `text()` output+- Check termimad docs for `inline()` vs `text()` differences++**Why it matters:** Single-line rendering might have different TTY detection logic.++**Code to test:**+```rust+let inline_result = skin.inline("**bold** and `code`");+let inline_str = format!("{}", inline_result);+eprintln!("Inline contains ANSI: {}", inline_str.contains('\x1b'));+```++### Question 7: Can we use termimad's `print_*` functions?+**Research needed:**+- Check if `print_text()`, `print_inline()` write ANSI to stdout+- See if we can capture their output to a string+- Test if they bypass our TTY issue++**Why it matters:** The print functions might force colors since they write directly to stdout.++**Code to research:**+```rust+// Does this output ANSI codes?+skin.print_text(md)?;+// Can we capture it somehow?+```++### Question 8: Are there alternatives to termimad?+**Research needed:**+- Search for other Rust markdown→ANSI libraries+- Check crates.io for "markdown terminal", "markdown ansi"+- Compare features and TTY handling++**Why it matters:** If termimad is fundamentally incompatible with our use case, we need alternatives.++**Libraries to research:**+- `colored` + simple markdown parser+- `syntect` (for code highlighting)+- `tabled` (for tables)+- Custom implementation using `anstyle`++### Question 9: What exactly does clap's StyledStr do?+**Research needed:**+- Understand how clap handles ANSI in help text+- Check if StyledStr preserves ANSI codes+- See if we're inadvertently stripping codes when converting++**Why it matters:** Maybe the issue is in our conversion from markdown → ANSI → StyledStr.++**Code to examine:**+```rust+fn styled_to_plain(s: &StyledStr) -> String {+ s.to_string() // Does this strip ANSI?+}+```++### Question 10: Is there a way to "fake" TTY for termimad?+**Research needed:**+- Check if we can temporarily override `std::io::stdout().is_terminal()`+- Look for mocking or test utilities+- See if there's a thread-local TTY override++**Why it matters:** If we can fake TTY during rendering, termimad might output ANSI.++**Approaches to research:**+- Mock stdout with a pseudo-TTY+- Use `duct` or similar to capture colored output+- Spawn a subprocess with PTY++## Successful Aspects++### 1. Markdown Parsing Works+Termimad successfully:+- Removes markdown syntax+- Wraps text appropriately+- Preserves semantic structure+- Handles code blocks, headers, bold, etc.++### 2. Integration with Clap Works+Our architecture successfully:+- Intercepts help before clap processes it+- Resolves correct subcommand for help+- Passes processed text back to clap+- Maintains all clap features (args, flags, etc.)++### 3. Pager Integration Works+The help pager:+- Correctly detects when to use pager+- Pipes output through less/custom pager+- Handles both stdout and stderr TTY detection+- Falls back gracefully when pager unavailable++## Current Output Examples++### Input (in src/cli.rs):+```rust+#[command(long_about = r#"Merge worktree into target branch++## OPERATION++The merge operation follows a strict order designed for **fail-fast execution**:++1. **Validate branches**+ Verifies current branch exists (not detached HEAD)+"#)]+```++### Actual Output (via `cargo run -- merge --help`):+```+Merge worktree into target branch++OPERATION++The merge operation follows a strict order designed for fail-fast execution:++1. Validate branches+ Verifies current branch exists (not detached HEAD)+```++**Observations:**+- `##` removed (good)+- `**bold**` markers removed (good)+- But no visual styling/colors (problem)+- Text is clean and readable (acceptable fallback)++## Next Steps / Potential Solutions++### Option A: Investigate termimad internals deeply+- Read termimad source code line-by-line+- Find TTY detection mechanism+- Attempt to override or bypass it+- Possibly submit PR to termimad for `force_colors` API++**Pros:** Uses intended library, clean solution if we find it+**Cons:** Time-consuming, might not find solution++### Option B: Switch to manual ANSI with anstyle+- Write simple markdown parser+- Use `anstyle` (already in dependencies) to add colors+- Full control over output++**Pros:** Complete control, known to work with our stack+**Cons:** Reimplementing markdown parsing, maintenance burden++### Option C: Use different markdown library+- Research alternatives (see Question 8)+- Test if they handle non-TTY better+- Integrate new library++**Pros:** Might "just work", less custom code+**Cons:** Unknown compatibility, learning curve++### Option D: Accept plain text markdown+- Keep current implementation (markdown processed but not colored)+- Output is actually quite readable+- Revisit when termimad adds force-colors API++**Pros:** No additional work, acceptable UX+**Cons:** Doesn't achieve original goal of colored help++## Critical Information for Research Tool++**We need to know:**++1. **How to force termimad/crossterm to output ANSI codes even when stdout is not a TTY**+ - Is there an API we missed?+ - Is there an environment variable?+ - Is there a workaround or hack?++2. **Whether other projects have solved this exact problem**+ - CLI tools using termimad + pager+ - How do they render colored markdown before piping to pager?++3. **Whether termimad is the right tool for this use case**+ - Maybe it's designed only for direct terminal output+ - Maybe we need a different library++4. **The exact mechanism termimad uses for color detection**+ - Source code examination+ - So we can override it++**If the research tool can provide:**+- Code examples showing termimad outputting ANSI to non-TTY+- Links to projects solving this problem+- Explanation of termimad's color detection mechanism+- Alternative library recommendations with evidence they work for our use case++Then we can move forward with confidence.++## Environment Details++- **Rust version:** 1.83 (2024 edition)+- **termimad version:** 0.34+- **crossterm version:** (via termimad, not direct dependency)+- **OS:** macOS (Darwin 25.0.0)+- **Terminal:** Tested with cargo run (which might not provide TTY)+- **Target use case:** CLI help piped through pager (less -R)++## Additional Context++This is part of a larger effort to improve CLI help readability. We previously attempted to use `clap-help` but discovered it doesn't support subcommands. The current termimad approach was recommended as a way to:+- Render markdown ourselves with termimad+- Feed ANSI-styled strings back to clap's `StyledStr`+- Let clap handle the rest of help generation++The approach is architecturally sound, but we're stuck on the "render markdown to ANSI" step because termimad appears to require TTY for color output.diff --git a/src/cli.rs b/src/cli.rsindex 79a3cba44..31f205f86 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -329,7 +329,7 @@ Docs: https://llm.datasette.io/ | https://github.com/sigoden/aichat},/// List worktrees and optionally branches- #[command(after_help = "## OPERATION+ #[command(after_long_help = "## OPERATIONDisplays worktrees in a table format with status information, commit details, and optional branch listings.@@ -453,7 +453,7 @@ Use `--format=json` for structured data. The `status_symbols` field contains two},/// Switch to a worktree- #[command(after_help = r#"## OPERATION+ #[command(after_long_help = r#"## OPERATION**Switching to Existing Worktree:**- If worktree exists for branch, changes directory via shell integration@@ -552,7 +552,7 @@ wt remove @ # Remove current worktree},/// Remove worktree and branch- #[command(after_help = r#"## OPERATION+ #[command(after_long_help = r#"## OPERATION**Remove Current Worktree** (no arguments):- Requires clean working tree (no uncommitted changes)diff --git a/src/help_resolver.rs b/src/help_resolver.rsnew file mode 100644index 000000000..665868b7c--- /dev/null+++ b/src/help_resolver.rs@@ -0,0 +1,75 @@+//! Resolves which subcommand's help to display based on argv.+//!+//! Walks through command-line arguments to find the deepest matching subcommand,+//! ignoring flags and their values.++use clap::Command;++/// Walk argv and descend into subcommands; ignore flags and values+pub fn resolve_target_command(+ cmd: &mut Command,+ argv: impl IntoIterator<Item = String>,+) -> &mut Command {+ // First pass: collect subcommand path by examining argv+ let subcommand_path = extract_subcommand_path(cmd, argv);++ // Second pass: navigate to the target command+ navigate_to_command(cmd, &subcommand_path)+}++/// Extract the sequence of subcommand names from argv+fn extract_subcommand_path(+ base_cmd: &Command,+ argv: impl IntoIterator<Item = String>,+) -> Vec<String> {+ let mut it = argv.into_iter().peekable();+ let _bin = it.next(); // skip program name+ let mut path = Vec::new();+ let mut current_cmd = base_cmd;++ while let Some(tok) = it.next() {+ if tok == "-h" || tok == "--help" {+ break;+ }+ if tok.starts_with('-') {+ // skip flag + its possible value (best-effort)+ if let Some(next) = it.peek()+ && !next.starts_with('-')+ && !is_subcommand(current_cmd, next)+ {+ let _ = it.next();+ }+ continue;+ }+ // Check if this is a subcommand+ if let Some(sub) = find_subcommand(current_cmd, &tok) {+ path.push(tok);+ current_cmd = sub;+ } else {+ // Token isn't a subcommand, stop searching+ break;+ }+ }++ path+}++/// Navigate to a subcommand by following a path+fn navigate_to_command<'a>(mut cmd: &'a mut Command, path: &[String]) -> &'a mut Command {+ for name in path {+ cmd = cmd+ .find_subcommand_mut(name)+ .expect("subcommand should exist if it was in the path");+ }+ cmd+}++fn is_subcommand(cmd: &Command, name: &str) -> bool {+ cmd.get_subcommands()+ .any(|c| c.get_name() == name || c.get_visible_aliases().any(|a| a == name))+}++fn find_subcommand<'a>(cmd: &'a Command, name: &str) -> Option<&'a Command> {+ cmd.get_subcommands()+ .find(|c| c.get_name() == name || c.get_visible_aliases().any(|a| a == name))+}diff --git a/src/main.rs b/src/main.rsindex 997d4edec..248bb3575 100644--- a/src/main.rs+++ b/src/main.rs@@ -10,7 +10,9 @@ mod commands;mod completion;mod display;mod help_pager;+mod help_resolver;mod llm;+mod md_help;mod output;pub use crate::cli::OutputFormat;@@ -32,20 +34,29 @@ use cli::{Cli, Commands, ConfigCommand, StandaloneCommand, StatusAction};/// Try to handle --help flag with pager before clap processes itfn maybe_handle_help_with_pager() -> bool {+ use clap::ColorChoice;use clap::error::ErrorKind;let mut cmd = Cli::command();+ cmd = cmd.color(ColorChoice::Always); // Force clap to always emit ANSI codes++ // DON'T render markdown yet - let clap generate help first+match cmd.try_get_matches_from_mut(std::env::args()) {Ok(_) => false, // Normal args, not helpErr(err) => {match err.kind() {ErrorKind::DisplayHelp => {- // Handle help with pager- let help_text = err.to_string();- if let Err(e) = help_pager::show_help_in_pager(&help_text) {- // Pager failed, show help directly+ // Re-resolve which subcommand's help user asked for+ let target = help_resolver::resolve_target_command(&mut cmd, std::env::args());+ let mut help = target.render_long_help().to_string(); // StyledStr -> string (contains raw markdown)++ // NOW render markdown sections to ANSI+ help = md_help::render_markdown_in_help(&help);++ if let Err(e) = help_pager::show_help_in_pager(&help) {log::debug!("Pager invocation failed: {}", e);- println!("{}", err);+ eprintln!("{}", help);}process::exit(0);}@@ -65,6 +76,9 @@ fn maybe_handle_help_with_pager() -> bool {}fn main() {+ // Tell crossterm to always emit ANSI sequences+ termimad::crossterm::style::force_color_output(true);+if completion::maybe_handle_env_completion() {return;}diff --git a/src/md_help.rs b/src/md_help.rsnew file mode 100644index 000000000..5d7744772--- /dev/null+++ b/src/md_help.rs@@ -0,0 +1,71 @@+//! Markdown rendering for CLI help text using termimad.++use termimad::{MadSkin, crossterm::style::Color};++/// Render markdown in help text to ANSI with minimal styling (green headers only)+pub fn render_markdown_in_help(help: &str) -> String {+ let mut skin = MadSkin::no_style();+ skin.headers[0].set_fg(Color::Green);+ skin.headers[1].set_fg(Color::Green);++ let width = terminal_size::terminal_size()+ .map(|(w, _)| w.0 as usize)+ .unwrap_or(80);++ let rendered = format!("{}", skin.text(help, Some(width)));++ // Color the CI status circles to match their descriptions+ colorize_status_circles(&rendered)+}++/// Add colors to status symbols in help text (matching wt list output colors)+fn colorize_status_circles(text: &str) -> String {+ use anstyle::{AnsiColor, Color as AnsiStyleColor, Style};++ // Define colors matching src/commands/list/model.rs StatusSymbols::render_with_mask+ let error = Style::new().fg_color(Some(AnsiStyleColor::Ansi(AnsiColor::Red))); // ERROR+ let warning = Style::new().fg_color(Some(AnsiStyleColor::Ansi(AnsiColor::Yellow))); // WARNING+ let cyan = Style::new().fg_color(Some(AnsiStyleColor::Ansi(AnsiColor::Cyan))); // CYAN+ let dim = Style::new().dimmed(); // HINT+ let green = Style::new().fg_color(Some(AnsiStyleColor::Ansi(AnsiColor::Green)));+ let blue = Style::new().fg_color(Some(AnsiStyleColor::Ansi(AnsiColor::Blue)));+ let gray = Style::new().fg_color(Some(AnsiStyleColor::Ansi(AnsiColor::BrightBlack)));++ text+ // CI status circles+ .replace("● passed", &format!("{green}●{green:#} passed"))+ .replace("● running", &format!("{blue}●{blue:#} running"))+ .replace("● failed", &format!("{error}●{error:#} failed"))+ .replace("● conflicts", &format!("{warning}●{warning:#} conflicts"))+ .replace("● no-ci", &format!("{gray}●{gray:#} no-ci"))+ // Conflicts: = is ERROR (red), ≠ is WARNING (yellow)+ .replace(+ "= Merge conflicts",+ &format!("{error}={error:#} Merge conflicts"),+ )+ .replace(+ "≠ Potential conflicts",+ &format!("{warning}≠{warning:#} Potential conflicts"),+ )+ // Git operations: WARNING (yellow)+ .replace("↻ Rebase", &format!("{warning}↻{warning:#} Rebase"))+ .replace("⋈ Merge", &format!("{warning}⋈{warning:#} Merge"))+ // Worktree attributes: WARNING (yellow)+ .replace("⊠ Locked", &format!("{warning}⊠{warning:#} Locked"))+ .replace("⚠ Prunable", &format!("{warning}⚠{warning:#} Prunable"))+ // Branch state: HINT (dimmed)+ .replace(+ "≡ Working tree matches",+ &format!("{dim}≡{dim:#} Working tree matches"),+ )+ .replace("∅ No commits", &format!("{dim}∅{dim:#} No commits"))+ .replace("· Branch without", &format!("{dim}·{dim:#} Branch without"))+ // Main/upstream divergence: NO COLOR (plain text in actual output)+ // ↑, ↓, ↕, ⇡, ⇣, ⇅ remain uncolored+ // Working tree changes: CYAN+ .replace("? Untracked", &format!("{cyan}?{cyan:#} Untracked"))+ .replace("! Modified", &format!("{cyan}!{cyan:#} Modified"))+ .replace("+ Staged", &format!("{cyan}+{cyan:#} Staged"))+ .replace("» Renamed", &format!("{cyan}»{cyan:#} Renamed"))+ .replace("✘ Deleted", &format!("{cyan}✘{cyan:#} Deleted"))+}diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snapindex 17080d9f8..52e7e2a81 100644--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpJDGfxp/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpctSaZ5/test-config.toml---success: trueexit_code: 0@@ -289,13 +289,13 @@ complete -c wt -n "__fish_wt_using_subcommand switch" -s c -l create -d 'Createcomplete -c wt -n "__fish_wt_using_subcommand switch" -s f -l force -d 'Skip approval prompts'complete -c wt -n "__fish_wt_using_subcommand switch" -l no-verify -d 'Skip all project hooks'complete -c wt -n "__fish_wt_using_subcommand switch" -s v -l verbose -d 'Show commands and debug info'-complete -c wt -n "__fish_wt_using_subcommand switch" -s h -l help -d 'Print help'+complete -c wt -n "__fish_wt_using_subcommand switch" -s h -l help -d 'Print help (see more with \'--help\')'complete -c wt -n "__fish_wt_using_subcommand remove" -s C -d 'Change working directory' -r -Fcomplete -c wt -n "__fish_wt_using_subcommand remove" -l no-delete-branch -d 'Keep branch after removal'complete -c wt -n "__fish_wt_using_subcommand remove" -s D -l force-delete -d 'Delete unmerged branches'complete -c wt -n "__fish_wt_using_subcommand remove" -l no-background -d 'Run removal in foreground'complete -c wt -n "__fish_wt_using_subcommand remove" -s v -l verbose -d 'Show commands and debug info'-complete -c wt -n "__fish_wt_using_subcommand remove" -s h -l help -d 'Print help'+complete -c wt -n "__fish_wt_using_subcommand remove" -s h -l help -d 'Print help (see more with \'--help\')'complete -c wt -n "__fish_wt_using_subcommand merge" -s C -d 'Change working directory' -r -Fcomplete -c wt -n "__fish_wt_using_subcommand merge" -l no-squash -d 'Skip commit squashing'complete -c wt -n "__fish_wt_using_subcommand merge" -l no-commit -d 'Skip commit, squash, and rebase'diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snapindex 58aba61e2..a7943d925 100644--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpnXjgUA/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpcZNo1a/test-config.toml---success: trueexit_code: 0@@ -429,8 +429,8 @@ _arguments "${_arguments_options[@]}" : \'--no-verify[Skip all project hooks]' \'-v[Show commands and debug info]' \'--verbose[Show commands and debug info]' \-'-h[Print help]' \-'--help[Print help]' \+'-h[Print help (see more with '\''--help'\'')]' \+'--help[Print help (see more with '\''--help'\'')]' \':branch -- Branch, path, '\''@'\'' (HEAD), '\''-'\'' (previous), or '\''^'\'' (main):_default' \&& ret=0;;@@ -443,8 +443,8 @@ _arguments "${_arguments_options[@]}" : \'--no-background[Run removal in foreground]' \'-v[Show commands and debug info]' \'--verbose[Show commands and debug info]' \-'-h[Print help]' \-'--help[Print help]' \+'-h[Print help (see more with '\''--help'\'')]' \+'--help[Print help (see more with '\''--help'\'')]' \'*::worktrees -- Worktree or branch (@ for current):_default' \&& ret=0;;