snyvi 1.0.1

A fast, beautiful viewer for the documents your agents produce
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
//! Turn a document into HTML exactly once, at receive time.

use comrak::adapters::SyntaxHighlighterAdapter;
use comrak::nodes::NodeValue;
use comrak::{format_html_with_plugins, parse_document, Arena, Options, Plugins};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{self, Write};
use std::path::Path;
use std::sync::Arc;
use syntect::parsing::{ParseState, Scope, ScopeStack, SyntaxReference, SyntaxSet};
use syntect::util::LinesWithEndings;

/// Source scanned for an outline, and the most entries returned.
const OUTLINE_CAP: usize = 512 * 1024;
const OUTLINE_ITEMS: usize = 1200;

/// One declaration in a source file.
#[derive(Debug, Clone, Serialize)]
pub struct Outline {
    pub name: String,
    /// fn | type | impl | mod
    pub kind: &'static str,
    /// 1-based, so the client can scroll to the matching line span.
    pub line: usize,
    pub depth: usize,
}

/// Sublime grammars mark a declared name with an `entity.name.*` scope. Call sites
/// and builtins use `support.*` and `variable.*`, so they stay out of the outline.
fn definition_kind(stack: &ScopeStack) -> Option<&'static str> {
    const DEFS: &[(&str, &str)] = &[
        ("entity.name.function", "fn"),
        ("entity.name.macro", "fn"),
        ("entity.name.struct", "type"),
        ("entity.name.enum", "type"),
        ("entity.name.union", "type"),
        ("entity.name.class", "type"),
        ("entity.name.interface", "type"),
        ("entity.name.trait", "type"),
        ("entity.name.type", "type"),
        ("entity.name.impl", "impl"),
        ("entity.name.namespace", "mod"),
        ("entity.name.module", "mod"),
        ("entity.name.package", "mod"),
    ];
    // Built once: Scope::new parses a string on every call otherwise.
    static TABLE: std::sync::OnceLock<Vec<(Scope, &'static str)>> = std::sync::OnceLock::new();
    let table = TABLE.get_or_init(|| {
        DEFS.iter()
            .filter_map(|(sel, kind)| Scope::new(sel).ok().map(|s| (s, *kind)))
            .collect()
    });
    for scope in stack.as_slice().iter().rev() {
        for (prefix, kind) in table {
            if prefix.is_prefix_of(*scope) {
                return Some(kind);
            }
        }
    }
    None
}

/// Highlight synchronously up to this many bytes; the rest is plain until a
/// background pass replaces it.
pub const HIGHLIGHT_CAP: usize = 256 * 1024;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
    Markdown,
    Code,
    Diff,
    Text,
    /// Displayed from its bytes rather than rendered from text.
    Image,
    /// Not text at all: described, never decoded.
    Binary,
    /// Delimited text, laid out as a table.
    Table,
}

impl Kind {
    pub fn as_str(self) -> &'static str {
        match self {
            Kind::Markdown => "markdown",
            Kind::Code => "code",
            Kind::Diff => "diff",
            Kind::Text => "text",
            Kind::Image => "image",
            Kind::Binary => "binary",
            Kind::Table => "table",
        }
    }
    pub fn parse(s: &str) -> Option<Kind> {
        match s {
            "markdown" => Some(Kind::Markdown),
            "code" => Some(Kind::Code),
            "diff" => Some(Kind::Diff),
            "text" => Some(Kind::Text),
            "image" => Some(Kind::Image),
            "binary" => Some(Kind::Binary),
            "table" => Some(Kind::Table),
            _ => None,
        }
    }
}

pub struct Renderer {
    ss: SyntaxSet,
    classes: ClassMap,
}

/// syntect's bundled grammars plus the extras in `syntaxes/`, packed by the ignored
/// test `build_syntax_pack`. Empty until that test has run; then the defaults are used.
const SYNTAX_PACK: &[u8] = include_bytes!("../syntaxes/pack.bin");

fn load_syntaxes() -> SyntaxSet {
    if SYNTAX_PACK.is_empty() {
        return SyntaxSet::load_defaults_newlines();
    }
    syntect::dumps::from_binary(SYNTAX_PACK)
}

/// Extensions the grammars do not list under their own names.
fn alias(ext: &str) -> &str {
    match ext {
        "tsx" | "mts" | "cts" => "ts",
        "jsx" | "mjs" | "cjs" => "js",
        "kts" => "kt",
        "h" => "c",
        "hpp" | "hh" | "cc" | "cxx" => "cpp",
        "zsh" | "bash" | "ksh" => "sh",
        "yml" => "yaml",
        "htm" | "xhtml" => "html",
        "markdown" | "mdx" => "md",
        "jsonc" | "json5" => "json",
        "pyi" | "pyw" => "py",
        "rake" | "gemspec" => "rb",
        "mk" => "makefile",
        "cmake" => "cmake",
        "ini" | "cfg" | "conf" | "toml" | "env" | "properties" => ext,
        _ => ext,
    }
}

impl Renderer {
    pub fn new() -> Self {
        Renderer {
            ss: load_syntaxes(),
            classes: ClassMap::new(),
        }
    }

    /// Names of every language this build can highlight.
    pub fn languages(&self) -> Vec<String> {
        let mut v: Vec<String> = self
            .ss
            .syntaxes()
            .iter()
            .filter(|s| !s.hidden)
            .map(|s| s.name.clone())
            .collect();
        v.sort();
        v
    }

    /// Decide what a document is from its path, an explicit language, and its content.
    pub fn detect(
        &self,
        path: Option<&str>,
        lang: Option<&str>,
        content: &str,
    ) -> (Kind, Option<String>) {
        if let Some(l) = lang
            .map(|l| l.trim().to_ascii_lowercase())
            .filter(|l| !l.is_empty())
        {
            return match l.as_str() {
                "md" | "markdown" | "mdx" => (Kind::Markdown, None),
                "diff" | "patch" => (Kind::Diff, None),
                "txt" | "text" | "plain" => (Kind::Text, None),
                "csv" | "tsv" => (Kind::Table, Some(l)),
                _ => (Kind::Code, Some(l)),
            };
        }
        if let Some(p) = path {
            let name = Path::new(p)
                .file_name()
                .map(|n| n.to_string_lossy().to_ascii_lowercase())
                .unwrap_or_default();
            if name == "dockerfile" || name.starts_with("dockerfile.") {
                return (Kind::Code, Some("dockerfile".into()));
            }
            if name == "makefile" || name == "gnumakefile" {
                return (Kind::Code, Some("makefile".into()));
            }
            let ext = Path::new(p)
                .extension()
                .map(|e| e.to_string_lossy().to_ascii_lowercase())
                .unwrap_or_default();
            return match ext.as_str() {
                "md" | "markdown" | "mdx" | "mdown" => (Kind::Markdown, None),
                "diff" | "patch" => (Kind::Diff, None),
                "txt" | "log" | "" => {
                    if looks_like_diff(content) {
                        (Kind::Diff, None)
                    } else {
                        (Kind::Text, None)
                    }
                }
                "csv" | "tsv" => (Kind::Table, Some(ext.clone())),
                e if is_image_ext(e) => (Kind::Image, Some(ext.clone())),
                _ => (Kind::Code, Some(ext)),
            };
        }
        if looks_like_diff(content) {
            return (Kind::Diff, None);
        }
        (Kind::Markdown, None)
    }

