worktrunk 0.36.0

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! Minimal markdown rendering for CLI help text.

use anstyle::{AnsiColor, Color, Color as AnsiStyleColor, Style};
use crossterm::style::Attribute;
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,
};

/// Table border style matching our help text format:
/// - Horizontal lines under headers with spaces between column segments
/// - No vertical borders
static HELP_TABLE_BORDERS: TableBorderChars = TableBorderChars {
    horizontal: '',
    vertical: ' ',
    top_left_corner: ' ',
    top_right_corner: ' ',
    bottom_right_corner: ' ',
    bottom_left_corner: ' ',
    top_junction: ' ',
    right_junction: ' ',
    bottom_junction: ' ',
    left_junction: ' ',
    cross: ' ', // Space at intersections gives separate line segments
};

/// Create a termimad skin for help text tables
fn help_table_skin() -> MadSkin {
    let mut skin = MadSkin::no_style();
    skin.table_border_chars = &HELP_TABLE_BORDERS;
    // Render backtick-enclosed text as dimmed, matching render_inline_formatting().
    // This is needed for colorize_status_symbols() to find and recolor symbols
    // like `●` that appear in table cells.
    skin.inline_code = CompoundStyle::with_attr(Attribute::Dim);
    skin
}

/// Render markdown in help text to ANSI with minimal styling (green headers only)
///
/// If `width` is provided, prose text is wrapped to that width. Tables, code blocks,
/// and headers are never wrapped (tables need full-width rows for alignment).
pub(crate) fn render_markdown_in_help_with_width(help: &str, width: Option<usize>) -> String {
    let green = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green)));

    let mut result = String::new();
    let mut in_code_block = false;
    let mut code_block_lang = String::new();
    let mut code_block_lines: Vec<&str> = Vec::new();
    let mut table_lines: Vec<&str> = Vec::new();

    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)
        if trimmed.starts_with("<!--") && trimmed.ends_with("-->") {
            i += 1;
            continue;
        }

        // Handle code fences
        if let Some(after_fence) = trimmed.strip_prefix("```") {
            if !in_code_block {
                // Opening fence — extract language identifier
                code_block_lang = after_fence.trim().to_string();
                code_block_lines.clear();
                in_code_block = true;
            } else {
                // Closing fence — render collected code block with gutter
                let content = code_block_lines.join("\n");
                let formatted = match code_block_lang.as_str() {
                    "toml" => format_toml(&content),
                    "console" => {
                        // Strip `$ ` prompt from console blocks for copy-paste.
                        // The prefix is preserved in source for web docs.
                        let stripped = content
                            .lines()
                            .map(|l| l.strip_prefix("$ ").unwrap_or(l))
                            .collect::<Vec<_>>()
                            .join("\n");
                        format_bash_with_gutter(&stripped)
                    }
                    "bash" | "sh" => format_bash_with_gutter(&content),
                    _ => {
                        // Dim the content before adding gutter (format_with_gutter
                        // doesn't style text; bash/toml formatters handle their own)
                        let dim = Style::new().dimmed();
                        let dimmed = code_block_lines
                            .iter()
                            .map(|l| format!("{dim}{l}{dim:#}"))
                            .collect::<Vec<_>>()
                            .join("\n");
                        format_with_gutter(&dimmed, None)
                    }
                };
                result.push_str(&formatted);
                result.push('\n');
                in_code_block = false;
            }
            i += 1;
            continue;
        }

        // Inside code blocks, collect lines for deferred rendering
        if in_code_block {
            code_block_lines.push(line);
            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, wrapping to fit terminal width if specified
            result.push_str(&render_table(&table_lines, width));
            continue;
        }

        // Horizontal rules (---, ***, ___) render as visible divider
        // No extra newlines - markdown source already has blank lines around ---
        //
        // TODO: We use `---` dividers instead of H1 headers because H1s break web docs
        // (pages already have a title from frontmatter). This decouples visual hierarchy
        // from heading semantics. Alternatives considered:
        // - Strip H1s during doc sync (demote to H2 for web)
        // - Treat `---` + H2 combo as "major section" (render H2 as UPPERCASE when preceded by ---)
        // - Use marker comments like `<!-- major -->` before H2
        // See git history for discussion.
        if trimmed == "---" || trimmed == "***" || trimmed == "___" {
            let dimmed = Style::new().dimmed();
            let rule_width = width.unwrap_or(40);
            let rule: String = "".repeat(rule_width);
            result.push_str(&format!("{dimmed}{rule}{dimmed:#}\n"));
            i += 1;
            continue;
        }

        // Outside code blocks, render markdown headers (never wrapped)
        // Visual hierarchy: H1 > H2 > H3 > H4
        // - H1: UPPERCASE green (most prominent, rarely used)
        // - H2: Bold green (major sections like "Examples", "Columns")
        // - H3: Normal green (subsections like "CI status", "commit object")
        // - H4: Bold (nested subsections like "Commit template")
        if let Some(header_text) = trimmed.strip_prefix("#### ") {
            let bold = Style::new().bold();
            result.push_str(&format!("{bold}{header_text}{bold:#}\n"));
        } else if let Some(header_text) = trimmed.strip_prefix("### ") {
            result.push_str(&format!("{green}{header_text}{green:#}\n"));
        } else if let Some(header_text) = trimmed.strip_prefix("## ") {
            let bold_green = Style::new()
                .bold()
                .fg_color(Some(Color::Ansi(AnsiColor::Green)));
            result.push_str(&format!("{bold_green}{header_text}{bold_green:#}\n"));
        } else if let Some(header_text) = trimmed.strip_prefix("# ") {
            result.push_str(&format!("{green}{}{green:#}\n", header_text.to_uppercase()));
        } else {
            // Prose text - wrap if width is specified
            let formatted = render_inline_formatting(line);
            if let Some(w) = width {
                // wrap_styled_text preserves leading indentation on continuation lines
                for wrapped_line in wrap_styled_text(&formatted, w) {
                    result.push_str(&wrapped_line);
                    result.push('\n');
                }
            } else {
                result.push_str(&formatted);
                result.push('\n');
            }
        }
        i += 1;
    }

    // Color status symbols to match their descriptions
    colorize_status_symbols(&result)
}

