index : gitrs
A lightweight web interface for browsing Git repositories, implemented in Rust
about summary refs log tree commit diff
gitrs / src / syntax_highlight.rs
-rw-r--r-- blob c482a9eaad4245602dda6e20927a5d655894996b 36788 bytes (plain)
1
use std::path::Path;
2
3
const IMPORTS: &[&str] = &[
4
    "use", "mod", "extern", "import", "from", "export", "package", "require", "include",
5
];
6
7
const KEYWORDS: &[&str] = &[
8
    "fn",
9
    "let",
10
    "mut",
11
    "pub",
12
    "priv",
13
    "struct",
14
    "enum",
15
    "impl",
16
    "trait",
17
    "type",
18
    "where",
19
    "for",
20
    "in",
21
    "while",
22
    "loop",
23
    "if",
24
    "else",
25
    "match",
26
    "return",
27
    "break",
28
    "continue",
29
    "async",
30
    "await",
31
    "move",
32
    "ref",
33
    "static",
34
    "const",
35
    "unsafe",
36
    "dyn",
37
    "as",
38
    "local",
39
    "function",
40
    "then",
41
    "elseif",
42
    "end",
43
    "do",
44
    "repeat",
45
    "until",
46
    "and",
47
    "or",
48
    "not",
49
    "def",
50
    "class",
51
    "try",
52
    "except",
53
    "finally",
54
    "with",
55
    "yield",
56
    "lambda",
57
    "pass",
58
    "raise",
59
    "switch",
60
    "case",
61
    "default",
62
    "var",
63
    "interface",
64
    "go",
65
    "defer",
66
    "select",
67
    "chan",
68
    "fallthrough",
69
    "elif",
70
    "fi",
71
    "done",
72
    "esac",
73
];
74
75
const BOOLEANS: &[&str] = &["true", "false", "nil", "null", "undefined"];
76
77
const BUILTIN_TYPES: &[&str] = &[
78
    "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "f32",
79
    "f64", "bool", "str", "char", "int", "float", "double", "void", "auto", "string", "number",
80
    "boolean", "any",
81
];
82
83
const BUILTIN_CONSTS: &[&str] = &["Some", "None", "Ok", "Err"];
84
85
const BUILTIN_FUNCS: &[&str] = &[
86
    "drop", "print", "ipairs", "pairs", "pcall", "xpcall", "tonumber", "tostring", "assert",
87
    "error", "len", "range", "echo", "set",
88
];
89
90
const BUILTIN_VARS: &[&str] = &["self", "Self", "super", "crate", "this"];
91
92
const SHELL_KEYWORDS: &[&str] = &[
93
    "if", "then", "else", "elif", "fi", "for", "in", "do", "done", "while", "until", "case",
94
    "esac", "function", "select", "end", "begin", "switch", "and", "or", "not",
95
];
96
97
const SHELL_BUILTINS: &[&str] = &[
98
    "cd", "echo", "printf", "export", "local", "readonly", "declare", "typeset", "set", "unset",
99
    "read", "return", "exit", "source", "eval", "exec", "shift", "test", "alias", "unalias", "pwd",
100
    "pushd", "popd", "trap", "wait", "true", "false", "which", "type", "command", "builtin",
101
    "sudo", "doas", "env", "time", "nohup", "xargs", "jobs", "fg", "bg", "kill",
102
];
103
104
const SHELL_CMD_PREFIXES: &[&str] = &[
105
    "sudo", "doas", "env", "time", "nohup", "command", "builtin", "exec", "then", "do", "else",
106
    "elif", "and", "or", "not",
107
];
108
109
#[derive(Clone, Copy, PartialEq, Eq)]
110
enum Mode {
111
    Code {
112
        hash_comments: bool,
113
        dash_comments: bool,
114
        rust_like: bool,
115
    },
116
    Shell,
117
    Config,
118
    Style,
119
    Markup,
120
    Plain,
121
}
122
123
#[derive(Clone, Copy, PartialEq, Eq)]
124
enum State {
125
    Normal,
126
    BlockComment,
127
    LuaBlockComment,
128
    DoubleString,
129
    RawString(usize),
130
}
131
132
pub fn highlight_lines(source: &str, path_or_lang: &str) -> Vec<String> {
133
    let mode = detect_mode(path_or_lang, source);
134
    let mut state = State::Normal;
135
136
    source
137
        .lines()
138
        .map(|line| highlight_line(line, mode, &mut state))
139
        .collect()
140
}
141
142
pub fn highlight_block(source: &str, lang: &str) -> String {
143
    let lines = highlight_lines(source, lang);
144
    format!("<pre><code>{}</code></pre>", lines.join("\n"))
145
}
146
147
fn detect_mode(path_or_lang: &str, source: &str) -> Mode {
148
    let lower = path_or_lang.trim().to_ascii_lowercase();
149
    let file_name = Path::new(&lower)
150
        .file_name()
151
        .and_then(|s| s.to_str())
152
        .unwrap_or(&lower);
153
    let ext = Path::new(file_name)
154
        .extension()
155
        .and_then(|s| s.to_str())
156
        .unwrap_or(file_name);
157
158
    if matches!(
159
        file_name,
160
        ".bashrc" | ".zshrc" | ".profile" | ".bash_profile"
161
    ) {
162
        return Mode::Shell;
163
    }
164
165
    if matches!(
166
        file_name,
167
        "justfile" | "makefile" | "gnumakefile" | "dockerfile" | "containerfile" | "pkgbuild"
168
    ) {
169
        return Mode::Code {
170
            hash_comments: true,
171
            dash_comments: false,
172
            rust_like: false,
173
        };
174
    }
175
176
    if matches!(
177
        file_name,
178
        ".gitignore" | ".gitmodules" | ".gitattributes" | ".editorconfig" | "cargo.lock"
179
    ) {
180
        return Mode::Config;
181
    }
182
183
    match ext {
184
        "rs" | "rust" | "ron" => Mode::Code {
185
            hash_comments: false,
186
            dash_comments: false,
187
            rust_like: true,
188
        },
189
        "lua" | "sql" => Mode::Code {
190
            hash_comments: false,
191
            dash_comments: true,
192
            rust_like: false,
193
        },
194
        "sh" | "bash" | "zsh" | "fish" | "shell" | "console" | "ash" | "dash" | "ksh" => {
195
            Mode::Shell
196
        }
197
        "py" | "python" | "rb" | "ruby" | "nix" | "pl" | "r" | "just" | "mk" | "cmake" => {
198
            Mode::Code {
199
                hash_comments: true,
200
                dash_comments: false,
201
                rust_like: false,
202
            }
203
        }
204
        "c" | "h" | "cpp" | "hpp" | "cc" | "cxx" | "go" | "golang" | "js" | "jsx" | "ts"
205
        | "tsx" | "javascript" | "typescript" | "java" | "cs" | "csharp" | "zig" | "kt"
206
        | "kotlin" | "swift" | "dart" | "php" | "glsl" | "wgsl" | "hlsl" => Mode::Code {
207
            hash_comments: false,
208
            dash_comments: false,
209
            rust_like: false,
210
        },
211
        "toml" | "ini" | "cfg" | "conf" | "yaml" | "yml" | "json" | "jsonc" | "kdl" | "service"
212
        | "timer" | "socket" | "target" | "mount" | "desktop" | "env" => Mode::Config,
213
        "css" | "scss" | "sass" | "less" => Mode::Style,
214
        "html" | "htm" | "xml" | "svg" | "xhtml" => Mode::Markup,
215
        _ if source.starts_with("#!") => {
216
            let first_line = source.lines().next().unwrap_or("");
217
            if first_line.contains("sh") {
218
                Mode::Shell
219
            } else {
220
                Mode::Code {
221
                    hash_comments: true,
222
                    dash_comments: false,
223
                    rust_like: false,
224
                }
225
            }
226
        }
227
        _ => Mode::Plain,
228
    }
229
}
230
231
fn highlight_line(line: &str, mode: Mode, state: &mut State) -> String {
232
    match mode {
233
        Mode::Plain => escape_html(line),
234
        Mode::Shell => highlight_shell_line(line, state),
235
        Mode::Config => highlight_config_line(line),
236
        Mode::Style => highlight_style_line(line, state),
237
        Mode::Markup => highlight_markup_line(line, state),
238
        Mode::Code {
239
            hash_comments,
240
            dash_comments,
241
            rust_like,
242
        } => highlight_code_line(line, hash_comments, dash_comments, rust_like, state),
243
    }
244
}
245
246
fn highlight_code_line(
247
    line: &str,
248
    hash_comments: bool,
249
    dash_comments: bool,
250
    rust_like: bool,
251
    state: &mut State,
252
) -> String {
253
    let bytes = line.as_bytes();
254
    let len = bytes.len();
255
    let mut i = 0;
256
    let mut out = String::with_capacity(len * 2);
257
    let mut prev_keyword = "";
258
    let mut prev_was_dot = false;
259
    let mut in_fn_params = false;
260
    let mut paren_depth: usize = 0;
261
262
    while i < len {
263
        match *state {
264
            State::BlockComment => {
265
                if let Some(pos) = line[i..].find("*/") {
266
                    let end = i + pos + 2;
267
                    push_span(&mut out, "hl-comment", &line[i..end]);
268
                    i = end;
269
                    *state = State::Normal;
270
                } else {
271
                    push_span(&mut out, "hl-comment", &line[i..]);
272
                    return out;
273
                }
274
                continue;
275
            }
276
            State::LuaBlockComment => {
277
                if let Some(pos) = line[i..].find("]]") {
278
                    let end = i + pos + 2;
279
                    push_span(&mut out, "hl-comment", &line[i..end]);
280
                    i = end;
281
                    *state = State::Normal;
282
                } else {
283
                    push_span(&mut out, "hl-comment", &line[i..]);
284
                    return out;
285
                }
286
                continue;
287
            }
288
            State::DoubleString => {
289
                i = scan_double_string(line, i, &mut out, state);
290
                continue;
291
            }
292
            State::RawString(hashes) => {
293
                i = scan_raw_string(line, i, hashes, &mut out, state);
294
                continue;
295
            }
296
            State::Normal => {}
297
        }
298
299
        let b = bytes[i];
300
301
        if b.is_ascii_whitespace() {
302
            let start = i;
303
            while i < len && bytes[i].is_ascii_whitespace() {
304
                i += 1;
305
            }
306
            out.push_str(&line[start..i]);
307
            continue;
308
        }
309
310
        // `//` and `/*` comments (C-style languages only)
311
        if !hash_comments && !dash_comments && b == b'/' && i + 1 < len {
312
            if bytes[i + 1] == b'/' {
313
                push_span(&mut out, "hl-comment", &line[i..]);
314
                break;
315
            }
316
            if bytes[i + 1] == b'*' {
317
                *state = State::BlockComment;
318
                continue;
319
            }
320
        }
321
322
        // Lua `--` and `--[[` comments
323
        if dash_comments && b == b'-' && i + 1 < len && bytes[i + 1] == b'-' {
324
            if line[i + 2..].starts_with("[[") {
325
                *state = State::LuaBlockComment;
326
                continue;
327
            }
328
            push_span(&mut out, "hl-comment", &line[i..]);
329
            break;
330
        }
331
332
        // `#` attributes, comments, or preprocessor directives
333
        if b == b'#' {
334
            if rust_like
335
                && i + 1 < len
336
                && (bytes[i + 1] == b'[' || bytes[i + 1] == b'!')
337
                && let Some(close) = line[i..].find(']')
338
            {
339
                let end = i + close + 1;
340
                push_span(&mut out, "hl-attribute", &line[i..end]);
341
                i = end;
342
                continue;
343
            }
344
            if hash_comments || (i == 0 && line.starts_with("#!")) {
345
                push_span(&mut out, "hl-comment", &line[i..]);
346
                break;
347
            }
348
            if !rust_like {
349
                let start = i;
350
                i += 1;
351
                while i < len && bytes[i].is_ascii_whitespace() {
352
                    i += 1;
353
                }
354
                while i < len && bytes[i].is_ascii_alphabetic() {
355
                    i += 1;
356
                }
357
                push_span(&mut out, "hl-macro", &line[start..i]);
358
                continue;
359
            }
360
        }
361
362
        // Rust raw strings `r"..."`, `r#"..."#`
363
        if rust_like && b == b'r' && i + 1 < len && (bytes[i + 1] == b'"' || bytes[i + 1] == b'#') {
364
            let mut hashes = 0;
365
            let mut j = i + 1;
366
            while j < len && bytes[j] == b'#' {
367
                hashes += 1;
368
                j += 1;
369
            }
370
            if j < len && bytes[j] == b'"' {
371
                push_span(&mut out, "hl-string", &line[i..=j]);
372
                *state = State::RawString(hashes);
373
                i = j + 1;
374
                continue;
375
            }
376
        }
377
378
        if b == b'"' {
379
            push_span(&mut out, "hl-string", "\"");
380
            *state = State::DoubleString;
381
            i = scan_double_string(line, i + 1, &mut out, state);
382
            prev_was_dot = false;
383
            continue;
384
        }
385
386
        if b == b'\'' {
387
            if rust_like {
388
                if let Some((end, is_lifetime)) = scan_rust_quote(line, i) {
389
                    let class = if is_lifetime { "hl-label" } else { "hl-escape" };
390
                    push_span(&mut out, class, &line[i..end]);
391
                    i = end;
392
                    prev_was_dot = false;
393
                    continue;
394
                }
395
            } else {
396
                let end = scan_single_string(line, i);
397
                push_span(&mut out, "hl-string", &line[i..end]);
398
                i = end;
399
                prev_was_dot = false;
400
                continue;
401
            }
402
        }
403
404
        if b.is_ascii_digit() {
405
            let start = i;
406
            i += 1;
407
            while i < len
408
                && (bytes[i].is_ascii_alphanumeric()
409
                    || bytes[i] == b'_'
410
                    || (bytes[i] == b'.' && i + 1 < len && bytes[i + 1].is_ascii_digit()))
411
            {
412
                i += 1;
413
            }
414
            push_span(&mut out, "hl-number", &line[start..i]);
415
            prev_was_dot = false;
416
            continue;
417
        }
418
419
        if is_ident_start(b) {
420
            let start = i;
421
            i += 1;
422
            while i < len && is_ident_continue(bytes[i]) {
423
                i += 1;
424
            }
425
            let ident = &line[start..i];
426
            let rest = &line[i..];
427
428
            if rest.starts_with('!') && !rest.starts_with("!=") {
429
                i += 1;
430
                push_span(&mut out, "hl-macro", &line[start..i]);
431
                prev_was_dot = false;
432
                continue;
433
            }
434
435
            let class = classify_ident(
436
                ident,
437
                rest.trim_start(),
438
                prev_keyword,
439
                prev_was_dot,
440
                in_fn_params && paren_depth == 1,
441
            );
442
            push_span(&mut out, class, ident);
443
444
            if matches!(ident, "fn" | "function" | "def") {
445
                in_fn_params = true;
446
            }
447
            prev_keyword = if matches!(class, "hl-keyword" | "hl-include") {
448
                ident
449
            } else {
450
                ""
451
            };
452
            prev_was_dot = false;
453
            continue;
454
        }
455
456
        if matches!(b, b'(' | b')' | b'[' | b']' | b'{' | b'}' | b',' | b';') {
457
            match b {
458
                b'(' => paren_depth += 1,
459
                b')' => {
460
                    paren_depth = paren_depth.saturating_sub(1);
461
                    if paren_depth == 0 {
462
                        in_fn_params = false;
463
                    }
464
                }
465
                b'{' | b';' => in_fn_params = false,
466
                _ => {}
467
            }
468
            push_span(&mut out, "hl-punctuation", &line[i..=i]);
469
            prev_was_dot = false;
470
            i += 1;
471
            continue;
472
        }
473
474
        if b == b':' {
475
            let len_colon = if i + 1 < len && bytes[i + 1] == b':' {
476
                2
477
            } else {
478
                1
479
            };
480
            push_span(&mut out, "hl-punctuation", &line[i..i + len_colon]);
481
            prev_was_dot = false;
482
            i += len_colon;
483
            continue;
484
        }
485
486
        if b == b'.' {
487
            if i + 1 < len && bytes[i + 1] == b'.' {
488
                let end = if i + 2 < len && bytes[i + 2] == b'=' {
489
                    i + 3
490
                } else {
491
                    i + 2
492
                };
493
                push_span(&mut out, "hl-operator", &line[i..end]);
494
                prev_was_dot = false;
495
                i = end;
496
            } else {
497
                push_span(&mut out, "hl-punctuation", ".");
498
                prev_was_dot = true;
499
                i += 1;
500
            }
501
            continue;
502
        }
503
504
        if is_operator_byte(b) {
505
            let start = i;
506
            i += 1;
507
            while i < len && is_operator_byte(bytes[i]) {
508
                i += 1;
509
            }
510
            push_span(&mut out, "hl-operator", &line[start..i]);
511
            prev_was_dot = false;
512
            continue;
513
        }
514
515
        let ch = line[i..].chars().next().unwrap();
516
        let end = i + ch.len_utf8();
517
        escape_into(&mut out, &line[i..end]);
518
        prev_was_dot = false;
519
        i = end;
520
    }
521
522
    out
523
}
524
525
fn classify_ident(
526
    ident: &str,
527
    trimmed_rest: &str,
528
    prev_keyword: &str,
529
    prev_was_dot: bool,
530
    in_fn_params: bool,
531
) -> &'static str {
532
    if !prev_was_dot {
533
        if IMPORTS.contains(&ident) {
534
            return "hl-include";
535
        }
536
        if KEYWORDS.contains(&ident) {
537
            return "hl-keyword";
538
        }
539
        if BOOLEANS.contains(&ident) {
540
            return "hl-boolean";
541
        }
542
        if BUILTIN_TYPES.contains(&ident) {
543
            return "hl-type-builtin";
544
        }
545
        if BUILTIN_CONSTS.contains(&ident) {
546
            return "hl-constant";
547
        }
548
        if BUILTIN_FUNCS.contains(&ident) {
549
            return "hl-function-builtin";
550
        }
551
        if BUILTIN_VARS.contains(&ident) {
552
            return "hl-variable";
553
        }
554
    }