    pub fn render(&self, kind: Kind, lang: Option<&str>, source: &str) -> String {
        self.render_with_base(kind, lang, source, None)
    }

    /// `file_base` is the URL prefix for relative image paths (`/files/<id>/`), given when
    /// the document came from a file on disk.
    pub fn render_with_base(
        &self,
        kind: Kind,
        lang: Option<&str>,
        source: &str,
        file_base: Option<&str>,
    ) -> String {
        match kind {
            Kind::Markdown => self.markdown(source, file_base),
            Kind::Code => self.code(lang, source, HIGHLIGHT_CAP),
            Kind::Diff => diff(source),
            Kind::Text => plain(source),
            Kind::Table => table(source, lang),
            // Both are built from bytes, by whoever holds them; there is no text to render.
            Kind::Image | Kind::Binary => placeholder(source),
        }
    }

    /// Full highlight with no cap, for the background pass on large files.
    pub fn render_code_uncapped(&self, lang: Option<&str>, source: &str) -> String {
        self.code(lang, source, usize::MAX)
    }

    fn markdown(&self, source: &str, file_base: Option<&str>) -> String {
        let mut options = Options::default();
        if let Some(base) = file_base {
            let base = base.to_string();
            options.extension.image_url_rewriter =
                Some(Arc::new(move |url: &str| rewrite_image_url(&base, url)));
        }
        let ext = &mut options.extension;
        ext.strikethrough = true;
        ext.table = true;
        ext.autolink = true;
        ext.tasklist = true;
        ext.footnotes = true;
        ext.description_lists = true;
        ext.multiline_block_quotes = true;
        ext.alerts = true;
        ext.header_ids = Some(String::new());
        options.render.github_pre_lang = true;
        options.render.full_info_string = false;

        let adapter = Highlighter {
            ss: &self.ss,
            classes: &self.classes,
        };
        let mut plugins = Plugins::default();
        plugins.render.codefence_syntax_highlighter = Some(&adapter);

        let trace = std::env::var_os("SNYVI_TRACE").is_some();
        let t = std::time::Instant::now();
        let arena = Arena::new();
        let root = parse_document(&arena, source, &options);
        // Raw HTML is rare in agent output. Without it, comrak's safe mode already escapes
        // everything and drops dangerous links, so the (expensive) sanitizer can be skipped.
        let has_raw_html = root.descendants().any(|n| {
            matches!(
                n.data.borrow().value,
                NodeValue::HtmlBlock(_) | NodeValue::HtmlInline(_)
            )
        });
        options.render.unsafe_ = has_raw_html;
        let mut raw = Vec::with_capacity(source.len() * 2);
        let _ = format_html_with_plugins(root, &options, &mut raw, &plugins);
        let raw = String::from_utf8(raw).unwrap_or_default();
        // comrak writes each heading's anchor `inert`, which makes the `#` the
        // stylesheet shows beside a heading a thing that cannot be clicked --
        // and the sanitizer strips the attribute, so a document with raw HTML
        // in it had a working link where one without had a dead one. Out of
        // the tab order instead, since it is aria-hidden: the heading's own
        // text is what a screen reader reads, and the client makes a click on
        // the mark copy the section's link.
        let raw = raw.replace("<a inert href=\"#", "<a tabindex=\"-1\" href=\"#");
        let t_md = t.elapsed();
        let out = if has_raw_html { sanitize(&raw) } else { raw };
        if trace {
            eprintln!(
                "  markdown: comrak+highlight {:.1} ms, sanitize {:.1} ms{} ({} KB -> {} KB)",
                t_md.as_secs_f64() * 1e3,
                (t.elapsed() - t_md).as_secs_f64() * 1e3,
                if has_raw_html { "" } else { " (skipped)" },
                source.len() / 1024,
                out.len() / 1024
            );
        }
        out
    }

    fn syntax_for(&self, lang: Option<&str>, source: &str) -> &SyntaxReference {
        lang.and_then(|l| {
            let l = alias(l);
            self.ss
                .find_syntax_by_token(l)
                .or_else(|| self.ss.find_syntax_by_extension(l))
        })
        .or_else(|| self.ss.find_syntax_by_first_line(source))
        .unwrap_or_else(|| self.ss.find_syntax_plain_text())
    }

