rpi-tui 0.3.5

Terminal User Interface for pi-rust
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
//! Lightweight code syntax highlighting for terminal rendering.
//!
//! Native Pi highlights fenced code with highlight.js
//! (`utils/syntax-highlight.ts`). rpi ships no JS highlighter, so this is a
//! small, dependency-free tokenizer covering the languages that show up most in
//! agent transcripts (Rust, JS/TS, Python, Go, JSON, shell, C-family, Ruby).
//!
//! It highlights four token classes — comments, strings, numbers and
//! keywords — and leaves everything else in the code-block body color. It does
//! **not** aim for highlight.js parity; unknown languages and unclassifiable
//! lines simply render in the base color, which is the correct fallback.

use crate::theme::ThemeColors;

/// Highlight state that persists across lines (block comments).
#[derive(Debug, Clone, Default)]
pub struct Highlighter {
    in_block_comment: bool,
    profile: Profile,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
enum Profile {
    #[default]
    Plain,
    SlashSlash, // rust, js, ts, go, c-family, java
    Hash,       // python, ruby, shell, yaml, toml
    Json,
    Sql,
}

impl Profile {
    fn for_language(language: &str) -> Self {
        match language {
            "rust" | "rs" | "javascript" | "js" | "jsx" | "typescript" | "ts" | "tsx" | "go"
            | "golang" | "c" | "cpp" | "c++" | "h" | "hpp" | "java" | "csharp" | "cs" | "swift"
            | "kotlin" | "scala" | "dart" | "php" => Self::SlashSlash,
            "python" | "py" | "ruby" | "rb" | "bash" | "sh" | "shell" | "zsh" | "fish" | "yaml"
            | "yml" | "toml" | "ini" | "r" | "perl" | "pl" | "makefile" | "dockerfile" => {
                Self::Hash
            }
            "json" | "jsonc" => Self::Json,
            "sql" => Self::Sql,
            _ => Self::Plain,
        }
    }

    fn line_comment(self) -> Option<&'static str> {
        match self {
            Self::SlashSlash => Some("//"),
            Self::Hash => Some("#"),
            Self::Sql => Some("--"),
            // JSON has no comments; JSONC is handled by the caller as SlashSlash.
            Self::Json | Self::Plain => None,
        }
    }

    fn supports_block_comments(self) -> bool {
        matches!(self, Self::SlashSlash | Self::Sql)
    }

    fn hash_is_comment(self) -> bool {
        self == Self::Hash
    }
}

fn keywords(language: &str) -> &'static [&'static str] {
    match language {
        "rust" | "rs" => &[
            "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum",
            "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod",
            "move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super",
            "trait", "true", "type", "unsafe", "use", "where", "while", "crate",
        ],
        "python" | "py" => &[
            "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del",
            "elif", "else", "except", "False", "finally", "for", "from", "global", "if", "import",
            "in", "is", "lambda", "None", "not", "or", "pass", "raise", "return", "True", "try",
            "while", "with", "yield",
        ],
        "javascript" | "js" | "jsx" | "typescript" | "ts" | "tsx" => &[
            "async",
            "await",
            "break",
            "case",
            "catch",
            "class",
            "const",
            "continue",
            "default",
            "delete",
            "do",
            "else",
            "export",
            "extends",
            "false",
            "finally",
            "for",
            "function",
            "if",
            "import",
            "in",
            "instanceof",
            "let",
            "new",
            "null",
            "return",
            "super",
            "switch",
            "this",
            "throw",
            "true",
            "try",
            "typeof",
            "undefined",
            "var",
            "void",
            "while",
            "yield",
            "interface",
            "type",
            "enum",
            "implements",
            "private",
            "public",
            "readonly",
        ],
        "go" | "golang" => &[
            "break",
            "case",
            "chan",
            "const",
            "continue",
            "default",
            "defer",
            "else",
            "fallthrough",
            "for",
            "func",
            "go",
            "goto",
            "if",
            "import",
            "interface",
            "map",
            "package",
            "range",
            "return",
            "select",
            "struct",
            "switch",
            "type",
            "var",
            "nil",
            "true",
            "false",
        ],
        "bash" | "sh" | "shell" | "zsh" | "fish" => &[
            "if", "then", "else", "elif", "fi", "for", "while", "do", "done", "case", "esac",
            "function", "return", "export", "local", "in",
        ],
        "c" | "cpp" | "c++" | "h" | "hpp" | "java" | "csharp" | "cs" => &[
            "auto",
            "bool",
            "break",
            "case",
            "catch",
            "char",
            "class",
            "const",
            "continue",
            "default",
            "do",
            "double",
            "else",
            "enum",
            "extern",
            "false",
            "float",
            "for",
            "if",
            "int",
            "long",
            "namespace",
            "new",
            "private",
            "protected",
            "public",
            "return",
            "short",
            "static",
            "struct",
            "switch",
            "template",
            "this",
            "throw",
            "true",
            "try",
            "typedef",
            "void",
            "while",
            "using",
            "override",
            "virtual",
        ],
        _ => &[
            "true", "false", "null", "if", "else", "for", "while", "return", "function", "class",
        ],
    }
}