/// Render a markdown table using termimad (for help text, no indent)
fn render_table(lines: &[&str], max_width: Option<usize>) -> String {
    render_table_with_termimad(lines, "", max_width)
}

/// Render a table from headers and rows using termimad.
///
/// Column widths are computed by termimad based on content.
pub(crate) fn render_data_table(headers: &[&str], rows: &[Vec<String>]) -> String {
    let header_line = format!("| {} |", headers.join(" | "));
    let separator = format!("|{}|", vec!["---"; headers.len()].join("|"));
    let row_lines: Vec<String> = rows
        .iter()
        .map(|row| format!("| {} |", row.join(" | ")))
        .collect();

    let mut lines: Vec<&str> = Vec::with_capacity(rows.len() + 2);
    lines.push(&header_line);
    lines.push(&separator);
    lines.extend(row_lines.iter().map(|s| s.as_str()));

    render_table_with_termimad(&lines, "", None)
}

/// Render a markdown table using termimad
///
/// Termimad handles column width calculation, cell wrapping, and alignment.
fn render_table_with_termimad(lines: &[&str], indent: &str, max_width: Option<usize>) -> String {
    if lines.is_empty() {
        return String::new();
    }

    // Preprocess lines to strip markdown links and unescape pipes
    // (termimad doesn't handle either)
    let processed: Vec<String> = lines
        .iter()
        .map(|line| unescape_table_pipes(&strip_markdown_links(line)))
        .collect();
    let markdown = processed.join("\n");

    // Determine width for termimad (subtract indent)
    let width = max_width
        .map(|w| w.saturating_sub(indent.width()))
        .unwrap_or(DEFAULT_HELP_WIDTH);

    let skin = help_table_skin();
    let rendered = skin.text(&markdown, Some(width)).to_string();

    // Add indent to each line
    if indent.is_empty() {
        rendered
    } else {
        rendered
            .lines()
            .map(|line| format!("{indent}{line}"))
            .collect::<Vec<_>>()
            .join("\n")
            + "\n"
    }
}