    /// Definitions in a source file, for the rail: the same parse the highlighter
    /// does, keeping the tokens the grammar marks as names of declared things.
    pub fn outline(&self, lang: Option<&str>, source: &str) -> Vec<Outline> {
        let syntax = self.syntax_for(lang, source);
        let mut state = ParseState::new(syntax);
        let mut stack = ScopeStack::new();
        let mut found: Vec<(usize, &'static str, String, usize)> = vec![];
        let mut consumed = 0usize;
        for (n, line) in LinesWithEndings::from(source).enumerate() {
            consumed += line.len();
            if consumed > OUTLINE_CAP || found.len() >= OUTLINE_ITEMS {
                break;
            }
            let text = line.strip_suffix('\n').unwrap_or(line);
            let Ok(ops) = state.parse_line(line, &self.ss) else {
                continue;
            };
            // The first run of definition-scoped tokens on a line names what it declares.
            let mut last = 0usize;
            let mut run: Option<(&'static str, String)> = None;
            let mut done: Option<(&'static str, String)> = None;
            for (idx, op) in &ops {
                let idx = (*idx).min(text.len());
                if idx > last {
                    let seg = &text[last..idx];
                    match (definition_kind(&stack), run.take()) {
                        (Some(k), Some((rk, mut name))) if rk == k => {
                            name.push_str(seg);
                            run = Some((k, name));
                        }
                        (Some(k), _) => run = Some((k, seg.to_string())),
                        (None, Some(r)) => {
                            done = Some(r);
                            break;
                        }
                        (None, None) => {}
                    }
                    last = idx;
                }
                let _ = stack.apply(op);
            }
            let item = done.or_else(|| {
                run.map(|(k, mut name)| {
                    if last < text.len() && definition_kind(&stack).is_some() {
                        name.push_str(&text[last..]);
                    }
                    (k, name)
                })
            });
            if let Some((kind, name)) = item {
                let name = name.trim().to_string();
                if !name.is_empty()
                    && name
                        .chars()
                        .all(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.')
                {
                    let indent: usize = text
                        .chars()
                        .take_while(|c| *c == ' ' || *c == '\t')
                        .map(|c| if c == '\t' { 4 } else { 1 })
                        .sum();
                    found.push((n + 1, kind, name, indent));
                }
            }
        }
        // Turn raw indent columns into nesting levels, so 4-space and 2-space files agree.
        let mut widths: Vec<usize> = found.iter().map(|(_, _, _, i)| *i).collect();
        widths.sort_unstable();
        widths.dedup();
        found
            .into_iter()
            .map(|(line, kind, name, indent)| Outline {
                depth: widths.iter().position(|w| *w == indent).unwrap_or(0).min(3),
                line,
                kind,
                name,
            })
            .collect()
    }

    fn code(&self, lang: Option<&str>, source: &str, cap: usize) -> String {
        let syntax = self.syntax_for(lang, source);
        let mut out = String::with_capacity(source.len() * 3);
        out.push_str("<pre class=\"code\" data-lang=\"");
        out.push_str(&html_escape::encode_double_quoted_attribute(
            syntax.name.as_str(),
        ));
        out.push_str("\"><code>");
        highlight_lines(&self.ss, &self.classes, syntax, source, cap, &mut out);
        out.push_str("</code></pre>");
        out
    }
}

/// Maps syntect scopes to a handful of short CSS classes. One span per token run,
/// instead of one nested span per scope, keeps the HTML small and the CSS simple.
pub struct ClassMap {
    table: Vec<(Scope, &'static str)>,
}

impl ClassMap {
    fn new() -> Self {
        // Order matters: more specific prefixes first.
        const ENTRIES: &[(&str, &str)] = &[
            ("comment", "c"),
            ("string", "s"),
            ("constant.numeric", "n"),
            ("constant.language", "n"),
            ("constant.character", "n"),
            ("constant.other", "n"),
            ("storage.type", "t"),
            ("storage", "k"),
            ("keyword", "k"),
            ("entity.name.function", "f"),
            ("support.function", "f"),
            ("entity.name.type", "t"),
            ("entity.name.class", "t"),
            ("entity.name.struct", "t"),
            ("entity.name.enum", "t"),
            ("entity.name.trait", "t"),
            ("entity.name.namespace", "t"),
            ("support.type", "t"),
            ("support.class", "t"),
            ("entity.name.tag", "tg"),
            ("entity.other.attribute-name", "at"),
            ("entity.other.inherited-class", "t"),
            ("entity.name", "f"),
            ("variable.parameter", "v"),
            ("variable.other.member", "v"),
            ("variable.language", "k"),
            ("support.constant", "n"),
            ("support.variable", "v"),
            ("punctuation.definition.comment", "c"),
            ("punctuation.definition.string", "s"),
            ("punctuation", "p"),
            ("markup.heading", "hd"),
            ("markup.bold", "b"),
            ("markup.italic", "i"),
            ("markup.raw", "raw"),
            ("markup.inserted", "ins"),
            ("markup.deleted", "del"),
            ("markup.underline.link", "lnk"),
            ("invalid", "inv"),
        ];
        ClassMap {
            table: ENTRIES
                .iter()
                .filter_map(|(sel, cls)| Scope::new(sel).ok().map(|s| (s, *cls)))
                .collect(),
        }
    }

    fn class_for(&self, stack: &ScopeStack) -> Option<&'static str> {
        for scope in stack.as_slice().iter().rev() {
            for (prefix, cls) in &self.table {
                if prefix.is_prefix_of(*scope) {
                    return Some(cls);
                }
            }
        }
        None
    }
}

/// Emit one `<span class="ln">` per line, highlighted up to the cap.
fn highlight_lines(
    ss: &SyntaxSet,
    classes: &ClassMap,
    syntax: &SyntaxReference,
    source: &str,
    cap: usize,
    out: &mut String,
) {
    let mut state = ParseState::new(syntax);
    let mut stack = ScopeStack::new();
    let mut consumed = 0usize;
    let mut lines = LinesWithEndings::from(source).peekable();
    while let Some(line) = lines.peek() {
        if consumed + line.len() > cap && consumed > 0 {
            break;
        }
        consumed += line.len();
        let text = line.strip_suffix('\n').unwrap_or(line);
        out.push_str("<span class=\"ln\">");
        match state.parse_line(line, ss) {
            Ok(ops) => {
                let mut last = 0usize;
                let mut open: Option<&'static str> = None;
                for (idx, op) in &ops {
                    let idx = (*idx).min(text.len());
                    if idx > last {
                        let seg = &text[last..idx];
                        emit(out, seg, refine(classes.class_for(&stack), seg), &mut open);
                        last = idx;
                    }
                    let _ = stack.apply(op);
                }
                if last < text.len() {
                    let seg = &text[last..];
                    emit(out, seg, refine(classes.class_for(&stack), seg), &mut open);
                }
                if open.is_some() {
                    out.push_str("</span>");
                }
            }
            Err(_) => out.push_str(&html_escape::encode_text(text)),
        }
        out.push_str("</span>\n");
        lines.next();
    }
    for line in lines {
        out.push_str("<span class=\"ln\">");
        out.push_str(&html_escape::encode_text(
            line.strip_suffix('\n').unwrap_or(line),
        ));
        out.push_str("</span>\n");
    }
}

/// Sublime grammars file declaration keywords (`let`, `fn`, `def`, `class`, ...) under
/// `storage.type`, the same scope as real type names. Colour the words as keywords.
fn refine(class: Option<&'static str>, text: &str) -> Option<&'static str> {
    if class == Some("t") {
        let w = text.trim();
        if matches!(
            w,
            "let"
                | "const"
                | "static"
                | "var"
                | "fn"
                | "func"
                | "function"
                | "def"
                | "class"
                | "struct"
                | "enum"
                | "impl"
                | "trait"
                | "interface"
                | "type"
                | "mod"
                | "module"
                | "namespace"
                | "union"
                | "typedef"
                | "extends"
                | "implements"
                | "new"
                | "abstract"
                | "final"
                | "override"
                | "declare"
                | "package"
                | "import"
                | "export"
                | "async"
                | "await"
        ) {
            return Some("k");
        }
    }
    class
}

/// Append a token run, opening/closing a class span only when the class changes.
fn emit(
    out: &mut String,
    text: &str,
    class: Option<&'static str>,
    open: &mut Option<&'static str>,
) {
    if text.is_empty() {
        return;
    }
    if *open != class {
        if open.is_some() {
            out.push_str("</span>");
        }
        if let Some(c) = class {
            out.push_str("<span class=\"");
            out.push_str(c);
            out.push_str("\">");
        }
        *open = class;
    }
    out.push_str(&html_escape::encode_text(text));
}

/// Extensions snyvi displays as a picture rather than as source.
pub const IMAGE_EXTS: &[&str] = &[
    "png", "jpg", "jpeg", "gif", "webp", "svg", "avif", "bmp", "ico",
];

pub fn is_image_ext(ext: &str) -> bool {
    IMAGE_EXTS.contains(&ext)
}

/// The lowercased extension of a path, or "" when it has none.
pub fn ext_of(path: &str) -> String {
    std::path::Path::new(path)
        .extension()
        .map(|e| e.to_string_lossy().to_ascii_lowercase())
        .unwrap_or_default()
}

/// A null byte in the first block is the usual signal, and what git uses. SVG is
/// text and is caught by `is_image_ext` before this ever sees it.
pub fn looks_binary(bytes: &[u8]) -> bool {
    bytes.iter().take(8000).any(|b| *b == 0)
}

/// A one-line note standing in for a body that cannot be shown.
pub fn placeholder(msg: &str) -> String {
    format!("<p class=\"empty\">{}</p>", html_escape::encode_text(msg))
}

/// Describe a file snyvi will not decode, in the units a reader thinks in.
pub fn describe_bytes(name: &str, size: u64) -> String {
    if size >= 1_048_576 {
        format!(
            "{name} is a binary file ({:.1} MB).",
            size as f64 / 1_048_576.0
        )
    } else {
        format!("{name} is a binary file ({} KB).", (size / 1024).max(1))
    }
}

/// What a file can be shown as beyond its source: "html" for a page the browser
/// can lay out, "pdf" for one it has a viewer for. Both are framed with an opaque
/// origin, never rendered into snyvi's own page.
pub fn preview_kind(ext: &str) -> Option<&'static str> {
    match ext {
        "html" | "htm" | "xhtml" => Some("html"),
        "pdf" => Some("pdf"),
        _ => None,
    }
}

/// The `<img>` body for an image document, pointed at wherever its bytes are served.
pub fn image_body(src_url: &str, alt: &str) -> String {
    format!(
        "<p class=\"doc-image\"><img src=\"{}\" alt=\"{}\" loading=\"lazy\"></p>",
        html_escape::encode_double_quoted_attribute(src_url),
        html_escape::encode_double_quoted_attribute(alt)
    )
}

fn plain(source: &str) -> String {
    let mut out = String::with_capacity(source.len() + 64);
    out.push_str("<pre class=\"code plain\" data-lang=\"Text\"><code>");
    for line in source.split_inclusive('\n') {
        out.push_str("<span class=\"ln\">");
        out.push_str(&html_escape::encode_text(
            line.strip_suffix('\n').unwrap_or(line),
        ));
        out.push_str("</span>\n");
    }
    out.push_str("</code></pre>");
    out
}

/// Rows past this are dropped. A spreadsheet of any size still opens instantly, and
/// nobody reads row 3000 of a table in a viewer; `o` opens the whole file.
const MAX_TABLE_ROWS: usize = 2000;
/// A column whose longest cell exceeds this is prose, not an identifier.
const PROSE_COLUMN_CHARS: usize = 44;

/// Split delimited text into rows, honouring RFC 4180 quoting: a field wrapped in
/// quotes may contain the delimiter, a newline, or a doubled quote standing for one.
fn parse_delimited(source: &str, delim: char, max_rows: usize) -> (Vec<Vec<String>>, bool) {
    let mut rows = Vec::new();
    let mut row = Vec::new();
    let mut field = String::new();
    let mut quoted = false;
    let mut chars = source.chars().peekable();
    while let Some(c) = chars.next() {
        if quoted {
            if c == '"' {
                if chars.peek() == Some(&'"') {
                    chars.next();
                    field.push('"');
                } else {
                    quoted = false;
                }
            } else {
                field.push(c);
            }
            continue;
        }
        match c {
            '"' if field.is_empty() => quoted = true,
            c if c == delim => row.push(std::mem::take(&mut field)),
            '\r' => {}
            '\n' => {
                row.push(std::mem::take(&mut field));
                // A trailing newline is a line ending, not an empty final row.
                if !(row.len() == 1 && row[0].is_empty()) {
                    rows.push(std::mem::take(&mut row));
                } else {
                    row.clear();
                }
                if rows.len() >= max_rows {
                    return (rows, chars.peek().is_some());
                }
            }
            c => field.push(c),
        }
    }
    if !field.is_empty() || !row.is_empty() {
        row.push(field);
        rows.push(row);
    }
    (rows, false)
}

/// A number, so it can be aligned like one. Deliberately narrow: a value that merely
/// starts with a digit is still text.
fn is_numeric(s: &str) -> bool {
    let t = s.trim().trim_start_matches(['-', '+']).replace(',', "");
    !t.is_empty()
        && t.chars()
            .all(|c| c.is_ascii_digit() || c == '.' || c == '%' || c == 'e' || c == 'E')
        && t.chars().any(|c| c.is_ascii_digit())
}

/// Lay delimited text out as a table, first row as the head.
pub fn table(source: &str, lang: Option<&str>) -> String {
    let delim = if lang == Some("tsv") { '\t' } else { ',' };
    let (rows, truncated) = parse_delimited(source, delim, MAX_TABLE_ROWS);
    if rows.is_empty() {
        return placeholder("This file has no rows.");
    }
    // Ragged rows are common in hand-edited files; pad them so the columns line up.
    let width = rows.iter().map(|r| r.len()).max().unwrap_or(0);
    // Identifiers and numbers are scanned down a column and must not wrap; prose
    // columns are read across and must, or they get cut off at the pane edge.
    let prose: Vec<bool> = (0..width)
        .map(|i| {
            rows.iter()
                .skip(1)
                .filter_map(|r| r.get(i))
                .map(|c| c.trim().len())
                .max()
                .unwrap_or(0)
                > PROSE_COLUMN_CHARS
        })
        .collect();
    let class_for = |i: usize, s: &str| match (prose[i], is_numeric(s)) {
        (true, _) => " class=\"wrap\"",
        (_, true) => " class=\"num\"",
        _ => "",
    };

    let mut out = String::with_capacity(source.len() * 2);
    out.push_str("<table class=\"data\"><thead><tr>");
    for (i, wraps) in prose.iter().enumerate() {
        let head = rows[0].get(i).map(|s| s.trim()).unwrap_or("");
        out.push_str(&format!(
            "<th{}>{}</th>",
            if *wraps { " class=\"wrap\"" } else { "" },
            html_escape::encode_text(head)
        ));
    }
    out.push_str("</tr></thead><tbody>");
    for row in rows.iter().skip(1) {
        out.push_str("<tr>");
        for i in 0..width {
            let v = row.get(i).map(String::as_str).unwrap_or("");
            out.push_str(&format!(
                "<td{}>{}</td>",
                class_for(i, v),
                html_escape::encode_text(v.trim())
            ));
        }
        out.push_str("</tr>");
    }
    out.push_str("</tbody></table>");
    if truncated {
        out.push_str(&placeholder(&format!(
            "Showing the first {MAX_TABLE_ROWS} rows. Open the source for the rest."
        )));
    }
    out
}

pub fn diff(source: &str) -> String {
    let mut out = String::with_capacity(source.len() * 2);
    out.push_str("<pre class=\"code diff\" data-lang=\"Diff\"><code>");
    for line in source.split_inclusive('\n') {
        let l = line.strip_suffix('\n').unwrap_or(line);
        let class = if l.starts_with("+++")
            || l.starts_with("---")
            || l.starts_with("diff ")
            || l.starts_with("index ")
        {
            "meta"
        } else if l.starts_with("@@") {
            "hunk"
        } else if l.starts_with('+') {
            "add"
        } else if l.starts_with('-') {
            "del"
        } else {
            "ctx"
        };
        out.push_str("<span class=\"ln ");
        out.push_str(class);
        out.push_str("\">");
        out.push_str(&html_escape::encode_text(l));
        out.push_str("</span>\n");
    }
    out.push_str("</code></pre>");
    out
}

fn looks_like_diff(content: &str) -> bool {
    let head: Vec<&str> = content.lines().take(6).collect();
    head.iter()
        .any(|l| l.starts_with("diff --git") || l.starts_with("@@ "))
        || (head.iter().any(|l| l.starts_with("--- "))
            && head.iter().any(|l| l.starts_with("+++ ")))
}

/// Title: explicit, else first Markdown H1, else file name, else "Untitled".
pub fn title_for(explicit: Option<&str>, kind: Kind, path: Option<&str>, content: &str) -> String {
    if let Some(t) = explicit.map(str::trim).filter(|t| !t.is_empty()) {
        return t.to_string();
    }
    if kind == Kind::Markdown {
        for line in content.lines().take(40) {
            let l = line.trim();
            if let Some(h) = l.strip_prefix("# ") {
                let h = h.trim().trim_end_matches('#').trim();
                if !h.is_empty() {
                    return h.to_string();
                }
            }
        }
    }
    if let Some(p) = path {
        if let Some(name) = Path::new(p).file_name() {
            return name.to_string_lossy().to_string();
        }
    }
    "Untitled".to_string()
}

/// If the first non-blank line is an H1 equal to `title`, return the content without it.
pub fn strip_leading_h1(content: &str, _title: &str) -> Option<String> {
    let mut lines = content.split_inclusive('\n');
    let mut prefix_len = 0usize;
    for line in lines.by_ref() {
        if line.trim().is_empty() {
            prefix_len += line.len();
            continue;
        }
        let h = line
            .trim()
            .strip_prefix("# ")?
            .trim()
            .trim_end_matches('#')
            .trim();
        if h.is_empty() {
            return None;
        }
        // The viewer prints the title above the body, so a leading H1 is a second
        // copy of it whether or not the words match.
        let rest_start = prefix_len + line.len();
        return Some(content[rest_start..].to_string());
    }
    None
}

fn sanitize(html: &str) -> String {
    let mut b = ammonia::Builder::default();
    b.add_tags(["input"])
        .add_tag_attributes("input", ["type", "checked", "disabled"])
        .add_tag_attributes(
            "a",
            [
                "id",
                "class",
                "aria-hidden",
                "tabindex",
                "data-footnote-ref",
                "data-footnote-backref",
            ],
        )
        .add_tag_attributes("li", ["id", "class"])
        .add_tag_attributes("ul", ["class"])
        .add_tag_attributes("ol", ["class", "start"])
        .add_tag_attributes("section", ["class", "data-footnotes"])
        .add_tag_attributes("div", ["class"])
        .add_tag_attributes("p", ["class"])
        .add_tag_attributes("span", ["class"])
        .add_tag_attributes("pre", ["class", "data-lang"])
        .add_tag_attributes("code", ["class"])
        .add_tag_attributes("table", ["class"])
        .add_tag_attributes("td", ["align", "style"])
        .add_tag_attributes("th", ["align", "style"])
        .add_tag_attributes("img", ["src", "alt", "title", "width", "height", "loading"])
        .add_tags(["section", "details", "summary"])
        .add_tag_attributes("details", ["open"]);
    for h in ["h1", "h2", "h3", "h4", "h5", "h6"] {
        b.add_tag_attributes(h, ["id"]);
    }
    b.link_rel(Some("noopener noreferrer"));
    b.clean(html).to_string()
}

/// comrak adapter: syntect with CSS classes, so code blocks share the page palette.
struct Highlighter<'a> {
    ss: &'a SyntaxSet,
    classes: &'a ClassMap,
}

impl SyntaxHighlighterAdapter for Highlighter<'_> {
    fn write_highlighted(
        &self,
        output: &mut dyn Write,
        lang: Option<&str>,
        code: &str,
    ) -> io::Result<()> {
        if lang
            .map(|l| l.eq_ignore_ascii_case("mermaid"))
            .unwrap_or(false)
        {
            // Diagram source stays verbatim; the client renders it after first paint.
            return output.write_all(html_escape::encode_text(code).as_bytes());
        }
        let syntax = lang
            .filter(|l| !l.is_empty())
            .and_then(|l| self.ss.find_syntax_by_token(l))
            .unwrap_or_else(|| self.ss.find_syntax_plain_text());
        let mut out = String::with_capacity(code.len() * 3);
        highlight_lines(self.ss, self.classes, syntax, code, HIGHLIGHT_CAP, &mut out);
        output.write_all(out.as_bytes())
    }

    fn write_pre_tag(
        &self,
        output: &mut dyn Write,
        attributes: HashMap<String, String>,
    ) -> io::Result<()> {
        let lang = attributes.get("lang").cloned().unwrap_or_default();
        if lang.eq_ignore_ascii_case("mermaid") {
            return output.write_all(b"<pre class=\"mermaid\" data-lang=\"Mermaid\">");
        }
        let name = self
            .ss
            .find_syntax_by_token(&lang)
            .map(|s| s.name.clone())
            .unwrap_or_else(|| {
                if lang.is_empty() {
                    "Text".into()
                } else {
                    lang.clone()
                }
            });
        write!(
            output,
            "<pre class=\"code\" data-lang=\"{}\">",
            html_escape::encode_double_quoted_attribute(&name)
        )
    }

    fn write_code_tag(
        &self,
        output: &mut dyn Write,
        attributes: HashMap<String, String>,
    ) -> io::Result<()> {
        match attributes.get("class") {
            Some(c) => write!(
                output,
                "<code class=\"{}\">",
                html_escape::encode_double_quoted_attribute(c)
            ),
            None => output.write_all(b"<code>"),
        }
    }
}

/// Relative image paths resolve against the source document's directory via `/files/<id>/`.
fn rewrite_image_url(base: &str, url: &str) -> String {
    let u = url.trim();
    let absolute = u.starts_with('/')
        || u.starts_with('#')
        || u.contains("://")
        || u.starts_with("data:")
        || u.starts_with("mailto:");
    if absolute || u.is_empty() {
        return u.to_string();
    }
    format!("{base}{}", u.strip_prefix("./").unwrap_or(u))
}

/// Side-by-side rendering of a unified diff with word-level highlights.
pub fn diff_split(source: &str) -> String {
    let mut out = String::with_capacity(source.len() * 3);
    out.push_str("<div class=\"split\">");
    let mut dels: Vec<&str> = vec![];
    let mut adds: Vec<&str> = vec![];
    let e = |s: &str| html_escape::encode_text(s).to_string();
    fn flush(out: &mut String, dels: &mut Vec<&str>, adds: &mut Vec<&str>) {
        let n = dels.len().max(adds.len());
        for i in 0..n {
            match (dels.get(i), adds.get(i)) {
                (Some(d), Some(a)) => {
                    let (dh, ah) = word_diff(&d[1..], &a[1..]);
                    out.push_str(&format!(
                        "<div class=\"l del\">{dh}</div><div class=\"r add\">{ah}</div>"
                    ));
                }
                (Some(d), None) => out.push_str(&format!(
                    "<div class=\"l del\">{}</div><div class=\"r empty\"></div>",
                    html_escape::encode_text(&d[1..])
                )),
                (None, Some(a)) => out.push_str(&format!(
                    "<div class=\"l empty\"></div><div class=\"r add\">{}</div>",
                    html_escape::encode_text(&a[1..])
                )),
                (None, None) => {}
            }
        }
        dels.clear();
        adds.clear();
    }
    for line in source.lines() {
        if line.starts_with("+++")
            || line.starts_with("---")
            || line.starts_with("diff ")
            || line.starts_with("index ")
        {
            flush(&mut out, &mut dels, &mut adds);
            out.push_str(&format!("<div class=\"meta full\">{}</div>", e(line)));
        } else if line.starts_with("@@") {
            flush(&mut out, &mut dels, &mut adds);
            out.push_str(&format!("<div class=\"hunk full\">{}</div>", e(line)));
        } else if let Some(rest) = line.strip_prefix('-') {
            let _ = rest;
            dels.push(line);
        } else if let Some(rest) = line.strip_prefix('+') {
            let _ = rest;
            adds.push(line);
        } else {
            flush(&mut out, &mut dels, &mut adds);
            let text = line.strip_prefix(' ').unwrap_or(line);
            out.push_str(&format!(
                "<div class=\"l ctx\">{0}</div><div class=\"r ctx\">{0}</div>",
                e(text)
            ));
        }
    }
    flush(&mut out, &mut dels, &mut adds);
    out.push_str("</div>");
    out
}

/// Word-level highlight of a changed line pair: (old html, new html).
fn word_diff(a: &str, b: &str) -> (String, String) {
    use similar::{ChangeTag, TextDiff};
    let d = TextDiff::from_words(a, b);
    let (mut oa, mut ob) = (String::new(), String::new());
    for c in d.iter_all_changes() {
        let t = html_escape::encode_text(c.value());
        match c.tag() {
            ChangeTag::Equal => {
                oa.push_str(&t);
                ob.push_str(&t);
            }
            ChangeTag::Delete => oa.push_str(&format!("<mark>{t}</mark>")),
            ChangeTag::Insert => ob.push_str(&format!("<mark>{t}</mark>")),
        }
    }
    (oa, ob)
}

/// Unified diff between two sources, for "compare with previous".
pub fn unified(a_name: &str, a: &str, b_name: &str, b: &str) -> String {
    let d = similar::TextDiff::from_lines(a, b);
    d.unified_diff()
        .context_radius(3)
        .header(a_name, b_name)
        .to_string()
}

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

    fn r() -> Renderer {
        Renderer::new()
    }

    /// Regenerate syntaxes/pack.bin: `cargo test --release build_syntax_pack -- --ignored`.
    /// Grammars that syntect cannot compile are reported and skipped.
    #[test]
    #[ignore]
    fn build_syntax_pack() {
        use syntect::parsing::{SyntaxDefinition, SyntaxSetBuilder};
        let mut b: SyntaxSetBuilder = SyntaxSet::load_defaults_newlines().into_builder();
        let mut added = vec![];
        for entry in std::fs::read_dir("syntaxes").unwrap().flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("sublime-syntax") {
                continue;
            }
            let src = std::fs::read_to_string(&path).unwrap();
            match SyntaxDefinition::load_from_str(
                &src,
                true,
                path.file_stem().and_then(|s| s.to_str()),
            ) {
                Ok(def) => {
                    added.push(format!("{} [{}]", def.name, def.file_extensions.join(",")));
                    b.add(def);
                }
                Err(e) => eprintln!("SKIP {}: {e}", path.display()),
            }
        }
        let ss = b.build();
        // Force-compile every grammar now so a broken regex fails here, not at runtime.
        for syn in ss.syntaxes() {
            let mut st = ParseState::new(syn);
            let _ = st.parse_line("x\n", &ss);
        }
        syntect::dumps::dump_to_file(&ss, "syntaxes/pack.bin").unwrap();
        eprintln!("added: {}", added.join("; "));
        eprintln!(
            "pack: {} KB, {} syntaxes",
            std::fs::metadata("syntaxes/pack.bin").unwrap().len() / 1024,
            ss.syntaxes().len()
        );
    }

