tinsel 1.1.0

Clean terminal output with a little sparkle: live step lists, spinners, tables, trees, prompts and full-screen apps.
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
//! Just enough syntax colouring for code excerpts: keywords, strings, numbers, comments, and
//! keys in config files. One line at a time, so a string or comment that spans lines is only
//! coloured on its first.

pub use crate::layout::IntoLang;

use crate::style::palette::{AMBER, BLUSH, MUTED, ROSE, SAGE, SOFT, TEXT};
use crate::style::{Rgb, mix, paint};

/// A language [`Code`](crate::Code) excerpts know how to colour.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Lang {
    /// Rust.
    Rust,
    /// TOML.
    Toml,
    /// JSON.
    Json,
    /// YAML.
    Yaml,
    /// Shell scripts and commands.
    Shell,
    /// Python.
    Python,
    /// JavaScript and TypeScript.
    JavaScript,
}

impl Lang {
    /// The language with this name or file extension (`rust` or `rs`, `toml`, `json`,
    /// `yaml` or `yml`, `sh`/`bash`/`zsh`/`shell`, `python` or `py`, `js`/`ts`/`javascript`).
    pub fn from_name(name: &str) -> Option<Lang> {
        Some(match name.to_ascii_lowercase().as_str() {
            "rust" | "rs" => Lang::Rust,
            "toml" => Lang::Toml,
            "json" | "jsonc" => Lang::Json,
            "yaml" | "yml" => Lang::Yaml,
            "sh" | "bash" | "zsh" | "shell" | "console" => Lang::Shell,
            "python" | "py" => Lang::Python,
            "js" | "ts" | "jsx" | "tsx" | "javascript" | "typescript" | "mjs" => Lang::JavaScript,
            _ => return None,
        })
    }

    /// The language a file is written in, from its extension.
    pub fn from_path(path: &str) -> Option<Lang> {
        Lang::from_name(path.rsplit_once('.')?.1)
    }

    /// One line of source coloured as this language: keywords, strings, numbers, comments,
    /// and keys in config files. Each line is coloured on its own, so a string or comment that
    /// spans lines is only coloured on its first. Without colour it comes back as it was.
    ///
    /// ```
    /// use tinsel::Lang;
    ///
    /// let line = Lang::Rust.highlight("let x = 1; // one");
    /// assert_eq!(tinsel::text::strip_ansi(&line), "let x = 1; // one");
    /// ```
    pub fn highlight(self, line: &str) -> String {
        crate::highlight::line(line, self, false)
    }

    fn comment(self) -> Option<&'static str> {
        match self {
            Lang::Rust | Lang::JavaScript => Some("//"),
            Lang::Toml | Lang::Yaml | Lang::Shell | Lang::Python => Some("#"),
            Lang::Json => None,
        }
    }

    fn keywords(self) -> &'static [&'static str] {
        match self {
            Lang::Rust => &[
                "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "fn",
                "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return",
                "self", "Self", "static", "struct", "super", "trait", "type", "unsafe", "use", "where", "while",
            ],
            Lang::Python => &[
                "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else",
                "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "not", "or",
                "pass", "raise", "return", "try", "while", "with", "yield",
            ],
            Lang::JavaScript => &[
                "async",
                "await",
                "break",
                "case",
                "catch",
                "class",
                "const",
                "continue",
                "default",
                "delete",
                "do",
                "else",
                "export",
                "extends",
                "finally",
                "for",
                "from",
                "function",
                "if",
                "import",
                "in",
                "instanceof",
                "interface",
                "let",
                "new",
                "of",
                "return",
                "switch",
                "throw",
                "try",
                "type",
                "typeof",
                "var",
                "while",
                "yield",
            ],
            Lang::Shell => &[
                "if", "then", "else", "elif", "fi", "for", "in", "do", "done", "while", "case", "esac", "function",
                "return", "export", "local",
            ],
            Lang::Toml | Lang::Json | Lang::Yaml => &[],
        }
    }

    fn constants(self) -> &'static [&'static str] {
        match self {
            Lang::Python => &["True", "False", "None"],
            Lang::JavaScript => &["true", "false", "null", "undefined"],
            _ => &["true", "false", "null", "None", "Some", "Ok", "Err"],
        }
    }
}