impl Highlighter {
    pub fn new(language: &str) -> Self {
        let lang = language.trim().to_ascii_lowercase();
        // `jsonc` allows `//` comments.
        let profile = if lang == "jsonc" {
            Profile::SlashSlash
        } else {
            Profile::for_language(&lang)
        };
        Self {
            in_block_comment: false,
            profile,
        }
    }

    /// Highlight one line, returning an ANSI-styled string. The caller is
    /// responsible for width computation on the *plain* text.
    pub fn highlight(&mut self, line: &str, colors: &ThemeColors) -> String {
        let base = colors.md_code_block;
        let comment = colors.muted;
        let string = colors.success;
        let number = colors.info;
        let keyword = colors.accent;

        if self.profile == Profile::Plain {
            return base.fg(line);
        }

        let keywords = keywords_from_profile(self.profile);
        let mut out = String::new();
        let chars: Vec<char> = line.chars().collect();
        let mut i = 0usize;
        let mut plain_start = 0usize;

        // Flush `plain_start..i` in base color when a token begins at `i`.
        macro_rules! flush {
            () => {
                if i > plain_start {
                    let text: String = chars[plain_start..i].iter().collect();
                    out.push_str(&base.fg(&text));
                }
            };
        }

        while i < chars.len() {
            // Continue a block comment started on a previous line.
            if self.in_block_comment {
                let close = if self.profile == Profile::Sql {
                    "*/"
                } else {
                    "*/"
                };
                if let Some(off) = find_seq(&chars, i, close) {
                    let end = off + 2;
                    let text: String = chars[i..end].iter().collect();
                    out.push_str(&comment.fg(&text));
                    i = end;
                    self.in_block_comment = false;
                    plain_start = i;
                    continue;
                } else {
                    let text: String = chars[i..].iter().collect();
                    out.push_str(&comment.fg(&text));
                    return finish(&out);
                }
            }

            let rest: String = chars[i..].iter().collect();
            let c = chars[i];

            // Line comment.
            if let Some(marker) = self.profile.line_comment() {
                if rest.starts_with(marker) {
                    flush!();
                    out.push_str(&comment.fg(&rest));
                    return finish(&out);
                }
            }
            // `#` line comment (python/shell/ruby) — only at line start or after
            // whitespace so `#{...}` interpolation and shebangs are not mangled
            // beyond the comment rule (shebang is a comment anyway).
            if self.profile.hash_is_comment()
                && c == '#'
                && (i == 0 || chars[i - 1].is_whitespace())
            {
                flush!();
                out.push_str(&comment.fg(&rest));
                return finish(&out);
            }

            // Block comment start.
            if self.profile.supports_block_comments() && rest.starts_with("/*") {
                flush!();
                if let Some(off) = find_seq(&chars, i + 2, "*/") {
                    let end = off + 2;
                    let text: String = chars[i..end].iter().collect();
                    out.push_str(&comment.fg(&text));
                    i = end;
                    plain_start = i;
                    continue;
                } else {
                    let text: String = chars[i..].iter().collect();
                    out.push_str(&comment.fg(&text));
                    self.in_block_comment = true;
                    return finish(&out);
                }
            }

            // String literal.
            if c == '"' || c == '\'' || c == '`' {
                flush!();
                let quote = c;
                let mut j = i + 1;
                let mut escaped = false;
                while j < chars.len() {
                    let cj = chars[j];
                    if escaped {
                        escaped = false;
                    } else if cj == '\\' {
                        escaped = true;
                    } else if cj == quote {
                        j += 1;
                        break;
                    }
                    j += 1;
                }
                let text: String = chars[i..j.min(chars.len())].iter().collect();
                out.push_str(&string.fg(&text));
                i = j.min(chars.len());
                plain_start = i;
                continue;
            }

            // Number.
            if c.is_ascii_digit() && (i == 0 || !is_ident_char(chars[i - 1])) {
                let mut j = i;
                while j < chars.len()
                    && (chars[j].is_ascii_alphanumeric() || chars[j] == '.' || chars[j] == '_')
                {
                    j += 1;
                }
                flush!();
                let text: String = chars[i..j].iter().collect();
                out.push_str(&number.fg(&text));
                i = j;
                plain_start = i;
                continue;
            }

            // Identifier / keyword.
            if is_ident_start(c) {
                let mut j = i;
                while j < chars.len() && is_ident_char(chars[j]) {
                    j += 1;
                }
                let word: String = chars[i..j].iter().collect();
                if keywords.contains(&word.as_str()) {
                    flush!();
                    out.push_str(&keyword.fg(&word));
                    i = j;
                    plain_start = i;
                    continue;
                }
                i = j;
                continue;
            }

            i += 1;
        }
        flush!();
        finish(&out)
    }
}