    #[test]
    fn detects_kind_from_path_lang_and_content() {
        let r = r();
        assert_eq!(r.detect(Some("/x/PLAN.md"), None, "").0, Kind::Markdown);
        assert_eq!(
            r.detect(Some("/x/main.rs"), None, ""),
            (Kind::Code, Some("rs".into()))
        );
        assert_eq!(r.detect(Some("/x/a.patch"), None, "").0, Kind::Diff);
        assert_eq!(r.detect(Some("/x/notes.txt"), None, "hello").0, Kind::Text);
        assert_eq!(
            r.detect(None, Some("py"), ""),
            (Kind::Code, Some("py".into()))
        );
        assert_eq!(
            r.detect(None, None, "diff --git a/x b/x\n--- a/x\n+++ b/x\n")
                .0,
            Kind::Diff
        );
        assert_eq!(r.detect(None, None, "# Heading\n\ntext").0, Kind::Markdown);
    }

    #[test]
    fn csv_becomes_a_table_with_quotes_and_ragged_rows_handled() {
        let src = "name,qty,note\n\"Widget, large\",12,\"he said \"\"hi\"\"\"\nBolt,3\n";
        let html = table(src, Some("csv"));
        assert!(
            html.contains("<th>name</th><th>qty</th><th>note</th>"),
            "{html}"
        );
        // A quoted field keeps its delimiter, and a doubled quote becomes one.
        assert!(html.contains("Widget, large"), "{html}");
        assert!(html.contains("he said \"hi\""), "{html}");
        // Numbers are marked so they can be aligned as numbers.
        assert!(html.contains("<td class=\"num\">12</td>"), "{html}");
        // A short row is padded rather than shifting the columns.
        assert!(
            html.ends_with("<td>Bolt</td><td class=\"num\">3</td><td></td></tr></tbody></table>"),
            "{html}"
        );

        // Tabs when the file says so.
        let tsv = table("a\tb\n1\t2\n", Some("tsv"));
        assert!(tsv.contains("<th>a</th><th>b</th>"), "{tsv}");

        // A cell that merely starts with a digit is still text.
        assert!(!table("h\n3 apples\n", Some("csv")).contains("class=\"num\""));
        assert!(table("", Some("csv")).contains("no rows"));
    }