/// One line coloured as `lang`. Dimmed lines keep their colours but quieter, so a marked
/// line stands out from the ones around it.
pub(crate) fn line(src: &str, lang: Lang, dim: bool) -> String {
    let tone = |c: Rgb| if dim { mix(c, MUTED, 0.45) } else { c };
    let base = if dim { SOFT } else { TEXT };
    let chars: Vec<char> = src.chars().collect();
    let mut out = String::new();
    let mut i = 0;
    let take = |from: usize, to: usize| chars[from..to].iter().collect::<String>();
    // config files: a key at the start of the line, before `=` or `:`
    let key_end = config_key(&chars, lang);
    // shell: the first word is the command
    let mut command_pending = lang == Lang::Shell;
    let first = first_non_space(&chars);

    while i < chars.len() {
        let c = chars[i];

        if let Some(end) = key_end.filter(|_| i == first) {
            out += &paint(tone(BLUSH), &take(i, end));
            i = end;
            continue;
        }
        if lang.comment().is_some_and(|m| starts_with(&chars[i..], m)) {
            out += &paint(tone(MUTED), &take(i, chars.len()));
            break;
        }
        if lang == Lang::Toml && c == '[' && i == first {
            out += &paint(tone(ROSE), &take(i, chars.len()));
            break;
        }
        if c == '"' || c == '`' || (c == '\'' && !is_lifetime(&chars, i, lang)) {
            let end = string_end(&chars, i);
            let text = take(i, end);
            // a JSON string followed by a colon is a key
            let is_key = lang == Lang::Json && chars[end..].iter().find(|c| !c.is_whitespace()) == Some(&':');
            out += &paint(tone(if is_key { BLUSH } else { SAGE }), &text);
            i = end;
            command_pending = false;
            continue;
        }
        if c.is_ascii_digit() && (i == 0 || !is_word(chars[i - 1])) {
            let end = scan(&chars, i, |c| c.is_ascii_alphanumeric() || c == '.' || c == '_');
            out += &paint(tone(AMBER), &take(i, end));
            i = end;
            continue;
        }
        if lang == Lang::Shell && c == '$' {
            let end = if chars.get(i + 1) == Some(&'{') {
                chars[i..]
                    .iter()
                    .position(|&c| c == '}')
                    .map_or(chars.len(), |p| i + p + 1)
            } else {
                scan(&chars, i + 1, is_word)
            };
            out += &paint(tone(BLUSH), &take(i, end));
            i = end;
            continue;
        }
        if is_word(c) || (lang == Lang::Shell && c == '-') {
            let end = scan(&chars, i, |c| is_word(c) || (lang == Lang::Shell && "-./".contains(c)));
            let word = take(i, end);
            let color = if command_pending {
                command_pending = false;
                ROSE
            } else if lang.keywords().contains(&word.as_str()) {
                ROSE
            } else if lang.constants().contains(&word.as_str()) {
                AMBER
            } else if lang == Lang::Shell && word.starts_with('-') {
                SOFT
            } else if lang == Lang::Rust && chars.get(end) == Some(&'!') {
                // macros
                ROSE
            } else if matches!(lang, Lang::Rust | Lang::JavaScript | Lang::Python)
                && word.starts_with(|c: char| c.is_ascii_uppercase())
            {
                // types and classes
                BLUSH
            } else {
                base
            };
            out += &paint(tone(color), &word);
            i = end;
            continue;
        }
        // stop before anything that starts a token of its own: a flag, in a shell
        let end = scan(&chars, i + 1, |c| {
            !(is_word(c) || "\"'`#$/".contains(c) || c.is_ascii_digit() || (lang == Lang::Shell && c == '-'))
        });
        let end = end.max(i + 1);
        let punct = take(i, end);
        if lang == Lang::Shell && punct.contains(['|', ';', '&']) {
            command_pending = true;
        }
        out += &paint(if c.is_whitespace() { base } else { tone(SOFT) }, &punct);
        i = end;
    }
    out
}

/// Whether `chars` begins with `prefix`, without building a string from them.
fn starts_with(chars: &[char], prefix: &str) -> bool {
    let mut chars = chars.iter();
    prefix.chars().all(|p| chars.next() == Some(&p))
}

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

fn scan(chars: &[char], from: usize, keep: impl Fn(char) -> bool) -> usize {
    chars[from.min(chars.len())..]
        .iter()
        .position(|&c| !keep(c))
        .map_or(chars.len(), |p| from + p)
}

fn first_non_space(chars: &[char]) -> usize {
    chars.iter().position(|c| !c.is_whitespace()).unwrap_or(chars.len())
}

/// Where a string starting at `from` ends (just past its closing quote), allowing escapes.
fn string_end(chars: &[char], from: usize) -> usize {
    let quote = chars[from];
    let mut i = from + 1;
    while i < chars.len() {
        match chars[i] {
            '\\' => i += 2,
            c if c == quote => return i + 1,
            _ => i += 1,
        }
    }
    chars.len()
}

/// In Rust, `'a` is a lifetime, not the start of a character literal like `'a'`.
fn is_lifetime(chars: &[char], at: usize, lang: Lang) -> bool {
    lang == Lang::Rust && chars.get(at + 2) != Some(&'\'') && chars.get(at + 1) != Some(&'\\')
}