555
556
    if matches!(prev_keyword, "fn" | "function" | "def") {
557
        return "hl-function";
558
    }
559
    if matches!(
560
        prev_keyword,
561
        "struct" | "enum" | "trait" | "type" | "class" | "interface"
562
    ) {
563
        return "hl-type";
564
    }
565
    if prev_keyword == "mod" {
566
        return "hl-module";
567
    }
568
569
    if ident.as_bytes()[0].is_ascii_uppercase() {
570
        let is_const = ident.len() > 1
571
            && ident
572
                .bytes()
573
                .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_');
574
        return if is_const { "hl-constant" } else { "hl-type" };
575
    }
576
577
    if trimmed_rest.starts_with("::") && !trimmed_rest.starts_with("::<") {
578
        return "hl-module";
579
    }
580
    if trimmed_rest.starts_with('(') || trimmed_rest.starts_with("::<") {
581
        return "hl-function";
582
    }
583
    if prev_was_dot {
584
        return "hl-property";
585
    }
586
    if trimmed_rest.starts_with(':') && !trimmed_rest.starts_with("::") {
587
        return if in_fn_params {
588
            "hl-parameter"
589
        } else {
590
            "hl-property"
591
        };
592
    }
593
594
    "hl-variable"
595
}
596
597
fn highlight_shell_line(line: &str, state: &mut State) -> String {
598
    let bytes = line.as_bytes();
599
    let len = bytes.len();
600
    let mut i = 0;
601
    let mut out = String::with_capacity(len * 2);
602
    let mut expect_cmd = true;
603
    let mut allow_assign = false;
604
605
    while i < len {
606
        if *state == State::DoubleString {
607
            i = scan_shell_double_string(line, i, &mut out, state);
608
            continue;
609
        }
610
611
        let b = bytes[i];
612
613
        if b.is_ascii_whitespace() {
614
            let start = i;
615
            while i < len && bytes[i].is_ascii_whitespace() {
616
                i += 1;
617
            }
618
            out.push_str(&line[start..i]);
619
            continue;
620
        }
621
622
        // `#` comment (only at start of line or after whitespace / `;`)
623
        if b == b'#' && (i == 0 || bytes[i - 1].is_ascii_whitespace() || bytes[i - 1] == b';') {
624
            push_span(&mut out, "hl-comment", &line[i..]);
625
            break;
626
        }
627
628
        // Single-quoted literal string
629
        if b == b'\'' {
630
            let end = scan_single_string(line, i);
631
            push_span(&mut out, "hl-string", &line[i..end]);
632
            i = end;
633
            expect_cmd = false;
634
            continue;
635
        }
636
637
        // Double-quoted string with `$VAR` interpolation
638
        if b == b'"' {
639
            push_span(&mut out, "hl-string", "\"");
640
            *state = State::DoubleString;
641
            i = scan_shell_double_string(line, i + 1, &mut out, state);
642
            expect_cmd = false;
643
            continue;
644
        }
645
646
        // Command substitution `$(` or `$VAR` / `${VAR}`
647
        if b == b'$' {
648
            if i + 1 < len && bytes[i + 1] == b'(' {
649
                push_span(&mut out, "hl-operator", "$(");
650
                i += 2;
651
                expect_cmd = true;
652
                allow_assign = false;
653
                continue;
654
            }
655
            let end = scan_shell_var(line, i);
656
            push_span(&mut out, "hl-variable", &line[i..end]);
657
            i = end;
658
            expect_cmd = false;
659
            continue;
660
        }
661
662
        // Multi-char shell operators and pipes/separators
663
        if let Some((op_len, resets_cmd)) = match_shell_operator(line, i) {
664
            push_span(&mut out, "hl-operator", &line[i..i + op_len]);
665
            i += op_len;
666
            if resets_cmd {
667
                expect_cmd = true;
668
                allow_assign = false;
669
            }
670
            continue;
671
        }
672
673
        // Closing paren of `$(...)` or subshell
674
        if b == b')' {
675
            push_span(&mut out, "hl-operator", ")");
676
            i += 1;
677
            expect_cmd = false;
678
            continue;
679
        }
680
681
        // Line continuation backslash at end of line
682
        if b == b'\\' && i + 1 == len {
683
            push_span(&mut out, "hl-operator", "\\");
684
            break;
685
        }
686
687
        // Scan a full shell word (keeping flags, paths, URLs, `<repo>`, etc. intact)
688
        let start = i;
689
        while i < len && !is_shell_word_break(bytes, i) {
690
            i += line[i..].chars().next().unwrap().len_utf8();
691
        }
692
        if i == start {
693
            let ch_len = line[i..].chars().next().unwrap().len_utf8();
694
            escape_into(&mut out, &line[i..i + ch_len]);
695
            i += ch_len;
696
            continue;
697
        }
698
699
        let word = &line[start..i];
700
701
        // `VAR=value` environment assignment (before a command or after `export`/`local`/etc.)
702
        if (expect_cmd || allow_assign)
703
            && let Some(eq) = word.find('=')
704
            && eq > 0
705
            && is_shell_ident(&word[..eq])
706
        {
707
            let name = &word[..eq];
708
            let val = &word[eq + 1..];
709
            let name_class = if name.len() > 1
710
                && name
711
                    .bytes()
712
                    .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')
713
            {
714
                "hl-constant"
715
            } else {
716
                "hl-variable"
717
            };
718
            push_span(&mut out, name_class, name);
719
            push_span(&mut out, "hl-operator", "=");
720
            if !val.is_empty() {
721
                if val.bytes().all(|c| c.is_ascii_digit()) {
722
                    push_span(&mut out, "hl-number", val);
723
                } else if matches!(val, "true" | "false") {
724
                    push_span(&mut out, "hl-boolean", val);
725
                } else {
726
                    escape_into(&mut out, val);
727
                }
728
            }
729
            continue;
730
        }
731
732
        if expect_cmd {
733
            if SHELL_KEYWORDS.contains(&word) {
734
                push_span(&mut out, "hl-keyword", word);
735
                expect_cmd = SHELL_CMD_PREFIXES.contains(&word);
736
                allow_assign = false;
737
            } else if SHELL_BUILTINS.contains(&word) {
738
                push_span(&mut out, "hl-function-builtin", word);
739
                expect_cmd = SHELL_CMD_PREFIXES.contains(&word);
740
                allow_assign = matches!(word, "export" | "local" | "readonly" | "declare" | "env");
741
            } else {
742
                push_span(&mut out, "hl-function", word);
743
                expect_cmd = false;
744
                allow_assign = false;
745
            }
746
        } else if word == "--" {
747
            push_span(&mut out, "hl-operator", word);
748
        } else if word.starts_with('-') && word.len() > 1 {
749
            if let Some(eq) = word.find('=') {
750
                push_span(&mut out, "hl-property", &word[..eq]);
751
                push_span(&mut out, "hl-operator", "=");
752
                escape_into(&mut out, &word[eq + 1..]);
753
            } else {
754
                push_span(&mut out, "hl-property", word);
755
            }
756
        } else if word.bytes().all(|c| c.is_ascii_digit()) {
757
            push_span(&mut out, "hl-number", word);
758
        } else if matches!(word, "true" | "false") {
759
            push_span(&mut out, "hl-boolean", word);
760
        } else if matches!(word, "in" | "do" | "then" | "fi" | "done" | "esac") {
761
            push_span(&mut out, "hl-keyword", word);
762
        } else {
763
            escape_into(&mut out, word);
764
        }
765
    }
766
767
    out
768
}
769
770
fn scan_shell_double_string(
771
    line: &str,
772
    mut i: usize,
773
    out: &mut String,
774
    state: &mut State,
775
) -> usize {
776
    let bytes = line.as_bytes();
777
    let len = bytes.len();
778
    let mut seg_start = i;
779
780
    while i < len {
781
        if bytes[i] == b'\\' && i + 1 < len {
782
            if i > seg_start {
783
                push_span(out, "hl-string", &line[seg_start..i]);
784
            }
785
            let esc_end = (i + 2).min(len);
786
            push_span(out, "hl-escape", &line[i..esc_end]);
787
            i = esc_end;
788
            seg_start = i;
789
        } else if bytes[i] == b'$'
790
            && i + 1 < len
791
            && bytes[i + 1] != b'"'
792
            && !bytes[i + 1].is_ascii_whitespace()
793
        {
794
            if i > seg_start {
795
                push_span(out, "hl-string", &line[seg_start..i]);
796
            }
797
            let var_end = scan_shell_var(line, i);
798
            push_span(out, "hl-variable", &line[i..var_end]);
799
            i = var_end;
800
            seg_start = i;
801
        } else if bytes[i] == b'"' {
802
            push_span(out, "hl-string", &line[seg_start..=i]);
803
            *state = State::Normal;
804
            return i + 1;
805
        } else {
806
            i += line[i..].chars().next().unwrap().len_utf8();
807
        }
808
    }
809
810
    if seg_start < len {
811
        push_span(out, "hl-string", &line[seg_start..len]);
812
    }
813
    len
814
}
815
816
fn scan_shell_var(line: &str, start: usize) -> usize {
817
    let bytes = line.as_bytes();
818
    let len = bytes.len();
819
    let mut i = start + 1;
820
    if i >= len {
821
        return i;
822
    }
823
    if bytes[i] == b'{' {
824
        if let Some(close) = line[i..].find('}') {
825
            return i + close + 1;
826
        }
827
        return len;
828
    }
829
    if matches!(bytes[i], b'?' | b'$' | b'!' | b'@' | b'*' | b'#' | b'-')
830
        || bytes[i].is_ascii_digit()
831
    {
832
        return i + 1;
833
    }
834
    while i < len && is_ident_continue(bytes[i]) {
835
        i += 1;
836
    }
837
    i
838
}
839
840
fn match_shell_operator(line: &str, i: usize) -> Option<(usize, bool)> {
841
    let rest = &line[i..];
842
    for (op, resets) in [
843
        ("2>&1", false),
844
        ("1>&2", false),
845
        ("<<-", false),
846
        ("&&", true),
847
        ("||", true),
848
        ("|&", true),
849
        (";;", true),
850
        (">>", false),
851
        ("<<", false),
852
        (">&", false),
853
        ("<&", false),
854
        ("|", true),
855
        (";", true),
856
        ("&", true),
857
    ] {
858
        if rest.starts_with(op) {
859
            return Some((op.len(), resets));
860
        }
861
    }
862
    // Single `<` or `>` only when standalone redirection (not `<repo>` placeholder)
863
    if (rest.starts_with('>') || rest.starts_with('<'))
864
        && (i == 0 || line.as_bytes()[i - 1].is_ascii_whitespace())
865
        && (rest.len() == 1 || rest.as_bytes()[1].is_ascii_whitespace())
866
    {
867
        return Some((1, false));
868
    }
869
    None
870
}
871
872
fn is_shell_word_break(bytes: &[u8], i: usize) -> bool {
873
    let b = bytes[i];
874
    b.is_ascii_whitespace() || matches!(b, b'|' | b'&' | b';' | b'(' | b')' | b'"' | b'\'' | b'$')
875
}
876
877
fn is_shell_ident(s: &str) -> bool {
878
    let bytes = s.as_bytes();
879
    !bytes.is_empty()
880
        && is_ident_start(bytes[0])
881
        && bytes[1..].iter().all(|&b| is_ident_continue(b))
882
}
883
884
fn highlight_config_line(line: &str) -> String {
885
    let trimmed = line.trim_start();
886
    if trimmed.starts_with('#') || trimmed.starts_with("//") || trimmed.starts_with(';') {
887
        let mut out = String::new();
888
        push_span(&mut out, "hl-comment", line);
889
        return out;
890
    }
891
892
    if trimmed.starts_with('[') && trimmed.ends_with(']') {
893
        let indent = &line[..line.len() - trimmed.len()];
894
        let mut out = String::from(indent);
895
        let open_len = if trimmed.starts_with("[[") { 2 } else { 1 };
896
        let close_len = if trimmed.ends_with("]]") { 2 } else { 1 };
897
        push_span(&mut out, "hl-punctuation", &trimmed[..open_len]);
898
        push_span(
899
            &mut out,
900
            "hl-property",
901
            &trimmed[open_len..trimmed.len() - close_len],
902
        );
903
        push_span(
904
            &mut out,
905
            "hl-punctuation",
906
            &trimmed[trimmed.len() - close_len..],
907
        );
908
        return out;
909
    }
910
911
    if let Some(sep_idx) = find_config_sep(line) {
912
        let key_part = &line[..sep_idx];
913
        let sep = &line[sep_idx..=sep_idx];
914
        let val_part = &line[sep_idx + 1..];
915
916
        let mut out = String::new();
917
        let key_trim = key_part.trim();
918
        if !key_trim.is_empty() {
919
            let lead = key_part.len() - key_part.trim_start().len();
920
            let trail = key_part.len() - key_part.trim_end().len();
921
            out.push_str(&key_part[..lead]);
922
            push_span(&mut out, "hl-property", key_trim);
923
            out.push_str(&key_part[key_part.len() - trail..]);
924
        } else {
925
            escape_into(&mut out, key_part);
926
        }
927
928
        let sep_class = if sep == "=" {
929
            "hl-operator"
930
        } else {
931
            "hl-punctuation"
932
        };
933
        push_span(&mut out, sep_class, sep);
934
935
        let mut state = State::Normal;
936
        out.push_str(&highlight_code_line(
937
            val_part, true, false, false, &mut state,
938
        ));
939
        return out;
940
    }
941
942
    let mut state = State::Normal;
943
    highlight_code_line(line, true, false, false, &mut state)
944
}
945
946
fn find_config_sep(line: &str) -> Option<usize> {
947
    let mut in_quotes = false;
948
    for (i, &b) in line.as_bytes().iter().enumerate() {
949
        if b == b'"' {
950
            in_quotes = !in_quotes;
951
        } else if !in_quotes && (b == b'=' || b == b':') {
952
            return Some(i);
953
        }
954
    }
955
    None
956
}
957
958
fn highlight_style_line(line: &str, state: &mut State) -> String {
959
    let trimmed = line.trim_start();
960
    if *state == State::BlockComment || trimmed.starts_with("/*") {
961
        return highlight_code_line(line, false, false, false, state);
962
    }
963
964
    if let Some(colon) = line.find(':')
965
        && !trimmed.starts_with(['.', '#', '@'])
966
        && !line[..colon].contains('{')
967
    {
968
        let prop = &line[..colon];
969
        let rest = &line[colon + 1..];
970
        let mut out = String::new();
971
        let lead = prop.len() - prop.trim_start().len();
972
        out.push_str(&prop[..lead]);
973
        push_span(&mut out, "hl-property", prop.trim_start());
974
        push_span(&mut out, "hl-punctuation", ":");
975
        out.push_str(&highlight_code_line(rest, false, false, false, state));
976
        return out;
977
    }
978
979
    highlight_code_line(line, false, false, false, state)
980
}
981
982
fn highlight_markup_line(line: &str, state: &mut State) -> String {
983
    let bytes = line.as_bytes();
984
    let len = bytes.len();
985
    let mut i = 0;
986
    let mut out = String::with_capacity(len * 2);
987
988
    while i < len {
989
        if *state == State::BlockComment {
990
            if let Some(pos) = line[i..].find("-->") {
991
                let end = i + pos + 3;
992
                push_span(&mut out, "hl-comment", &line[i..end]);
993
                i = end;
994
                *state = State::Normal;
995
            } else {
996
                push_span(&mut out, "hl-comment", &line[i..]);
997
                return out;
998
            }
999
            continue;
1000
        }
1001
1002
        if line[i..].starts_with("<!--") {
1003
            *state = State::BlockComment;
1004
            continue;
1005
        }
1006
1007
        if bytes[i] == b'<' {
1008
            let start = i;
1009
            i += 1;
1010
            if i < len && matches!(bytes[i], b'/' | b'!' | b'?') {
1011
                i += 1;
1012
            }
1013
            push_span(&mut out, "hl-tag-delimiter", &line[start..i]);
1014
1015
            let tag_start = i;
1016
            while i < len && (bytes[i].is_ascii_alphanumeric() || matches!(bytes[i], b'-' | b':')) {
1017
                i += 1;
1018
            }
1019
            if i > tag_start {
1020
                push_span(&mut out, "hl-tag", &line[tag_start..i]);
1021
            }
1022
1023
            while i < len && bytes[i] != b'>' {
1024
                if bytes[i].is_ascii_whitespace() {
1025
                    out.push(bytes[i] as char);
1026
                    i += 1;
1027
                } else if matches!(bytes[i], b'"' | b'\'') {
1028
                    let quote = bytes[i];
1029
                    let s_start = i;
1030
                    i += 1;
1031
                    while i < len && bytes[i] != quote {
1032
                        i += 1;
1033
                    }
1034
                    if i < len {
1035
                        i += 1;
1036
                    }
1037
                    push_span(&mut out, "hl-string", &line[s_start..i]);
1038
                } else if bytes[i] == b'=' {
1039
                    push_span(&mut out, "hl-operator", "=");
1040
                    i += 1;
1041
                } else if bytes[i] == b'/' && i + 1 < len && bytes[i + 1] == b'>' {
1042
                    push_span(&mut out, "hl-tag-delimiter", "/>");
1043
                    i += 2;
1044
                    break;
1045
                } else {
1046
                    let attr_start = i;
1047
                    while i < len
1048
                        && !bytes[i].is_ascii_whitespace()
1049
                        && !matches!(bytes[i], b'=' | b'>' | b'/' | b'"' | b'\'')
1050
                    {
1051
                        i += 1;
1052
                    }
1053
                    if i > attr_start {
1054
                        push_span(&mut out, "hl-label", &line[attr_start..i]);
1055
                    } else {
1056
                        escape_into(&mut out, &line[i..=i]);
1057
                        i += 1;
1058
                    }
1059
                }
1060
            }
1061
1062
            if i < len && bytes[i] == b'>' {
1063
                push_span(&mut out, "hl-tag-delimiter", ">");
1064
                i += 1;
1065
            }
1066
            continue;
1067
        }
1068
1069
        let next_lt = line[i..].find('<').map(|p| i + p).unwrap_or(len);
1070
        escape_into(&mut out, &line[i..next_lt]);
1071
        i = next_lt;
1072
    }
1073
1074
    out
1075
}
1076
1077
fn scan_double_string(line: &str, mut i: usize, out: &mut String, state: &mut State) -> usize {
1078
    let bytes = line.as_bytes();
1079
    let len = bytes.len();
1080
    let mut seg_start = i;
1081
1082
    while i < len {
1083
        if bytes[i] == b'\\' && i + 1 < len {
1084
            if i > seg_start {
1085
                push_span(out, "hl-string", &line[seg_start..i]);
1086
            }
1087
            let esc_end = (i + 2).min(len);
1088
            push_span(out, "hl-escape", &line[i..esc_end]);
1089
            i = esc_end;
1090
            seg_start = i;
1091
        } else if bytes[i] == b'"' {
1092
            push_span(out, "hl-string", &line[seg_start..=i]);
1093
            *state = State::Normal;
1094
            return i + 1;
1095
        } else {
1096
            i += line[i..].chars().next().unwrap().len_utf8();
1097
        }
1098
    }
1099
1100
    if seg_start < len {
1101
        push_span(out, "hl-string", &line[seg_start..len]);
1102
    }
1103
    len
1104
}
1105
1106
fn scan_raw_string(
1107
    line: &str,
1108
    mut i: usize,
1109
    hashes: usize,
1110
    out: &mut String,
1111
    state: &mut State,
1112
) -> usize {
1113
    let bytes = line.as_bytes();
1114
    let len = bytes.len();
1115
    let start = i;
1116
1117
    while i < len {
1118
        if bytes[i] == b'"' {
1119
            let mut h = 0;
1120
            while i + 1 + h < len && bytes[i + 1 + h] == b'#' && h < hashes {
1121
                h += 1;
1122
            }
1123
            if h == hashes {
1124
                let end = i + 1 + hashes;
1125
                push_span(out, "hl-string", &line[start..end]);
1126
                *state = State::Normal;
1127
                return end;
1128
            }
1129
        }
1130
        i += 1;
1131
    }
1132
1133
    if start < len {
1134
        push_span(out, "hl-string", &line[start..len]);
1135
    }
1136
    len
1137
}
1138
1139
fn scan_single_string(line: &str, start: usize) -> usize {
1140
    let bytes = line.as_bytes();
1141
    let len = bytes.len();
1142
    let mut i = start + 1;
1143
    while i < len {
1144
        if bytes[i] == b'\\' && i + 1 < len {
1145
            i += 2;
1146
        } else if bytes[i] == b'\'' {
1147
            return i + 1;
1148
        } else {
1149
            i += 1;
1150
        }
1151
    }
1152
    len
1153
}
1154
1155
fn scan_rust_quote(line: &str, start: usize) -> Option<(usize, bool)> {
1156
    let rest = &line[start + 1..];
1157
    if let Some(escaped) = rest.strip_prefix('\\')
1158
        && let Some(close) = escaped.find('\'')
1159
    {
1160
        return Some((start + 2 + close + 1, false));
1161
    }
1162
    let mut chars = rest.char_indices();
1163
    if let Some((_, first)) = chars.next() {
1164
        if let Some((next_idx, '\'')) = chars.next() {
1165
            return Some((start + 1 + next_idx + 1, false));
1166
        }
1167
        if first.is_ascii_alphabetic() || first == '_' {
1168
            let mut end = first.len_utf8();
1169
            for (idx, ch) in rest[end..].char_indices() {
1170
                if ch.is_ascii_alphanumeric() || ch == '_' {
1171
                    end = first.len_utf8() + idx + ch.len_utf8();
1172
                } else {
1173
                    break;
1174
                }
1175
            }
1176
            return Some((start + 1 + end, true));
1177
        }
1178
    }
1179
    None
1180
}
1181
1182
fn is_ident_start(b: u8) -> bool {
1183
    b.is_ascii_alphabetic() || b == b'_'
1184
}
1185
1186
fn is_ident_continue(b: u8) -> bool {
1187
    b.is_ascii_alphanumeric() || b == b'_'
1188
}
1189
1190
fn is_operator_byte(b: u8) -> bool {
1191
    matches!(
1192
        b,
1193
        b'=' | b'+'
1194
            | b'-'
1195
            | b'*'
1196
            | b'/'
1197
            | b'%'
1198
            | b'&'
1199
            | b'|'
1200
            | b'^'
1201
            | b'!'
1202
            | b'<'
1203
            | b'>'
1204
            | b'?'
1205
            | b'~'
1206
            | b'@'
1207
    )
1208
}
1209
1210
fn push_span(out: &mut String, class: &str, text: &str) {
1211
    if text.is_empty() {
1212
        return;
1213
    }
1214
    out.push_str("<span class=\"");
1215
    out.push_str(class);
1216
    out.push_str("\">");
1217
    escape_into(out, text);
1218
    out.push_str("</span>");
1219
}
1220
1221
fn escape_html(text: &str) -> String {
1222
    let mut out = String::with_capacity(text.len());
1223
    escape_into(&mut out, text);
1224
    out
1225
}
1226
1227
fn escape_into(out: &mut String, text: &str) {
1228
    v_htmlescape::b_escape(text.as_bytes(), out);
1229
}