    #[test]
    fn only_pages_and_pdfs_offer_a_preview() {
        assert_eq!(preview_kind("html"), Some("html"));
        assert_eq!(preview_kind("htm"), Some("html"));
        assert_eq!(preview_kind("xhtml"), Some("html"));
        assert_eq!(preview_kind("pdf"), Some("pdf"));
        for ext in ["md", "rs", "svg", "png", "txt", "json", ""] {
            assert_eq!(preview_kind(ext), None, "{ext} is not previewable");
        }
    }

    #[test]
    fn title_precedence() {
        assert_eq!(
            title_for(Some(" Given "), Kind::Markdown, None, "# H1"),
            "Given"
        );
        assert_eq!(
            title_for(None, Kind::Markdown, Some("/a/b.md"), "\n\n# From H1 #\n"),
            "From H1"
        );
        assert_eq!(
            title_for(None, Kind::Code, Some("/a/main.rs"), "# not a heading"),
            "main.rs"
        );
        assert_eq!(
            title_for(None, Kind::Markdown, None, "no heading"),
            "Untitled"
        );
    }

    #[test]
    fn markdown_fast_path_and_sanitizer() {
        let r = r();
        let safe = r.render(
            Kind::Markdown,
            None,
            "Hello *world*\n\n- [x] done\n\n[js](javascript:alert(1))",
        );
        assert!(safe.contains("<em>world</em>"));
        assert!(safe.contains("type=\"checkbox\""));
        assert!(
            !safe.contains("javascript:"),
            "dangerous link dropped: {safe}"
        );

        let raw = r.render(Kind::Markdown, None, "<details><summary>s</summary>hidden <script>alert(1)</script></details>\n\n<img src=x onerror=alert(1)>");
        assert!(raw.contains("<details>"), "harmless html kept: {raw}");
        assert!(!raw.contains("<script"), "script removed: {raw}");
        assert!(!raw.contains("onerror"), "event handler removed: {raw}");
    }

