File size: 11,324 Bytes
d90101d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use nu_ansi_term::{Color, Style};

pub(crate) struct StyledText {
    pub(crate) buffer: Vec<(Style, String)>,
}

impl StyledText {
    pub fn new() -> Self {
        Self { buffer: Vec::new() }
    }

    pub fn push(&mut self, value: (Style, String)) {
        self.buffer.push(value);
    }
}

/// Syntax highlighter for the forge readline prompt.
///
/// Applies visual styles to recognised input patterns as the user types:
/// - Commands (`:foo` or `/foo` for backward compatibility) are rendered in
///   yellow bold.
/// - File mentions (`@[path]`) are rendered in cyan bold.
/// - Shell pass-through commands (`!cmd`) are rendered in magenta.
/// - All other text is rendered in the default terminal style.
pub struct ForgeHighlighter;

impl ForgeHighlighter {
    pub(crate) fn highlight(&self, line: &str, _cursor: usize) -> StyledText {
        let mut styled = StyledText::new();

        if line.is_empty() {
            return styled;
        }

        // Command: highlight the command token (e.g. `:compact` or `/compact` for
        // compat) in yellow bold, then the remainder (arguments) without
        // special styling.
        if line.starts_with('/') || line.starts_with(':') {
            let end = line.find(|c: char| c.is_whitespace()).unwrap_or(line.len());
            styled.push((
                Style::new().bold().fg(Color::Yellow),
                line.get(..end).unwrap_or(line).to_string(),
            ));
            if end < line.len()
                && let Some(args) = line.get(end..)
            {
                highlight_mentions(args, &mut styled);
            }
            return styled;
        }

        // Shell pass-through: `!<cmd>` rendered in magenta.
        if line.starts_with('!') {
            styled.push((Style::new().fg(Color::Magenta), line.to_string()));
            return styled;
        }

        // General message text — scan for `@[...]` file mentions and colour them cyan
        // bold.
        highlight_mentions(line, &mut styled);

        styled
    }
}