/// Unescape pipe characters in markdown table cells: `\|` -> `|`
///
/// In markdown tables, `|` is the column delimiter. To include a literal pipe
/// character inside a cell, you escape it as `\|`. Termimad doesn't handle this
/// escape sequence, so we preprocess it.
fn unescape_table_pipes(line: &str) -> String {
    line.replace(r"\|", "|")
}

/// Strip markdown links, keeping only the link text: `[text](url)` -> `text`
///
/// Limitation: Links in clap help text may be broken across lines by clap's wrapping
/// before this function runs. The simple fix (setting `cmd.term_width(0)` to disable
/// clap's wrapping) doesn't work because clap provides proper indentation for option
/// description continuation lines — our `wrap_styled_text` would lose this alignment.
///
/// To support arbitrary markdown links in `--help`, we'd need to split help output at
/// `find_after_help_start()`, keep clap's wrapped Options section, get raw after_long_help
/// via `cmd.get_after_long_help()`, process it ourselves, then combine. This requires
/// restructuring since `cmd` is consumed by `try_get_matches_from_mut`.
///
/// Current workaround: Use plain URLs in cli.rs (terminals auto-link `https://...`),
/// transform to markdown links for web docs in `post_process_for_html()`.
fn strip_markdown_links(line: &str) -> String {
    let mut result = String::new();
    let mut chars = line.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '[' {
            // Potential markdown link
            let mut link_text = String::new();
            let mut found_close = false;
            let mut bracket_depth = 0;

            for c in chars.by_ref() {
                if c == '[' {
                    bracket_depth += 1;
                    link_text.push(c);
                } else if c == ']' {
                    if bracket_depth == 0 {
                        found_close = true;
                        break;
                    }
                    bracket_depth -= 1;
                    link_text.push(c);
                } else {
                    link_text.push(c);
                }
            }

            if found_close && chars.peek() == Some(&'(') {
                chars.next(); // consume '('
                // Skip URL until closing ')'
                for c in chars.by_ref() {
                    if c == ')' {
                        break;
                    }
                }
                // Output just the link text
                result.push_str(&link_text);
            } else {
                // Not a valid link, output literally
                result.push('[');
                result.push_str(&link_text);
                if found_close {
                    result.push(']');
                }
            }
        } else {
            result.push(ch);
        }
    }

    result
}

/// Render inline markdown formatting (bold, inline code, links)
fn render_inline_formatting(line: &str) -> String {
    // First strip links, preserving link text (which may contain bold/code)
    let line = strip_markdown_links(line);

    let bold = Style::new().bold();
    let code = Style::new().dimmed();

    let mut result = String::new();
    let mut chars = line.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '`' {
            // Inline code
            let mut code_content = String::new();
            for c in chars.by_ref() {
                if c == '`' {
                    break;
                }
                code_content.push(c);
            }
            result.push_str(&format!("{code}{code_content}{code:#}"));
        } else if ch == '*' && chars.peek() == Some(&'*') {
            // Bold
            chars.next(); // consume second *
            let mut bold_content = String::new();
            while let Some(c) = chars.next() {
                if c == '*' && chars.peek() == Some(&'*') {
                    chars.next(); // consume closing **
                    break;
                }
                bold_content.push(c);
            }
            // Recursively process inline formatting within bold content
            let processed_content = render_inline_formatting(&bold_content);
            result.push_str(&format!("{bold}{processed_content}{bold:#}"));
        } else {
            result.push(ch);
        }
    }

    result
}