    #[test]
    fn heading_anchors_are_clickable_on_both_paths() {
        let r = r();
        for src in ["## Hello there\n\ntext\n", "## Hello there\n\n<b>raw</b>\n"] {
            // The sanitizer rewrites the tag on the raw path, so the check is
            // on the attributes rather than on the exact string.
            let html = r.render(Kind::Markdown, None, src);
            let a = html
                .split("<a ")
                .nth(1)
                .and_then(|s| s.split('>').next())
                .unwrap_or_default();
            assert!(a.contains("tabindex=\"-1\""), "{html}");
            assert!(a.contains("class=\"anchor\""), "{html}");
            assert!(a.contains("href=\"#hello-there\""), "{html}");
            assert!(!html.contains("inert"), "{html}");
        }
    }

    #[test]
    fn code_blocks_get_compact_classes_and_line_spans() {
        let r = r();
        let html = r.render(
            Kind::Markdown,
            None,
            "```rust\nfn main() { let s = \"hi\"; }\n```\n",
        );
        assert!(
            html.contains("<pre class=\"code\" data-lang=\"Rust\">"),
            "{html}"
        );
        assert!(html.contains("<span class=\"k\">fn</span>"), "{html}");
        assert!(html.contains("<span class=\"s\">"), "{html}");
        assert_eq!(html.matches("<span class=\"ln\">").count(), 1);

        let code = r.render(Kind::Code, Some("py"), "def f():\n    return 1\n");
        assert_eq!(code.matches("<span class=\"ln\">").count(), 2);
        assert!(code.contains("data-lang=\"Python\""));
        let esc = r.render(Kind::Code, Some("html"), "<b onclick=\"x()\">hi</b>\n");
        assert!(
            esc.contains("&lt;") && !esc.contains("<b ") && !esc.contains("onclick=\""),
            "source text is escaped: {esc}"
        );
        assert!(esc.contains("data-lang=\"HTML\""));
    }

