Skip to main content

vtcode_ui/tui/ui/
shell_syntax.rs

1//! Shell syntax helpers for `• Ran` tool-call lines.
2//!
3//! Extracted from `src/agent/runloop/unified/tool_pipeline/pty_stream/segments.rs`
4//! so both live PTY rendering and the compact-activity row share one
5//! tokenizer + palette. Keeps command/args/option/keyword coloring DRY.
6
7use std::sync::Arc;
8
9use anstyle::{AnsiColor, Color as AnsiColorEnum, Effects, Style as AnsiStyle};
10use vtcode_commons::ui_protocol::{InlineSegment, InlineTextStyle, convert_style};
11
12use crate::tui::ui::syntax_highlight;
13
14pub struct ShellLineStyles {
15    pub output: Arc<InlineTextStyle>,
16    pub bullet: Arc<InlineTextStyle>,
17    pub glyph: Arc<InlineTextStyle>,
18    pub verb: Arc<InlineTextStyle>,
19    pub command: Arc<InlineTextStyle>,
20    pub args: Arc<InlineTextStyle>,
21    pub keyword: Arc<InlineTextStyle>,
22    pub variable: Arc<InlineTextStyle>,
23    pub string: Arc<InlineTextStyle>,
24    pub option: Arc<InlineTextStyle>,
25    pub truncation: Arc<InlineTextStyle>,
26    /// Structural tokens (`|`, `;`, `&&`, redirections) — muted so command
27    /// words and args carry the color hierarchy.
28    pub separator: Arc<InlineTextStyle>,
29    /// Grouped `N commands` counts — dimmed like the verb so collapsed
30    /// rows recede; the green bullet keeps the success signal.
31    pub count: Arc<InlineTextStyle>,
32}
33
34impl ShellLineStyles {
35    /// Styles derived from the process-global UI theme (used by PTY live view
36    /// when no session is available). The binary's PTY stream reuses this type.
37    pub fn new() -> Self {
38        let theme_styles = crate::theme::active_styles();
39        Self::from_ansi_styles(theme_styles.pty_output)
40    }
41
42    /// Styles derived from a session's resolved theme — preferred inside
43    /// `AppSession`/`Session` where `InlineTheme` is already available.
44    pub fn from_session(_session: &crate::tui::core_tui::app::session::AppSession) -> Self {
45        let theme_styles = crate::theme::active_styles();
46        // Body-derived tones so compact rows track theme changes
47        // (e.g. catppuccin-latte).
48        Self::from_ansi_styles(theme_styles.pty_output)
49    }
50
51    fn from_ansi_styles(pty_output: AnsiStyle) -> Self {
52        let output = Arc::new(convert_style(pty_output));
53        let magenta_bold = Arc::new(convert_style(
54            AnsiStyle::new()
55                .fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Magenta)))
56                .effects(Effects::BOLD),
57        ));
58        // Compact-row headers recede to dimmed body text (Codex-style):
59        // success rows are glanceable, failures render expanded and loud.
60        let dimmed = Arc::new(convert_style(pty_output | Effects::DIMMED));
61        let yellow = Arc::new(convert_style(AnsiStyle::new().fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Yellow)))));
62        // Args use the themed body color (opaque) instead of hardcoded dimmed
63        // white so paths/args stay legible on light themes; separators stay
64        // dimmed so command words keep the visual hierarchy.
65        let args = Arc::new(convert_style(pty_output));
66
67        Self {
68            output: Arc::clone(&output),
69            bullet: Arc::new(convert_style(AnsiStyle::new().fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Green))))),
70            glyph: Arc::clone(&output),
71            verb: Arc::clone(&dimmed),
72            command: Arc::new(convert_style(
73                AnsiStyle::new()
74                    .fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Green)))
75                    .effects(Effects::BOLD),
76            )),
77            args: Arc::clone(&args),
78            keyword: magenta_bold,
79            variable: Arc::clone(&yellow),
80            string: yellow,
81            option: Arc::new(convert_style(AnsiStyle::new().fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Red))))),
82            truncation: Arc::clone(&dimmed),
83            separator: Arc::clone(&dimmed),
84            count: dimmed,
85        }
86    }
87}
88
89impl Default for ShellLineStyles {
90    fn default() -> Self {
91        Self::new()
92    }
93}
94
95pub fn is_bash_keyword(token: &str) -> bool {
96    matches!(
97        token,
98        "if" | "then"
99            | "else"
100            | "elif"
101            | "fi"
102            | "for"
103            | "in"
104            | "do"
105            | "done"
106            | "while"
107            | "until"
108            | "case"
109            | "esac"
110            | "function"
111            | "select"
112            | "time"
113            | "coproc"
114            | "{"
115            | "}"
116            | "[["
117            | "]]"
118    )
119}
120
121pub fn is_command_separator(token: &str) -> bool {
122    matches!(token, "|" | "||" | "&&" | ";" | ";;" | "&")
123}
124
125/// Redirection operators, including fd-prefixed and target-attached forms:
126/// `>`, `>>`, `2>`, `2>&1`, `2>/dev/null`, `<`, `<<`.
127fn is_redirection_token(token: &str) -> bool {
128    let body = token.trim_start_matches(|c: char| c.is_ascii_digit());
129    body.starts_with('>') || body.starts_with('<')
130}
131
132pub fn tokenize_preserve_whitespace(text: &str) -> Vec<&str> {
133    let mut parts = Vec::new();
134    let mut in_single = false;
135    let mut in_double = false;
136    let mut escaped = false;
137    let mut token_start: Option<usize> = None;
138    let mut token_is_whitespace = false;
139
140    for (idx, ch) in text.char_indices() {
141        if escaped {
142            escaped = false;
143        } else if ch == '\\' && !in_single {
144            escaped = true;
145        } else if ch == '\'' && !in_double {
146            in_single.toggle();
147        } else if ch == '"' && !in_single {
148            in_double.toggle();
149        }
150
151        let is_whitespace = !in_single && !in_double && ch.is_whitespace();
152        match token_start {
153            None => {
154                token_start = Some(idx);
155                token_is_whitespace = is_whitespace;
156            }
157            Some(start) if token_is_whitespace != is_whitespace => {
158                parts.push(&text[start..idx]);
159                token_start = Some(idx);
160                token_is_whitespace = is_whitespace;
161            }
162            _ => {}
163        }
164    }
165
166    if let Some(start) = token_start {
167        parts.push(&text[start..]);
168    }
169
170    parts
171}
172
173fn style_for_token<'a>(token: &'a str, expect_command: &mut bool, styles: &'a ShellLineStyles) -> Arc<InlineTextStyle> {
174    if token.trim().is_empty() {
175        return Arc::clone(&styles.output);
176    }
177
178    if is_command_separator(token) {
179        *expect_command = true;
180        return Arc::clone(&styles.separator);
181    }
182
183    if is_redirection_token(token) {
184        *expect_command = false;
185        return Arc::clone(&styles.separator);
186    }
187
188    if token.starts_with('"') || token.starts_with('\'') || token.ends_with('"') || token.ends_with('\'') {
189        *expect_command = false;
190        return Arc::clone(&styles.string);
191    }
192
193    if token.starts_with('$') || token.contains("=$") || token.starts_with("${") {
194        *expect_command = false;
195        return Arc::clone(&styles.variable);
196    }
197
198    if token.starts_with('-') && token.len() > 1 {
199        *expect_command = false;
200        return Arc::clone(&styles.option);
201    }
202
203    if is_bash_keyword(token) {
204        *expect_command = true;
205        return Arc::clone(&styles.keyword);
206    }
207
208    if *expect_command {
209        *expect_command = false;
210        return Arc::clone(&styles.command);
211    }
212
213    Arc::clone(&styles.args)
214}
215
216/// Split trailing `;`/`&`/`|` runs off a whitespace-delimited token so
217/// attached separators (`-120;`, `'---';`) color as separators instead of
218/// inheriting the word's option/string style. Redirections (`2>/dev/null`,
219/// `2>&1`) end in word characters and are left intact.
220fn split_trailing_command_operators(token: &str) -> Vec<&str> {
221    let bytes = token.as_bytes();
222    let mut end = bytes.len();
223    while end > 0 && matches!(bytes[end - 1], b';' | b'&' | b'|') {
224        end -= 1;
225    }
226    if end == 0 || end == bytes.len() {
227        return vec![token];
228    }
229    vec![&token[..end], &token[end..]]
230}
231
232fn bash_segments(text: &str, styles: &ShellLineStyles, expect_command: bool) -> Vec<InlineSegment> {
233    let mut segments = Vec::new();
234    let mut command_expected = expect_command;
235    for token in tokenize_preserve_whitespace(text) {
236        if token.trim().is_empty() {
237            segments.push(InlineSegment {
238                text: token.to_string(),
239                style: Arc::clone(&styles.output),
240            });
241            continue;
242        }
243        for part in split_trailing_command_operators(token) {
244            segments.push(InlineSegment {
245                text: part.to_string(),
246                style: style_for_token(part, &mut command_expected, styles),
247            });
248        }
249    }
250    segments
251}
252
253pub fn shell_syntax_segments(text: &str, styles: &ShellLineStyles, expect_command: bool) -> Vec<InlineSegment> {
254    let highlighted = syntax_highlight::highlight_line_to_anstyle_segments(
255        text,
256        Some("bash"),
257        syntax_highlight::get_active_syntax_theme(),
258        true,
259    );
260    shell_syntax_segments_with_highlighted(text, styles, expect_command, highlighted)
261}
262
263/// Prefer shell syntax highlighting only when it keeps token colors distinct.
264///
265/// A handful of syntax themes return one foreground color for a shell line.
266/// In that case the semantic tokenizer provides more useful command, option,
267/// and argument styling than accepting the uniform highlighter result.
268pub(crate) fn shell_syntax_segments_with_highlighted(
269    text: &str,
270    styles: &ShellLineStyles,
271    expect_command: bool,
272    highlighted: Option<Vec<(AnsiStyle, String)>>,
273) -> Vec<InlineSegment> {
274    let semantic = bash_segments(text, styles, expect_command);
275    let Some(highlighted) = highlighted else {
276        return semantic;
277    };
278
279    if highlighted.is_empty() {
280        return semantic;
281    }
282
283    let converted = highlighted
284        .into_iter()
285        .map(|(style, text)| InlineSegment {
286            text,
287            style: Arc::new(convert_style(style).merge_color(styles.args.color)),
288        })
289        .collect::<Vec<_>>();
290
291    let converted_text = converted.iter().map(|segment| segment.text.as_str()).collect::<String>();
292    if converted_text != text {
293        return semantic;
294    }
295
296    let non_ws_count = semantic.iter().filter(|segment| !segment.text.trim().is_empty()).count();
297    if non_ws_count > 1 {
298        let mut first_colors: Option<(Option<AnsiColorEnum>, Option<AnsiColorEnum>)> = None;
299        let mut has_distinct = false;
300        for style in converted
301            .iter()
302            .filter(|segment| !segment.text.trim().is_empty())
303            .map(|segment| segment.style.as_ref())
304        {
305            let colors = (style.color, style.bg_color);
306            if let Some(seed) = first_colors {
307                if colors != seed {
308                    has_distinct = true;
309                    break;
310                }
311            } else {
312                first_colors = Some(colors);
313            }
314        }
315        if !has_distinct {
316            return semantic;
317        }
318    }
319
320    converted
321}
322
323pub fn line_to_compact_segments(
324    metadata: &vtcode_commons::ui_protocol::CompactActivityMetadata,
325    styles: &ShellLineStyles,
326) -> Vec<InlineSegment> {
327    // • Ran N command(s): one count form for single and grouped rows.
328    let mut segments = Vec::new();
329    segments.push(InlineSegment {
330        text: "• ".to_string(),
331        style: Arc::clone(&styles.bullet),
332    });
333    segments.push(InlineSegment {
334        text: "Ran".to_string(),
335        style: Arc::clone(&styles.verb),
336    });
337    segments.push(InlineSegment {
338        text: " ".to_string(),
339        style: Arc::clone(&styles.output),
340    });
341
342    // One count form for single and grouped rows alike, dimmed with the
343    // verb so success rows recede. Must stay byte-identical with
344    // `display_text`.
345    let noun = if metadata.command_count == 1 {
346        "command"
347    } else {
348        "commands"
349    };
350    segments.push(InlineSegment {
351        text: format!("{} {noun}", metadata.command_count),
352        style: Arc::clone(&styles.count),
353    });
354    if metadata.hidden_line_count > 0 {
355        segments.push(InlineSegment {
356            text: format!(" · … +{} lines", metadata.hidden_line_count),
357            style: Arc::clone(&styles.truncation),
358        });
359    }
360
361    if let Some(suffix) = metadata.suffix.as_deref().filter(|s| !s.is_empty()) {
362        segments.push(InlineSegment {
363            text: " · ".to_string(),
364            style: Arc::clone(&styles.truncation),
365        });
366        segments.push(InlineSegment {
367            text: suffix.to_string(),
368            style: Arc::clone(&styles.truncation),
369        });
370    }
371
372    segments
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    #[test]
380    fn command_header_preserves_distinct_semantic_token_colors() {
381        let styles = ShellLineStyles::new();
382        let segments =
383            shell_syntax_segments("find src/agent/runloop -maxdepth 3 -type f -name *.rs | sort", &styles, true);
384        let option = segments
385            .iter()
386            .find(|segment| segment.text.contains("maxdepth"))
387            .expect("option token");
388        let command = segments
389            .iter()
390            .find(|segment| segment.text.contains("find"))
391            .expect("command token");
392        assert_ne!(option.style.color, command.style.color);
393    }
394
395    #[test]
396    fn single_command_row_uses_count_form_like_grouped_rows() {
397        // Compact rows render one count form for one or many commands; the
398        // full pipeline stays in the review capture behind the row.
399        let styles = ShellLineStyles::new();
400        let meta = vtcode_commons::ui_protocol::CompactActivityMetadata {
401            group_id: 1,
402            command_count: 1,
403            command: Some("grep -rn pattern docs | grep -v node_modules".into()),
404            hidden_line_count: 0,
405            suffix: None,
406            review_anchor: None,
407            review_anchors: vec![],
408        };
409        let segs = line_to_compact_segments(&meta, &styles);
410        let text: String = segs.iter().map(|s| s.text.as_str()).collect();
411        assert_eq!(text, "• Ran 1 command");
412        assert_eq!(text, meta.display_text(), "segments must match display_text");
413        // Asymmetric: the plural form keeps working.
414        let meta = vtcode_commons::ui_protocol::CompactActivityMetadata { command_count: 4, command: None, ..meta };
415        let text: String = line_to_compact_segments(&meta, &styles)
416            .iter()
417            .map(|s| s.text.as_str())
418            .collect();
419        assert_eq!(text, "• Ran 4 commands");
420        assert_eq!(text, meta.display_text(), "segments must match display_text");
421    }
422
423    #[test]
424    fn compact_row_count_form_carries_hidden_lines_and_suffix() {
425        let styles = ShellLineStyles::new();
426        let meta = vtcode_commons::ui_protocol::CompactActivityMetadata {
427            group_id: 1,
428            command_count: 1,
429            command: Some("cargo check".into()),
430            hidden_line_count: 3,
431            suffix: Some("output retained".into()),
432            review_anchor: Some(7),
433            review_anchors: vec![7],
434        };
435        let text: String = line_to_compact_segments(&meta, &styles)
436            .iter()
437            .map(|s| s.text.as_str())
438            .collect();
439        assert_eq!(text, "• Ran 1 command · … +3 lines · output retained");
440        assert_eq!(text, meta.display_text(), "segments must match display_text");
441    }
442
443    #[test]
444    fn grouped_has_no_single_command_highlight() {
445        let styles = ShellLineStyles::new();
446        let meta = vtcode_commons::ui_protocol::CompactActivityMetadata {
447            group_id: 1,
448            command_count: 4,
449            command: None,
450            hidden_line_count: 10,
451            suffix: Some("output retained".into()),
452            review_anchor: Some(1),
453            review_anchors: vec![1],
454        };
455        let segs = line_to_compact_segments(&meta, &styles);
456        let text: String = segs.iter().map(|s| s.text.as_str()).collect();
457        assert!(text.contains("4 commands"));
458        assert!(text.contains("output retained"));
459    }
460
461    #[test]
462    fn grouped_headers_stay_dimmed_with_a_green_bullet() {
463        let styles = ShellLineStyles::new();
464        for style in [&styles.count, &styles.verb] {
465            assert!(style.effects.contains(Effects::DIMMED), "headers recede");
466            assert!(!style.effects.contains(Effects::BOLD), "headers never shout");
467        }
468        assert_eq!(styles.bullet.color, styles.command.color, "success keeps its green signal");
469        assert!(!styles.bullet.effects.contains(Effects::DIMMED), "the signal stays vivid");
470    }
471
472    #[test]
473    fn args_use_themed_body_color_for_light_theme_legibility() {
474        let styles = ShellLineStyles::new();
475        assert_eq!(styles.args.color, styles.output.color);
476    }
477
478    #[test]
479    fn attached_separator_splits_from_word_style() {
480        let styles = ShellLineStyles::new();
481        let segments = bash_segments("head -120; echo hi", &styles, true);
482        let option = segments.iter().find(|s| s.text == "-120").expect("option part");
483        let separator = segments.iter().find(|s| s.text == ";").expect("separator part");
484        assert_eq!(option.style.color, styles.option.color);
485        assert_eq!(separator.style.color, styles.separator.color);
486        assert!(separator.style.effects.contains(Effects::DIMMED));
487    }
488
489    #[test]
490    fn uniform_syntax_highlighting_uses_semantic_fallback() {
491        let styles = ShellLineStyles::new();
492        let highlighted_style = AnsiStyle::new().fg_color(Some(AnsiColorEnum::Ansi(AnsiColor::Cyan)));
493        let highlighted = ["cargo", " ", "check", " ", "-p", " ", "vtcode"]
494            .into_iter()
495            .map(|text| (highlighted_style, text.to_string()))
496            .collect();
497
498        let segments =
499            shell_syntax_segments_with_highlighted("cargo check -p vtcode", &styles, true, Some(highlighted));
500        let command = segments.iter().find(|segment| segment.text == "cargo").expect("command token");
501        let option = segments.iter().find(|segment| segment.text == "-p").expect("option token");
502
503        assert_eq!(command.style.color, styles.command.color);
504        assert_eq!(option.style.color, styles.option.color);
505        assert_ne!(command.style.color, option.style.color);
506    }
507}