Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Render markdown tables in help text with proper alignment
Maximilian Roos8d5a3b3db4d6
diff --git a/docs/content/list.md b/docs/content/list.mdindex d13bdc004..720d22581 100644--- a/docs/content/list.md+++ b/docs/content/list.md@@ -95,7 +95,7 @@ The CI column shows GitHub/GitLab pipeline status:| <span style='color:#a00'>●</span> red | Checks failed || <span style='color:#a60'>●</span> yellow | Merge conflicts with base || <span style='color:#888'>●</span> gray | No checks configured |-| blank | No PR/MR found |+| (blank) | No PR/MR found |Any CI dot appears dimmed when there are unpushed local changes (stale status). CI indicators are clickable links to the PR page.diff --git a/src/cli.rs b/src/cli.rsindex fca403d94..0a9ebbc35 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -1028,7 +1028,7 @@ The CI column shows GitHub/GitLab pipeline status:| `●` red | Checks failed || `●` yellow | Merge conflicts with base || `●` gray | No checks configured |-| blank | No PR/MR found |+| (blank) | No PR/MR found |Any CI dot appears dimmed when there are unpushed local changes (stale status). CI indicators are clickable links to the PR page.diff --git a/src/md_help.rs b/src/md_help.rsindex 9bb41f681..6a419899c 100644--- a/src/md_help.rs+++ b/src/md_help.rs@@ -1,6 +1,7 @@//! Minimal markdown rendering for CLI help text.use anstyle::{AnsiColor, Color, Style};+use unicode_width::UnicodeWidthStr;/// Render markdown in help text to ANSI with minimal styling (green headers only)pub fn render_markdown_in_help(help: &str) -> String {@@ -9,32 +10,55 @@ pub fn render_markdown_in_help(help: &str) -> String {let mut result = String::new();let mut in_code_block = false;+ let mut table_lines: Vec<&str> = Vec::new();- for line in help.lines() {+ let lines: Vec<&str> = help.lines().collect();+ let mut i = 0;++ while i < lines.len() {+ let line = lines[i];let trimmed = line.trim_start();// Skip HTML comments (expansion markers for web docs, see readme_sync.rs)- // Only matches single-line comments; multi-line would span multiple iterationsif trimmed.starts_with("<!--") && trimmed.ends_with("-->") {+ i += 1;continue;}// Track code block stateif trimmed.starts_with("```") {in_code_block = !in_code_block;- // Skip the fence markers themselves+ i += 1;continue;}// Inside code blocks, render dimmed with indentif in_code_block {result.push_str(&format!(" {dimmed}{line}{dimmed:#}\n"));+ i += 1;+ continue;+ }++ // Detect markdown table rows+ if trimmed.starts_with('|') && trimmed.ends_with('|') {+ // Collect all consecutive table lines+ table_lines.clear();+ while i < lines.len() {+ let tl = lines[i].trim_start();+ if tl.starts_with('|') && tl.ends_with('|') {+ table_lines.push(lines[i]);+ i += 1;+ } else {+ break;+ }+ }+ // Render the table+ result.push_str(&render_table(&table_lines));continue;}// Outside code blocks, render markdown headersif let Some(header_text) = trimmed.strip_prefix("### ") {- // Subheadings: bold (differentiated from green ## section headers)let bold = Style::new().bold();result.push_str(&format!("{bold}{header_text}{bold:#}\n"));} else if let Some(header_text) = trimmed.strip_prefix("## ") {@@ -42,17 +66,123 @@ pub fn render_markdown_in_help(help: &str) -> String {} else if let Some(header_text) = trimmed.strip_prefix("# ") {result.push_str(&format!("{green}{header_text}{green:#}\n"));} else {- // Render inline formatting (bold, inline code)let formatted = render_inline_formatting(line);result.push_str(&formatted);result.push('\n');}+ i += 1;}// Color status symbols to match their descriptionscolorize_status_symbols(&result)}+/// Render a markdown table with proper column alignment+fn render_table(lines: &[&str]) -> String {+ // Parse table cells+ let mut rows: Vec<Vec<String>> = Vec::new();+ let mut separator_idx: Option<usize> = None;++ for (idx, line) in lines.iter().enumerate() {+ let trimmed = line.trim();+ // Remove leading/trailing pipes and split+ let inner = trimmed.trim_start_matches('|').trim_end_matches('|');+ let cells: Vec<String> = inner.split('|').map(|s| s.trim().to_string()).collect();++ // Check if this is the separator row (contains only dashes and colons)+ if cells+ .iter()+ .all(|c| c.chars().all(|ch| ch == '-' || ch == ':'))+ {+ separator_idx = Some(idx);+ } else {+ rows.push(cells);+ }+ }++ if rows.is_empty() {+ return String::new();+ }++ // Calculate column widths (using display width for Unicode)+ let num_cols = rows.iter().map(|r| r.len()).max().unwrap_or(0);+ let mut col_widths: Vec<usize> = vec![0; num_cols];++ for row in &rows {+ for (i, cell) in row.iter().enumerate() {+ if i < num_cols {+ // Apply inline formatting to measure rendered width+ let formatted = render_inline_formatting(cell);+ let display_width = strip_ansi(&formatted).width();+ col_widths[i] = col_widths[i].max(display_width);+ }+ }+ }++ // Render rows+ let mut result = String::new();+ let has_header = separator_idx.is_some();++ for (row_idx, row) in rows.iter().enumerate() {+ result.push_str(" "); // Indent++ for (col_idx, cell) in row.iter().enumerate() {+ if col_idx > 0 {+ result.push_str(" "); // Column separator+ }++ let formatted = render_inline_formatting(cell);+ let display_width = strip_ansi(&formatted).width();+ let padding = col_widths+ .get(col_idx)+ .unwrap_or(&0)+ .saturating_sub(display_width);++ result.push_str(&formatted);+ for _ in 0..padding {+ result.push(' ');+ }+ }+ result.push('\n');++ // Add visual separator after header row+ if has_header && row_idx == 0 {+ result.push_str(" ");+ for (col_idx, width) in col_widths.iter().enumerate() {+ if col_idx > 0 {+ result.push_str(" ");+ }+ for _ in 0..*width {+ result.push('─');+ }+ }+ result.push('\n');+ }+ }++ result+}++/// Strip ANSI escape codes for width calculation+fn strip_ansi(s: &str) -> String {+ let mut result = String::new();+ let mut in_escape = false;++ for ch in s.chars() {+ if ch == '\x1b' {+ in_escape = true;+ } else if in_escape {+ if ch == 'm' {+ in_escape = false;+ }+ } else {+ result.push(ch);+ }+ }++ result+}+/// Render inline markdown formatting (bold, inline code, links)fn render_inline_formatting(line: &str) -> String {let bold = Style::new().bold();@@ -144,8 +274,35 @@ fn colorize_status_symbols(text: &str) -> String {let disabled = Style::new().fg_color(Some(AnsiStyleColor::Ansi(AnsiColor::BrightBlack)));let working_tree = Style::new().fg_color(Some(AnsiStyleColor::Ansi(AnsiColor::Cyan)));+ // Pattern for dimmed text (from inline `code` rendering)+ // render_inline_formatting wraps backticked text in dimmed style+ let code_style = Style::new().dimmed();+ let dimmed_bullet = format!("{code_style}●{code_style:#}");+text- // CI status circles+ // CI status circles in table format: `●` green → colored ● green+ // The backticks are converted to dimmed styling by render_inline_formatting first+ .replace(+ &format!("{dimmed_bullet} green"),+ &format!("{success}●{success:#} green"),+ )+ .replace(+ &format!("{dimmed_bullet} blue"),+ &format!("{progress}●{progress:#} blue"),+ )+ .replace(+ &format!("{dimmed_bullet} red"),+ &format!("{error}●{error:#} red"),+ )+ .replace(+ &format!("{dimmed_bullet} yellow"),+ &format!("{warning}●{warning:#} yellow"),+ )+ .replace(+ &format!("{dimmed_bullet} gray"),+ &format!("{disabled}●{disabled:#} gray"),+ )+ // Legacy CI status circles (for statusline format).replace("● passed", &format!("{success}●{success:#} passed")).replace("● running", &format!("{progress}●{progress:#} running")).replace("● failed", &format!("{error}●{error:#} failed"))diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snapindex 430c371ba..99990edf6 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap@@ -46,10 +46,10 @@ Manages configuration, shell integration, and runtime settings.Worktrunk uses two configuration files:-| File | Location | Purpose |-|------|----------|---------|-| [1mUser config[0m | [2m~/.config/worktrunk/config.toml[0m | Personal settings, command defaults, approved project commands |-| [1mProject config[0m | [2m.config/wt.toml[0m | Lifecycle hooks, checked into version control |+ File Location Purpose+ ────────────── ─────────────────────────────── ──────────────────────────────────────────────────────────────+ [1mUser config[0m [2m~/.config/worktrunk/config.toml[0m Personal settings, command defaults, approved project commands+ [1mProject config[0m [2m.config/wt.toml[0m Lifecycle hooks, checked into version control[32mExamples[0m@@ -182,11 +182,11 @@ Config keys use kebab-case ([2mworktree-path[0m), while env vars use SCREAMINGFor nested config sections, use double underscores to separate levels:-| Config | Environment Variable |-|--------|---------------------|-| [2mworktree-path[0m | [2mWORKTRUNK_WORKTREE_PATH[0m |-| [2mcommit-generation.command[0m | [2mWORKTRUNK_COMMIT_GENERATION__COMMAND[0m |-| [2mcommit-generation.args[0m | [2mWORKTRUNK_COMMIT_GENERATION__ARGS[0m |+ Config Environment Variable+ ───────────────────────── ────────────────────────────────────+ [2mworktree-path[0m [2mWORKTRUNK_WORKTREE_PATH[0m+ [2mcommit-generation.command[0m [2mWORKTRUNK_COMMIT_GENERATION__COMMAND[0m+ [2mcommit-generation.args[0m [2mWORKTRUNK_COMMIT_GENERATION__ARGS[0mNote the single underscore after [2mWORKTRUNK[0m and double underscores between nested keys.@@ -206,8 +206,8 @@ Override the LLM command in CI to use a mock:[1mSpecial variables[0m-| Variable | Purpose |-|----------|---------|-| [2mWORKTRUNK_CONFIG_PATH[0m | Override user config file location (not a config key) |-| [2mNO_COLOR[0m | Disable colored output (standard) |-| [2mCLICOLOR_FORCE[0m | Force colored output even when not a TTY |+ Variable Purpose+ ───────────────────── ─────────────────────────────────────────────────────+ [2mWORKTRUNK_CONFIG_PATH[0m Override user config file location (not a config key)+ [2mNO_COLOR[0m Disable colored output (standard)+ [2mCLICOLOR_FORCE[0m Force colored output even when not a TTYdiff --git a/tests/snapshots/integration__integration_tests__help__help_list_long.snap b/tests/snapshots/integration__integration_tests__help__help_list_long.snapindex 629c3b4d1..fe4e644af 100644--- a/tests/snapshots/integration__integration_tests__help__help_list_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_list_long.snap@@ -81,30 +81,30 @@ Output as JSON for scripting:[32mColumns[0m-| Column | Shows |-|--------|-------|-| Branch | Branch name |-| Status | Compact symbols (see below) |-| HEAD± | Uncommitted changes: +added -deleted lines |-| main↕ | Commits ahead/behind main |-| main…± | Line diffs in commits ahead of main ([2m--full[0m) |-| Path | Worktree directory |-| Remote⇅ | Commits ahead/behind tracking branch |-| CI | Pipeline status ([2m--full[0m) |-| Commit | Short hash (8 chars) |-| Age | Time since last commit |-| Message | Last commit message (truncated) |+ Column Shows+ ─────── ────────────────────────────────────────────+ Branch Branch name+ Status Compact symbols (see below)+ HEAD± Uncommitted changes: +added -deleted lines+ main↕ Commits ahead/behind main+ main…± Line diffs in commits ahead of main ([2m--full[0m)+ Path Worktree directory+ Remote⇅ Commits ahead/behind tracking branch+ CI Pipeline status ([2m--full[0m)+ Commit Short hash (8 chars)+ Age Time since last commit+ Message Last commit message (truncated)The CI column shows GitHub/GitLab pipeline status:-| Indicator | Meaning |-|-----------|---------|-| [2m●[0m green | All checks passed |-| [2m●[0m blue | Checks running |-| [2m●[0m red | Checks failed |-| [2m●[0m yellow | Merge conflicts with base |-| [2m●[0m gray | No checks configured |-| blank | No PR/MR found |+ Indicator Meaning+ ───────── ─────────────────────────+ [32m●[0m green All checks passed+ [34m●[0m blue Checks running+ [31m●[0m red Checks failed+ [33m●[0m yellow Merge conflicts with base+ [90m●[0m gray No checks configured+ (blank) No PR/MR foundAny CI dot appears dimmed when there are unpushed local changes (stale status). CI indicators are clickable links to the PR page.@@ -112,29 +112,29 @@ Any CI dot appears dimmed when there are unpushed local changes (stale status).Symbols appear in the Status column in this order:-| Category | Symbol | Meaning |-|----------|--------|---------|-| Working tree | [2m+[0m | Staged files |-| | [2m![0m | Modified files (unstaged) |-| | [2m?[0m | Untracked files |-| | [2m✖[0m | Merge conflicts |-| | [2m↻[0m | Rebase in progress |-| | [2m⋈[0m | Merge in progress |-| Branch state | [2m⊘[0m | Would conflict if merged to main ([2m--full[0m only) |-| | [2m≡[0m | Matches main (identical contents) |-| | [2m_[0m | No commits ahead, clean working tree |-| Main divergence | [2m^[0m | Is the main branch |-| | [2m↑[0m | Ahead of main |-| | [2m↓[0m | Behind main |-| | [2m↕[0m | Diverged from main |-| Remote divergence | [2m\|[0m | In sync with remote |-| | [2m⇡[0m | Ahead of remote |-| | [2m⇣[0m | Behind remote |-| | [2m⇅[0m | Diverged from remote |-| Worktree state | [2m/[0m | Branch without worktree |-| | [2m⚑[0m | Path doesn't match template |-| | [2m⌫[0m | Prunable (directory missing) |-| | [2m⊠[0m | Locked worktree |+ Category Symbol Meaning+ ───────────────── ────── ────────────────────────────────────────────── ───────────────────+ Working tree [2m+[0m Staged files+ [2m![0m Modified files (unstaged)+ [2m?[0m Untracked files+ [2m✖[0m Merge conflicts+ [2m↻[0m Rebase in progress+ [2m⋈[0m Merge in progress+ Branch state [2m⊘[0m Would conflict if merged to main ([2m--full[0m only)+ [2m≡[0m Matches main (identical contents)+ [2m_[0m No commits ahead, clean working tree+ Main divergence [2m^[0m Is the main branch+ [2m↑[0m Ahead of main+ [2m↓[0m Behind main+ [2m↕[0m Diverged from main+ Remote divergence [2m\[0m [2m[0m In sync with remote+ [2m⇡[0m Ahead of remote+ [2m⇣[0m Behind remote+ [2m⇅[0m Diverged from remote+ Worktree state [2m/[0m Branch without worktree+ [2m⚑[0m Path doesn't match template+ [2m⌫[0m Prunable (directory missing)+ [2m⊠[0m Locked worktreeRows are dimmed when the branch content is already in main ([2m≡[0m matches main or [2m_[0m no commits ahead).diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snapindex 0bbd2521f..8d55bf38c 100644--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap@@ -96,11 +96,11 @@ With [2m--create[0m, worktrunk:[32mShortcuts[0m-| Shortcut | Meaning |-|----------|---------|-| [2m^[0m | Default branch (main/master) |-| [2m@[0m | Current branch/worktree |-| [2m-[0m | Previous worktree (like [2mcd -[0m) |+ Shortcut Meaning+ ──────── ─────────────────────────────+ [2m^[0m Default branch (main/master)+ [2m@[0m Current branch/worktree+ [2m-[0m Previous worktree (like [2mcd -[0m)[2mwt switch - # Back to previous[0m[2mwt switch ^ # Main worktree[0m