    #[test]
    fn highlight_cap_leaves_tail_plain_and_uncapped_does_not() {
        let r = r();
        let big: String = (0..20_000).map(|i| format!("let v{i} = {i};\n")).collect();
        assert!(big.len() > HIGHLIGHT_CAP);
        let capped = r.render(Kind::Code, Some("rs"), &big);
        let full = r.render_code_uncapped(Some("rs"), &big);
        assert!(capped.matches("class=\"k\"").count() < full.matches("class=\"k\"").count());
        assert_eq!(capped.matches("<span class=\"ln\">").count(), 20_000);
        assert_eq!(full.matches("<span class=\"ln\">").count(), 20_000);
    }

    #[test]
    fn image_urls_rewrite_only_when_relative() {
        assert_eq!(
            rewrite_image_url("/files/abc/", "./img/a.png"),
            "/files/abc/img/a.png"
        );
        assert_eq!(
            rewrite_image_url("/files/abc/", "../x.png"),
            "/files/abc/../x.png"
        );
        assert_eq!(
            rewrite_image_url("/files/abc/", "https://h/x.png"),
            "https://h/x.png"
        );
        assert_eq!(rewrite_image_url("/files/abc/", "/abs.png"), "/abs.png");
        let r = Renderer::new();
        let html = r.render_with_base(
            Kind::Markdown,
            None,
            "![alt](shot.png)",
            Some("/files/abc/"),
        );
        assert!(html.contains("src=\"/files/abc/shot.png\""), "{html}");
        let plain = r.render(Kind::Markdown, None, "![alt](shot.png)");
        assert!(plain.contains("src=\"shot.png\""), "{plain}");
    }