/// For TOML and YAML: where a `key =` or `key:` at the start of the line ends.
fn config_key(chars: &[char], lang: Lang) -> Option<usize> {
    let sep = match lang {
        Lang::Toml => '=',
        Lang::Yaml => ':',
        _ => return None,
    };
    let start = first_non_space(chars);
    // YAML list items can carry a key too: `- name: x`
    let start = if lang == Lang::Yaml && chars.get(start) == Some(&'-') {
        start + 1 + chars[start + 1..].iter().take_while(|c| c.is_whitespace()).count()
    } else {
        start
    };
    let end = scan(chars, start, |c| is_word(c) || "-.\"'".contains(c));
    let after = chars[end..].iter().position(|c| !c.is_whitespace()).map(|p| end + p);
    (end > start && after.is_some_and(|a| chars[a] == sep)).then_some(end)
}

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

    #[test]
    fn colouring_never_changes_the_text() {
        crate::style::with_color_mode(crate::ColorMode::TrueColor, || {
            for (src, lang) in [
                (r#"let x: Vec<&'a str> = vec!["a\"b", 'c']; // hi"#, Lang::Rust),
                (r#"port = "80" # web"#, Lang::Toml),
                (r#"{"a": [1, true, null]}"#, Lang::Json),
                ("- name: ${HOME}/x", Lang::Yaml),
                (r#"cargo build --release | tee "$LOG" # go"#, Lang::Shell),
                ("def f(x): return None", Lang::Python),
                ("const a = `x${y}`;", Lang::JavaScript),
            ] {
                assert_eq!(strip_ansi(&line(src, lang, false)), src, "{lang:?}");
                assert_eq!(strip_ansi(&line(src, lang, true)), src, "{lang:?}");
            }
        });
    }

    #[test]
    fn a_long_line_takes_linear_time() {
        let src = "a + ".repeat(40_000);
        let started = std::time::Instant::now();
        let out = crate::style::with_color_mode(crate::ColorMode::None, || line(&src, Lang::Rust, false));
        assert_eq!(out, src);
        assert!(
            started.elapsed() < std::time::Duration::from_secs(1),
            "{:?}",
            started.elapsed()
        );
    }

    #[test]
    fn finds_config_keys() {
        let chars: Vec<char> = "  memory = 512".chars().collect();
        assert_eq!(config_key(&chars, Lang::Toml), Some(8));
        let chars: Vec<char> = "- name: web".chars().collect();
        assert_eq!(config_key(&chars, Lang::Yaml), Some(6));
        let chars: Vec<char> = "just text".chars().collect();
        assert_eq!(config_key(&chars, Lang::Toml), None);
    }

    #[test]
    fn languages_come_from_paths() {
        assert_eq!(Lang::from_path("src/main.rs"), Some(Lang::Rust));
        assert_eq!(Lang::from_path("app.yml"), Some(Lang::Yaml));
        assert_eq!(Lang::from_path("Makefile"), None);
    }

    #[test]
    fn languages_come_from_names() {
        let names = ["JSON", "zsh", "py", "tsx", "rs", "toml", "yml"];
        let langs: Vec<_> = names.iter().map(|n| Lang::from_name(n)).collect();
        assert_eq!(
            langs,
            [
                Lang::Json,
                Lang::Shell,
                Lang::Python,
                Lang::JavaScript,
                Lang::Rust,
                Lang::Toml,
                Lang::Yaml
            ]
            .map(Some)
        );
        assert_eq!(Lang::from_name("cobol"), None);
    }

    fn coloured(src: &str, lang: Lang) -> String {
        crate::style::with_color_mode(crate::ColorMode::TrueColor, || line(src, lang, false))
    }

    fn painted(color: crate::Rgb, s: &str) -> String {
        crate::style::with_color_mode(crate::ColorMode::TrueColor, || paint(color, s))
    }

    #[test]
    fn toml_sections_are_headings() {
        assert_eq!(coloured("[server]", Lang::Toml), painted(ROSE, "[server]"));
    }

    #[test]
    fn shell_flags_are_quieter() {
        let out = coloured("cargo build --release", Lang::Shell);
        assert!(out.contains(&painted(SOFT, "--release")), "{out:?}");
    }

    #[test]
    fn a_command_after_a_pipe_is_a_command() {
        let out = coloured("cargo build | tee log", Lang::Shell);
        assert!(out.contains(&painted(ROSE, "tee")), "{out:?}");
        let out = coloured("make&&ls", Lang::Shell);
        assert!(out.contains(&painted(ROSE, "ls")), "{out:?}");
    }

    #[test]
    fn shell_variables_stand_out() {
        let out = coloured("echo ${HOME} $USER", Lang::Shell);
        assert!(
            out.contains(&painted(BLUSH, "${HOME}")) && out.contains(&painted(BLUSH, "$USER")),
            "{out:?}"
        );
        assert!(coloured("echo ${HOME", Lang::Shell).ends_with(&painted(BLUSH, "${HOME")));
    }

    #[test]
    fn an_unclosed_string_runs_to_the_end() {
        assert_eq!(coloured(r#""open"#, Lang::Json), painted(SAGE, r#""open"#));
    }
}