/// Add colors to status symbols in help text (matching wt list output colors)
fn colorize_status_symbols(text: &str) -> String {
    // Define semantic styles matching src/commands/list/model.rs StatusSymbols::styled_symbols
    let error = Style::new().fg_color(Some(AnsiStyleColor::Ansi(AnsiColor::Red)));
    let warning = Style::new().fg_color(Some(AnsiStyleColor::Ansi(AnsiColor::Yellow)));
    let success = Style::new().fg_color(Some(AnsiStyleColor::Ansi(AnsiColor::Green)));
    let progress = Style::new().fg_color(Some(AnsiStyleColor::Ansi(AnsiColor::Blue)));
    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 dim = Style::new().dimmed();

    // Helper to create dimmed symbol pattern and its colored replacement
    let replace_dim = |text: String, sym: &str, style: Style| -> String {
        let dimmed = format!("{dim}{sym}{dim:#}");
        let colored = format!("{style}{sym}{style:#}");
        text.replace(&dimmed, &colored)
    };

    let mut result = text.to_string();

    // Working tree symbols: CYAN
    result = replace_dim(result, "+", working_tree);
    result = replace_dim(result, "!", working_tree);
    result = replace_dim(result, "?", working_tree);

    // Conflicts: ERROR (red)
    result = replace_dim(result, "", error);

    // Git operations, MergeTreeConflicts: WARNING (yellow)
    result = replace_dim(result, "", warning);
    result = replace_dim(result, "", warning);
    result = replace_dim(result, "", warning);

    // Worktree state: BranchWorktreeMismatch (red), Prunable/Locked (yellow)
    result = replace_dim(result, "", error);
    result = replace_dim(result, "", warning);
    result = replace_dim(result, "", warning);

    // CI status circles: replace dimmed ● followed by color name
    let dimmed_bullet = format!("{dim}{dim:#}");
    result = result
        .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"),
        )
        // CI error indicator: ⚠ symbol (also rendered dimmed initially)
        .replace(
            &format!("{dim}{dim:#} yellow"),
            &format!("{warning}{warning:#} yellow"),
        );

    // Legacy CI status circles (for statusline format)
    result = result
        .replace("● passed", &format!("{success}{success:#} passed"))
        .replace("● running", &format!("{progress}{progress:#} running"))
        .replace("● failed", &format!("{error}{error:#} failed"))
        .replace("● conflicts", &format!("{warning}{warning:#} conflicts"))
        .replace("● no-ci", &format!("{disabled}{disabled:#} no-ci"));

    // Symbols that should remain dimmed are already dimmed from backtick rendering:
    // - Main state: _ (same commit), ⊂ (content integrated), ^, ↑, ↓, ↕
    // - Upstream divergence: |, ⇡, ⇣, ⇅
    // - Worktree state: / (branch without worktree)

    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use insta::assert_snapshot;

    /// Test helper: render markdown without prose wrapping
    fn render_markdown_in_help(help: &str) -> String {
        render_markdown_in_help_with_width(help, None)
    }

    // ============================================================================
    // strip_markdown_links / unescape_table_pipes (exact transformations)
    // ============================================================================

    #[test]
    fn test_render_inline_formatting_strips_links() {
        assert_eq!(render_inline_formatting("[text](url)"), "text");
        assert_eq!(
            render_inline_formatting("See [wt hook](@/hook.md) for details"),
            "See wt hook for details"
        );
    }

    #[test]
    fn test_render_inline_formatting_nested_brackets() {
        assert_eq!(
            render_inline_formatting("[text [with brackets]](url)"),
            "text [with brackets]"
        );
    }

    #[test]
    fn test_render_inline_formatting_multiple_links() {
        assert_eq!(render_inline_formatting("[a](b) and [c](d)"), "a and c");
    }

    #[test]
    fn test_render_inline_formatting_malformed_links() {
        // Missing URL - preserved literally
        assert_eq!(render_inline_formatting("[text]"), "[text]");
        // Unclosed bracket - preserved literally
        assert_eq!(render_inline_formatting("[text"), "[text");
        // Not followed by ( - preserved literally
        assert_eq!(render_inline_formatting("[text] more"), "[text] more");
    }

    #[test]
    fn test_render_inline_formatting_preserves_bold_and_code() {
        assert_eq!(
            render_inline_formatting("**bold** and `code`"),
            "\u{1b}[1mbold\u{1b}[0m and \u{1b}[2mcode\u{1b}[0m"
        );
    }

    #[test]
    fn test_unescape_table_pipes() {
        assert_eq!(unescape_table_pipes(r"a \| b"), "a | b");
        assert_eq!(
            unescape_table_pipes(r"\| start \| end \|"),
            "| start | end |"
        );
        assert_eq!(unescape_table_pipes("no pipes here"), "no pipes here");
        assert_eq!(unescape_table_pipes("a | b"), "a | b");
    }

    // ============================================================================
    // render_inline_formatting (ANSI styling)
    // ============================================================================

    #[test]
    fn test_render_inline_formatting_styles() {
        // Inline code
        let code = render_inline_formatting("`code`");
        assert_snapshot!(code, @"code");

        // Bold
        let bold = render_inline_formatting("**bold**");
        assert_snapshot!(bold, @"bold");

        // Nested: code inside bold
        let bold_code = render_inline_formatting("**`wt list`:**");
        assert_snapshot!(bold_code, @"wt list:");

        // Mixed formatting
        let mixed = render_inline_formatting("text `code` more **bold** end");
        assert_snapshot!(mixed, @"text code more bold end");

        // Backticks inside link text
        let link_code = render_inline_formatting("See [`wt hook`](@/hook.md) for details");
        assert_snapshot!(link_code, @"See wt hook for details");

        // Unclosed backtick
        let unclosed_code = render_inline_formatting("`unclosed");
        assert_snapshot!(unclosed_code, @"unclosed");

        // Unclosed bold
        let unclosed_bold = render_inline_formatting("**unclosed");
        assert_snapshot!(unclosed_bold, @"unclosed");
    }

    // ============================================================================
    // render_markdown_in_help
    // ============================================================================

    #[test]
    fn test_render_markdown_in_help_headers() {
        // All header levels in one snapshot to show the visual hierarchy:
        // H1: UPPERCASE green, H2: bold green, H3: green, H4: bold
        let md = "# Title\n## Section\n### Subsection\n#### Nested";
        let result = render_markdown_in_help(md);
        assert_snapshot!(result, @"
        TITLE
        Section
        Subsection
        Nested
        ");
    }

    #[test]
    fn test_render_markdown_in_help_horizontal_rule() {
        let result = render_markdown_in_help("before\n\n---\n\n## Section");
        assert_snapshot!(result, @"
        before

        ────────────────────────────────────────

        Section
        ");
    }

    #[test]
    fn test_render_markdown_in_help_console_strips_dollar() {
        // Console blocks strip `$ ` for copy-paste; web docs keep it
        let result = render_markdown_in_help("```console\n$ wt step deploy\n$ wt list\n```");
        let stripped = ansi_str::AnsiStr::ansi_strip(&result);
        assert!(
            !stripped.contains("$ "),
            "terminal output should not contain '$ ' prompt: {stripped}"
        );
        assert!(stripped.contains("wt step deploy"));
        assert!(stripped.contains("wt list"));
    }

    #[test]
    fn test_render_markdown_in_help_code_block() {
        let result = render_markdown_in_help("```\ncode here\n```\nafter");
        assert_snapshot!(result, @"
          code here
        after
        ");
    }

    #[test]
    fn test_render_markdown_in_help_toml_code_block() {
        let result = render_markdown_in_help("```toml\n[section]\nkey = \"value\"\n```\nafter");
        assert_snapshot!(result, @r#"
          [section]
          key = "value"
        after
        "#);
    }

    #[test]
    fn test_render_markdown_in_help_html_comment() {
        let result = render_markdown_in_help("<!-- comment -->\nvisible");
        assert_snapshot!(result, @"visible");
    }

    #[test]
    fn test_render_markdown_in_help_plain_text() {
        let result = render_markdown_in_help("Just plain text");
        assert_snapshot!(result, @"Just plain text");
    }

    #[test]
    fn test_render_markdown_in_help_table() {
        let result = render_markdown_in_help("| A | B |\n| - | - |\n| 1 | 2 |");
        assert_snapshot!(result, @"
         A   B  
        ─── ─── 
        1   2
        ");
    }

    // ============================================================================
    // render_data_table
    // ============================================================================

    #[test]
    fn test_render_data_table_basic() {
        let rows = vec![
            vec!["Alice".into(), "42".into()],
            vec!["Bob".into(), "7".into()],
        ];
        let result = render_data_table(&["Name", "Score"], &rows);
        assert_snapshot!(result, @"
        Name  Score 
        ───── ───── 
        Alice 42    
        Bob   7
        ");
    }

    #[test]
    fn test_render_data_table_empty_rows() {
        let result = render_data_table(&["A", "B"], &[]);
        assert_snapshot!(result, @"
         A   B  
        ─── ───
        ");
    }

    // ============================================================================
    // colorize_status_symbols
    // ============================================================================

    #[test]
    fn test_colorize_status_symbols() {
        let dim = Style::new().dimmed();

        // Working tree symbols → cyan
        let working_tree = colorize_status_symbols(&format!("{dim}+{dim:#} staged"));
        assert_snapshot!(working_tree, @"+ staged");

        // Conflicts → red
        let conflicts = colorize_status_symbols(&format!("{dim}{dim:#} conflicts"));
        assert_snapshot!(conflicts, @"✘ conflicts");

        // Git operations → yellow
        let git_ops = colorize_status_symbols(&format!("{dim}{dim:#} rebase"));
        assert_snapshot!(git_ops, @"⤴ rebase");

        // CI status: passed → green, failed → red, running → blue
        let ci_passed = colorize_status_symbols("● passed");
        assert_snapshot!(ci_passed, @"● passed");

        let ci_failed = colorize_status_symbols("● failed");
        assert_snapshot!(ci_failed, @"● failed");

        let ci_running = colorize_status_symbols("● running");
        assert_snapshot!(ci_running, @"● running");
    }

    #[test]
    fn test_colorize_status_symbols_no_change() {
        let input = "plain text here";
        let result = colorize_status_symbols(input);
        assert_eq!(result, input);
    }

    // ============================================================================
    // render_table
    // ============================================================================

    #[test]
    fn test_render_table_escaped_pipe() {
        let lines = vec![
            "| Category | Symbol | Meaning |",
            "| --- | --- | --- |",
            r"| Remote | `\|` | In sync |",
        ];
        let result = render_table(&lines, None);
        assert_snapshot!(result, @"
        Category Symbol Meaning 
        ──────── ────── ─────── 
        Remote   |      In sync
        ");
    }

    #[test]
    fn test_render_table_column_alignment() {
        let lines = vec![
            "| Short | LongerHeader |",
            "| ----- | ------------ |",
            "| A | B |",
        ];
        let result = render_table(&lines, None);
        assert_snapshot!(result, @"
        Short LongerHeader 
        ───── ──────────── 
        A     B
        ");
    }

    #[test]
    fn test_render_table_uneven_columns() {
        let lines = vec!["| A | B | C |", "| --- | --- | --- |", "| 1 | 2 |"];
        let result = render_table(&lines, None);
        assert_snapshot!(result, @"
         A   B   C  
        ─── ─── ─── 
        1   2
        ");
    }

    #[test]
    fn test_render_table_no_separator() {
        let lines = vec!["| A | B |", "| 1 | 2 |"];
        let result = render_table(&lines, None);
        assert_snapshot!(result, @"
        A   B  
        1   2
        ");
    }

    #[test]
    fn test_render_markdown_in_help_table_wrapping() {
        let help = r#"### Other environment variables

| Variable | Purpose |
|----------|---------|
| `WORKTRUNK_BIN` | Override binary path for shell wrappers (useful for testing dev builds) |
| WORKTRUNK_CONFIG_PATH | Override user config file location |
| `WORKTRUNK_MAX_CONCURRENT_COMMANDS` | Max parallel git commands (default: 32). Lower if hitting resource limits. |
| NO_COLOR | Disable colored output (standard) |
"#;
        let result = render_markdown_in_help_with_width(help, Some(80));
        assert_snapshot!(result, @"
        Other environment variables

                     Variable                                Purpose                    
         ───────────────────────────────── ──────────────────────────────────────────── 
         WORKTRUNK_BIN                     Override binary path for shell wrappers      
                                           (useful for testing dev builds)              
         WORKTRUNK_CONFIG_PATH             Override user config file location           
         WORKTRUNK_MAX_CONCURRENT_COMMANDS Max parallel git commands (default: 32).     
                                           Lower if hitting resource limits.            
         NO_COLOR                          Disable colored output (standard)
        ");
    }
}