    #[test]
    fn mermaid_blocks_keep_source_verbatim() {
        let html =
            Renderer::new().render(Kind::Markdown, None, "```mermaid\ngraph TD; A-->B\n```\n");
        assert!(
            html.contains("<pre class=\"mermaid\" data-lang=\"Mermaid\">"),
            "{html}"
        );
        assert!(html.contains("A--&gt;B"), "{html}");
        assert!(!html.contains("class=\"ln\""), "{html}");
    }

    #[test]
    fn split_diff_pairs_lines_and_marks_words() {
        let html = diff_split(
            "--- a\n+++ b\n@@ -1,2 +1,2 @@\n ctx\n-the old value\n+the new value\n+extra\n",
        );
        assert!(html.contains("<div class=\"hunk full\">"));
        assert!(html.contains("<div class=\"l del\">the <mark>old</mark> value</div><div class=\"r add\">the <mark>new</mark> value</div>"), "{html}");
        assert!(
            html.contains("<div class=\"l empty\"></div><div class=\"r add\">extra</div>"),
            "{html}"
        );
        assert_eq!(html.matches("class=\"l ctx\"").count(), 1);
    }

    #[test]
    fn outline_finds_declarations_not_call_sites() {
        let r = r();
        let src = "use std::io;\n\npub struct Config {\n    pub name: String,\n}\n\nimpl Config {\n    pub fn load() -> Self {\n        println!(\"x\");\n        Self::default()\n    }\n}\n\nfn main() {\n    load();\n}\n";
        let rust = r.outline(Some("rs"), src);
        let got: Vec<(&str, &str, usize)> = rust
            .iter()
            .map(|o| (o.name.as_str(), o.kind, o.line))
            .collect();
        assert!(got.contains(&("Config", "type", 3)), "{got:?}");
        assert!(got.contains(&("load", "fn", 8)), "{got:?}");
        assert!(got.contains(&("main", "fn", 14)), "{got:?}");
        assert!(
            !got.iter().any(|(n, _, l)| *n == "load" && *l == 15),
            "call sites excluded: {got:?}"
        );
        let depth = |name: &str, line: usize| {
            rust.iter()
                .find(|o| o.name == name && o.line == line)
                .map(|o| o.depth)
        };
        assert_eq!(depth("main", 14), Some(0));
        assert!(depth("load", 8) > Some(0), "nested one level: {rust:?}");

        let py = r.outline(Some("py"), "import os\n\nclass Store:\n    def get(self, k):\n        return os.path.join(k)\n\ndef main():\n    pass\n");
        let got: Vec<(&str, &str)> = py.iter().map(|o| (o.name.as_str(), o.kind)).collect();
        assert!(got.contains(&("Store", "type")), "{got:?}");
        assert!(got.contains(&("get", "fn")), "{got:?}");
        assert!(got.contains(&("main", "fn")), "{got:?}");
        assert!(
            !got.iter().any(|(n, _)| *n == "join"),
            "method calls excluded: {got:?}"
        );

        assert!(r
            .outline(Some("txt"), "just words\nmore words\n")
            .is_empty());
    }

    #[test]
    fn a_leading_h1_is_dropped_even_when_it_differs_from_the_title() {
        assert_eq!(
            strip_leading_h1("\n# Its own heading\n\nbody", "A different title").as_deref(),
            Some("\nbody")
        );
        assert_eq!(
            strip_leading_h1("# Same\n\nbody", "Same").as_deref(),
            Some("\nbody")
        );
        assert!(
            strip_leading_h1("intro\n# Later\n", "x").is_none(),
            "only a leading H1"
        );
        assert!(strip_leading_h1("## Smaller\n", "x").is_none());
    }

    #[test]
    fn prose_columns_wrap_and_identifier_columns_do_not() {
        let long = "Configure firewalls and proxy servers so that inbound traffic is filtered";
        let src =
            format!("id,status,description\nKSI-CNA-2,modified,{long}\nKSI-CNA-4,same,short\n");
        let html = table(&src, Some("csv"));
        assert!(
            html.contains("<th class=\"wrap\">description</th>"),
            "{html}"
        );
        assert!(
            html.contains("<th>id</th>"),
            "identifier header stays rigid: {html}"
        );
        assert!(
            html.contains(&format!("<td class=\"wrap\">{long}</td>")),
            "{html}"
        );
        assert!(html.contains("<td>KSI-CNA-2</td>"), "{html}");
    }

    #[test]
    fn diff_lines_are_classified() {
        let html = diff("--- a\n+++ b\n@@ -1 +1 @@\n-old\n+new\n ctx\n");
        for c in ["meta", "hunk", "del", "add", "ctx"] {
            assert!(
                html.contains(&format!("class=\"ln {c}\"")),
                "missing {c}: {html}"
            );
        }
        let u = unified("a", "x\ny\n", "b", "x\nz\n");
        assert!(u.contains("-y") && u.contains("+z"));
    }
}