fn keywords_from_profile(profile: Profile) -> &'static [&'static str] {
    match profile {
        Profile::SlashSlash => keywords("rust"),
        Profile::Hash => keywords("python"),
        Profile::Json => &["true", "false", "null"],
        Profile::Sql => &[
            "SELECT", "FROM", "WHERE", "INSERT", "UPDATE", "DELETE", "CREATE", "TABLE", "JOIN",
            "ON", "GROUP", "BY", "ORDER", "LIMIT", "AND", "OR", "NOT", "NULL", "AS",
        ],
        Profile::Plain => &[],
    }
}

fn find_seq(chars: &[char], from: usize, seq: &str) -> Option<usize> {
    let target: Vec<char> = seq.chars().collect();
    if target.is_empty() || chars.len() < target.len() {
        return None;
    }
    let start = from.min(chars.len());
    for i in start..=chars.len() - target.len() {
        if chars[i..i + target.len()] == target[..] {
            return Some(i);
        }
    }
    None
}

fn is_ident_start(c: char) -> bool {
    c.is_alphabetic() || c == '_' || c == '$'
}

fn is_ident_char(c: char) -> bool {
    c.is_alphanumeric() || c == '_' || c == '$'
}

fn finish(out: &str) -> String {
    // Close any open SGR so the panel background (applied later) is not
    // overridden past the end of the line.
    if out.is_empty() {
        String::new()
    } else {
        format!("{out}\x1b[0m")
    }
}

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

    #[test]
    fn plain_language_is_passthrough() {
        let colors = ThemeColors::default();
        let mut h = Highlighter::new("text");
        let out = h.highlight("hello world", &colors);
        assert!(out.contains("hello world"));
    }

    #[test]
    fn rust_keyword_is_highlighted() {
        let colors = ThemeColors::default();
        let mut h = Highlighter::new("rust");
        let out = h.highlight("fn main() { let x = 1; }", &colors);
        assert!(out.contains("fn"));
        assert!(out.contains("let"));
        // The keyword color is applied at least once.
        assert!(out.contains('\x1b'));
    }

    #[test]
    fn line_comment_is_full_line() {
        let colors = ThemeColors::default();
        let mut h = Highlighter::new("rust");
        let out = h.highlight("// a comment with fn keyword", &colors);
        // `fn` inside a comment must not have been treated as a keyword.
        assert_eq!(out.matches(colors.accent.to_fg().as_str()).count(), 0);
    }

    #[test]
    fn block_comment_spans_lines() {
        let colors = ThemeColors::default();
        let mut h = Highlighter::new("rust");
        let first = h.highlight("/* start", &colors);
        assert!(first.contains("start"));
        assert!(h.in_block_comment);
        let second = h.highlight("still comment */ fn x()", &colors);
        assert!(!h.in_block_comment);
        // `fn` after the close is a keyword.
        assert!(second.contains("fn"));
    }

    #[test]
    fn string_literal_swallows_keyword() {
        let colors = ThemeColors::default();
        let mut h = Highlighter::new("python");
        let out = h.highlight("s = \"if for while\"", &colors);
        assert!(out.contains("if for while"));
    }

    #[test]
    fn json_literals() {
        let colors = ThemeColors::default();
        let mut h = Highlighter::new("json");
        let out = h.highlight("{\"a\": true, \"b\": null}", &colors);
        assert!(out.contains("true"));
    }
}