/// Walk through `line` and emit styled segments, colouring every `@[...]`
/// mention (matching the ZSH pattern `@\[[^]]*\]`) in cyan bold and leaving
/// surrounding text unstyled.
///
/// Mirrors `ZSH_HIGHLIGHT_PATTERNS+=('@\[[^]]#\]' 'fg=cyan,bold')` exactly:
/// - Requires `@[` opener.
/// - Matches zero or more non-`]` characters inside the brackets.
/// - Requires closing `]` — unterminated tags are left unstyled.
fn highlight_mentions(line: &str, styled: &mut StyledText) {
    let mut remaining = line;

    while !remaining.is_empty() {
        // Find the next `@[` opener.
        match remaining.find("@[") {
            None => {
                // No more mentions — emit the rest as plain text.
                styled.push((Style::new(), remaining.to_string()));
                break;
            }
            Some(start) => {
                // Emit any plain text before the `@[`.
                if start > 0
                    && let Some(before) = remaining.get(..start)
                {
                    styled.push((Style::new(), before.to_string()));
                }

                // `after_open` starts at `@[`.
                let after_open = match remaining.get(start..) {
                    Some(s) => s,
                    None => {
                        styled.push((Style::new(), remaining.to_string()));
                        break;
                    }
                };

                // Look for a `]` that is not immediately after `@[`.
                // The ZSH pattern `[^]#` matches zero-or-more non-`]` chars,
                // so `@[]` (empty brackets) also qualifies.
                // We search for `]` starting from position 2 (after `@[`).
                match after_open.get(2..).and_then(|s| s.find(']')) {
                    None => {
                        // No closing `]` — emit `@[` and the rest as plain text
                        // to match ZSH behaviour (unterminated tag = no highlight).
                        styled.push((Style::new(), after_open.to_string()));
                        break;
                    }
                    Some(rel_close) => {
                        // Absolute position of `]` within `after_open`.
                        let close = 2 + rel_close;
                        // Emit `@[...]` in cyan bold (inclusive of both brackets).
                        let mention = after_open.get(..=close).unwrap_or(after_open);
                        styled.push((Style::new().bold().fg(Color::Cyan), mention.to_string()));
                        match after_open.get(close + 1..) {
                            Some(rest) => remaining = rest,
                            None => break,
                        }
                    }
                }
            }
        }
    }
}

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

    fn render(styled: &StyledText) -> String {
        styled.buffer.iter().map(|(_, s)| s.as_str()).collect()
    }

    fn styles(styled: &StyledText) -> Vec<Style> {
        styled.buffer.iter().map(|(style, _)| *style).collect()
    }

    #[test]
    fn test_slash_command_highlighted() {
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight("/compact", 0);
        assert_eq!(render(&actual), "/compact");
        assert_eq!(styles(&actual)[0], Style::new().bold().fg(Color::Yellow));
    }

    #[test]
    fn test_colon_command_highlighted() {
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight(":compact", 0);
        assert_eq!(render(&actual), ":compact");
        assert_eq!(styles(&actual)[0], Style::new().bold().fg(Color::Yellow));
    }

    #[test]
    fn test_colon_command_with_args() {
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight(":commit some message", 0);
        let parts: Vec<_> = actual
            .buffer
            .iter()
            .map(|(s, t)| (*s, t.as_str()))
            .collect();
        assert_eq!(parts[0], (Style::new().bold().fg(Color::Yellow), ":commit"));
        assert_eq!(parts[1].1, " some message");
    }

    #[test]
    fn test_slash_command_with_args() {
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight("/commit some message", 0);
        let parts: Vec<_> = actual
            .buffer
            .iter()
            .map(|(s, t)| (*s, t.as_str()))
            .collect();
        assert_eq!(parts[0], (Style::new().bold().fg(Color::Yellow), "/commit"));
        assert_eq!(parts[1].1, " some message");
    }

    #[test]
    fn test_shell_command_highlighted() {
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight("!ls -la", 0);
        assert_eq!(render(&actual), "!ls -la");
        assert_eq!(styles(&actual)[0], Style::new().fg(Color::Magenta));
    }

    #[test]
    fn test_file_mention_highlighted() {
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight("explain @[src/main.rs] please", 0);
        let parts: Vec<_> = actual
            .buffer
            .iter()
            .map(|(s, t)| (*s, t.as_str()))
            .collect();
        assert_eq!(parts[0], (Style::new(), "explain "));
        assert_eq!(
            parts[1],
            (Style::new().bold().fg(Color::Cyan), "@[src/main.rs]")
        );
        assert_eq!(parts[2], (Style::new(), " please"));
    }

    #[test]
    fn test_multiple_file_mentions() {
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight("@[a.rs] and @[b.rs]", 0);
        let texts: Vec<_> = actual.buffer.iter().map(|(_, t)| t.as_str()).collect();
        assert_eq!(texts, vec!["@[a.rs]", " and ", "@[b.rs]"]);
        assert_eq!(actual.buffer[0].0, Style::new().bold().fg(Color::Cyan));
        assert_eq!(actual.buffer[2].0, Style::new().bold().fg(Color::Cyan));
    }

    #[test]
    fn test_plain_text_unstyled() {
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight("hello world", 0);
        assert_eq!(render(&actual), "hello world");
        assert_eq!(styles(&actual)[0], Style::new());
    }

    #[test]
    fn test_empty_input() {
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight("", 0);
        assert!(actual.buffer.is_empty());
    }

    // --- ZSH parity tests ---

    #[test]
    fn test_file_mention_with_line_range() {
        // @[path:start:end] — same as ZSH pattern, content inside can contain colons
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight("@[src/main.rs:10:20]", 0);
        assert_eq!(render(&actual), "@[src/main.rs:10:20]");
        assert_eq!(styles(&actual)[0], Style::new().bold().fg(Color::Cyan));
    }

    #[test]
    fn test_file_mention_with_symbol() {
        // @[path#symbol] — content inside can contain `#`
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight("check @[src/lib.rs#my_fn] here", 0);
        let parts: Vec<_> = actual
            .buffer
            .iter()
            .map(|(s, t)| (*s, t.as_str()))
            .collect();
        assert_eq!(
            parts[1],
            (Style::new().bold().fg(Color::Cyan), "@[src/lib.rs#my_fn]")
        );
    }

    #[test]
    fn test_unterminated_mention_not_highlighted() {
        // ZSH requires closing `]`, so unterminated tags are plain text.
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight("see @[src/main.rs", 0);
        assert_eq!(render(&actual), "see @[src/main.rs");
        // No cyan segment
        assert!(
            styles(&actual)
                .iter()
                .all(|s| *s != Style::new().bold().fg(Color::Cyan))
        );
    }

    #[test]
    fn test_slash_command_with_mention_in_args() {
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight("/review @[src/main.rs] please", 0);
        let parts: Vec<_> = actual
            .buffer
            .iter()
            .map(|(s, t)| (*s, t.as_str()))
            .collect();
        assert_eq!(parts[0], (Style::new().bold().fg(Color::Yellow), "/review"));
        assert_eq!(parts[1], (Style::new(), " "));
        assert_eq!(
            parts[2],
            (Style::new().bold().fg(Color::Cyan), "@[src/main.rs]")
        );
        assert_eq!(parts[3], (Style::new(), " please"));
    }

    #[test]
    fn test_colon_command_with_mention_in_args() {
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight(":review @[src/lib.rs]", 0);
        let parts: Vec<_> = actual
            .buffer
            .iter()
            .map(|(s, t)| (*s, t.as_str()))
            .collect();
        assert_eq!(parts[0], (Style::new().bold().fg(Color::Yellow), ":review"));
        assert_eq!(parts[1], (Style::new(), " "));
        assert_eq!(
            parts[2],
            (Style::new().bold().fg(Color::Cyan), "@[src/lib.rs]")
        );
    }

    #[test]
    fn test_bare_at_sign_not_highlighted() {
        // A bare `@word` (no brackets) is plain text — matches ZSH pattern behaviour.
        let fixture = ForgeHighlighter;
        let actual = fixture.highlight("email@example.com", 0);
        assert_eq!(render(&actual), "email@example.com");
        assert_eq!(styles(&actual)[0], Style::new());
    }
}