rustik-diff 0.3.0

Pure diff viewer and Git diff pager for Rustik.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
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
//! Highlight request and result protocol for diff rendering.

use std::collections::{BTreeMap, hash_map::DefaultHasher};
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use rustik_highlight as syntax;
use rustik_tui as tui;
use rustik_tui::{Color, Label, Line, Style};

use crate::{DiffLine, FileDiff, FileId, Hunk, HunkId, RowId};

/// Side of the diff used as syntax-highlighting source context.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum DiffSide {
    /// Old side of a deleted or context line.
    Old,
    /// New side of an added or context line.
    New,
}

/// Cache key for one highlighted diff row.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct HighlightKey {
    /// File containing the row.
    pub file: FileId,
    /// Diff side to highlight.
    pub side: DiffSide,
    /// One-based source line number.
    pub source_line: u32,
    /// Hash of the row text.
    pub text_hash: u64,
    /// Syntax key or `auto`.
    pub syntax: String,
    /// Theme key.
    pub theme: String,
}

/// Request sent from a visible diff viewport to a highlighter.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HighlightRequest {
    /// Stable cache key for this request.
    pub key: HighlightKey,
    /// Hunk containing the row.
    pub hunk: HunkId,
    /// Row to highlight.
    pub row: RowId,
    /// Source path used for syntax inference.
    pub path: Option<PathBuf>,
    /// Source-side text used for range highlighting.
    pub source: HighlightSource,
}

/// Highlighted line returned by a worker.
#[derive(Clone, Debug)]
pub struct HighlightResult {
    /// Cache key copied from the original request.
    pub key: HighlightKey,
    /// Hunk containing the highlighted row.
    pub hunk: HunkId,
    /// Highlighted row.
    pub row: RowId,
    /// Renderable highlighted line.
    pub line: tui::Line,
}

/// File-side source text used to highlight a diff row with surrounding context.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HighlightSource {
    /// Source-side text assembled from the diff.
    pub text: Arc<str>,
    /// Source line represented by the head of [`HighlightSource::text`].
    pub head: u32,
    /// Byte offset of each source line.
    line_starts: Arc<[u32]>,
}

/// Pure built-in highlighter for visible diff rows.
#[derive(Debug)]
pub struct BuiltinHighlighter {
    /// Grammar and theme registry.
    registry: syntax::Registry,
    /// Theme used when requests ask for automatic theme selection.
    default_theme: String,
    /// Per-source tokenizer caches reused across batches.
    blob_caches: BTreeMap<BlobCacheKey, BlobCacheEntry>,
}

/// Identifier for cached blob-highlight state.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
struct BlobCacheKey {
    /// Grammar name used to tokenize the source.
    grammar: String,
    /// Address of the cached source allocation.
    text_ptr: usize,
    /// Length of the cached source allocation.
    text_len: usize,
}

/// Cached tokenizer state for one source allocation.
#[derive(Debug)]
struct BlobCacheEntry {
    /// Source owner that keeps the cached allocation pinned.
    _source: Arc<str>,
    /// Per-line parser state and scope cache.
    cache: syntax::BlobCache,
}

/// Highlights diff rows requested by a [`crate::DiffViewer`].
pub trait DiffHighlighter {
    /// Highlights one batch of visible diff rows.
    fn highlight_batch(&mut self, requests: Vec<HighlightRequest>) -> Vec<HighlightResult>;
}

/// Grouping key for requests that can share one range highlighter.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
struct HighlightBatchKey {
    /// File containing the requested rows.
    file: FileId,
    /// Source side containing the requested rows.
    side: DiffSide,
    /// Syntax key requested by the viewer.
    syntax: String,
    /// Theme key requested by the viewer.
    theme: String,
    /// Path used for syntax inference.
    path: Option<PathBuf>,
    /// Source allocation identity.
    source: HighlightSourceId,
}

/// Allocation identity for source text shared by highlight requests.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
struct HighlightSourceId {
    /// Address of the source text allocation.
    ptr: usize,
    /// Length of the source text allocation.
    len: usize,
    /// Source line represented by the head of the source text.
    head: u32,
}

impl HighlightKey {
    /// Creates a key for a row of source text.
    pub fn new(input: HighlightKeyInput<'_>) -> Self {
        let mut hasher = DefaultHasher::new();
        input.text.hash(&mut hasher);

        Self {
            file: input.file,
            side: input.side,
            source_line: input.source_line,
            text_hash: hasher.finish(),
            syntax: input.syntax.unwrap_or("auto").to_owned(),
            theme: input.theme.to_owned(),
        }
    }
}

impl HighlightSource {
    /// Creates source text beginning at a source line.
    pub fn new(text: impl Into<Arc<str>>, head: u32) -> Self {
        let text = text.into();
        let mut line_starts = Vec::new();
        if !text.is_empty() {
            line_starts.push(0);
            line_starts.extend(
                text.bytes()
                    .enumerate()
                    .filter(|(index, byte)| *byte == b'\n' && index + 1 < text.len())
                    .map(|(index, _)| (index + 1) as u32),
            );
        }
        Self {
            text,
            head,
            line_starts: line_starts.into(),
        }
    }

    /// Returns the zero-based source-text line index for a source line.
    pub fn line_index(&self, source_line: u32) -> Option<usize> {
        source_line.checked_sub(self.head).map(|line| line as usize)
    }

    /// Returns one source line without its trailing line terminator.
    pub fn line(&self, source_line: u32) -> Option<&str> {
        let index = self.line_index(source_line)?;
        self.indexed_line(index)
    }

    /// Returns one source line by its zero-based index.
    fn indexed_line(&self, index: usize) -> Option<&str> {
        let start = *self.line_starts.get(index)? as usize;
        let mut end = self
            .line_starts
            .get(index + 1)
            .map_or(self.text.len(), |next| *next as usize);
        if end > start && self.text.as_bytes()[end - 1] == b'\n' {
            end -= 1;
        }
        if end > start && self.text.as_bytes()[end - 1] == b'\r' {
            end -= 1;
        }
        Some(&self.text[start..end])
    }

    /// Returns the bytes retained by this source and its line index.
    pub(crate) fn retained_bytes(&self) -> usize {
        self.text
            .len()
            .saturating_add(self.line_starts.len() * size_of::<u32>())
    }

    /// Returns whether this source reproduces every row `hunk` shows on `side`.
    ///
    /// Highlighted rows are rendered from the source text, not the diff, so a
    /// source that has drifted from the patch would display lines the patch
    /// never contained. Worktree files drift whenever they are edited after the
    /// diff was produced.
    pub fn matches_hunk(&self, hunk: &Hunk, side: DiffSide) -> bool {
        let Some(mut line) = self.line_index(hunk_head(hunk, side)) else {
            return false;
        };

        hunk.lines
            .iter()
            .filter(|line| source_len(line, side) != 0)
            .all(|expected| {
                let matches = self.indexed_line(line) == Some(expected.text.as_str());
                line += 1;
                matches
            })
    }

    /// Returns a compact identity for grouping requests that share this source.
    fn id(&self) -> HighlightSourceId {
        HighlightSourceId {
            ptr: self.text.as_ptr() as usize,
            len: self.text.len(),
            head: self.head,
        }
    }
}

impl Hunk {
    /// Builds contiguous source text for one hunk side.
    pub fn highlight_source(&self, side: DiffSide) -> HighlightSource {
        let mut text = String::new();
        push_hunk_source_lines(self, side, &mut text);
        HighlightSource::new(text, hunk_head(self, side))
    }
}

impl FileDiff {
    /// Returns the source path for a file side, falling back to the other side.
    pub fn source_path(&self, side: DiffSide) -> Option<PathBuf> {
        let (primary, fallback) = match side {
            DiffSide::Old => (&self.header.old_path, &self.header.new_path),
            DiffSide::New => (&self.header.new_path, &self.header.old_path),
        };
        primary.clone().or_else(|| fallback.clone())
    }

    /// Builds contiguous source text for one file side.
    ///
    /// Returns `None` when the file's hunks are not contiguous on `side`.
    pub fn highlight_source(&self, side: DiffSide) -> Option<HighlightSource> {
        let mut text = String::new();
        let mut head = None;
        let mut next_line = None;

        for hunk in &self.hunks {
            let hunk_head = hunk_head(hunk, side);
            if next_line.is_some_and(|line| line != hunk_head) {
                return None;
            }
            head.get_or_insert(hunk_head);
            push_hunk_source_lines(hunk, side, &mut text);
            let len = hunk
                .lines
                .iter()
                .map(|line| source_len(line, side))
                .sum::<u32>();
            next_line = Some(hunk_head + len);
        }
        head.map(|head| HighlightSource::new(text, head))
    }
}

/// Appends source-side hunk lines to `text`.
///
/// Blank lines are kept so a [`HighlightSource`] line index stays aligned with
/// its source line number.
fn push_hunk_source_lines(hunk: &Hunk, side: DiffSide, text: &mut String) {
    let mut first = text.is_empty();

    for line in &hunk.lines {
        if source_len(line, side) == 0 {
            continue;
        }
        if first {
            first = false;
        } else {
            text.push('\n');
        }
        text.push_str(&line.text);
    }
}

/// Returns the first source line for one hunk side.
fn hunk_head(hunk: &Hunk, side: DiffSide) -> u32 {
    match side {
        DiffSide::Old => hunk.header.old_line_no,
        DiffSide::New => hunk.header.new_line_no,
    }
}

/// Returns how many source lines a diff line contributes on `side`.
fn source_len(line: &DiffLine, side: DiffSide) -> u32 {
    match side {
        DiffSide::Old => line.kind.old_len(),
        DiffSide::New => line.kind.new_len(),
    }
}

impl BuiltinHighlighter {
    /// Creates a highlighter from caller-loaded grammars and themes.
    pub fn new(registry: syntax::Registry, default_theme: impl Into<String>) -> Self {
        Self {
            registry,
            default_theme: default_theme.into(),
            blob_caches: BTreeMap::new(),
        }
    }

    /// Adds `grammar` to this highlighter if a grammar with the same name is absent.
    pub fn ensure_grammar(&mut self, grammar: syntax::Grammar) {
        if self.registry.grammar_by_name(&grammar.name).is_err() {
            self.registry.add_grammar(grammar);
        }
    }

    /// Returns whether a path selects a loaded non-plain grammar.
    pub fn has_path_grammar(&self, path: &Path) -> bool {
        self.registry
            .query(syntax::GrammarQuery {
                syntax: None,
                path: Some(path),
                head: None,
            })
            .is_ok_and(|grammar| grammar.scope_name != "text.plain")
    }

    /// Highlights one request.
    pub fn highlight(&mut self, request: HighlightRequest) -> HighlightResult {
        self.highlight_group(vec![request]).remove(0)
    }

    /// Highlights multiple requests.
    pub fn highlight_requests<I>(&mut self, requests: I) -> Vec<HighlightResult>
    where
        I: IntoIterator<Item = HighlightRequest>,
    {
        let mut batches: BTreeMap<HighlightBatchKey, Vec<HighlightRequest>> = BTreeMap::new();
        for request in requests {
            batches
                .entry(HighlightBatchKey::from(&request))
                .or_default()
                .push(request);
        }

        batches
            .into_values()
            .flat_map(|requests| self.highlight_group(requests))
            .collect()
    }

    /// Highlights grouped requests with one range highlighter.
    fn highlight_group(&mut self, requests: Vec<HighlightRequest>) -> Vec<HighlightResult> {
        let Some(first) = requests.first() else {
            return Vec::new();
        };
        let Ok(grammar) = self.registry.query(syntax::GrammarQuery {
            syntax: (first.key.syntax != "auto").then_some(first.key.syntax.as_str()),
            path: first.path.as_deref(),
            head: first.source.text.lines().next(),
        }) else {
            return requests.into_iter().map(HighlightResult::plain).collect();
        };
        let theme_name = if first.key.theme == "auto" {
            self.default_theme.as_str()
        } else {
            &first.key.theme
        };
        let Ok(theme) = self.registry.theme_by_name(theme_name) else {
            return requests.into_iter().map(HighlightResult::plain).collect();
        };
        let range = requests.iter().filter_map(|request| {
            request
                .source
                .line_index(request.key.source_line)
                .map(|line| line..line.saturating_add(1))
        });
        let mut start = usize::MAX;
        let mut end = 0;
        for range in range {
            start = start.min(range.start);
            end = end.max(range.end);
        }
        if start >= end {
            return requests.into_iter().map(HighlightResult::plain).collect();
        }
        let source = first.source.text.clone();
        let cache_key = BlobCacheKey {
            grammar: grammar.name.clone(),
            text_ptr: source.as_ptr() as usize,
            text_len: source.len(),
        };
        let cache = self
            .blob_caches
            .remove(&cache_key)
            .map(|entry| entry.cache)
            .unwrap_or_default();

        let mut lines = BTreeMap::new();
        let cache = {
            let mut blob = syntax::BlobHighlighter::with_cache(grammar, source.as_ref(), cache);
            blob.highlight_styled_range(theme, start..end, |line| {
                lines.insert(line.line_index, line_from_spans(line.text, line.styles));
            });
            blob.into_cache()
        };
        self.blob_caches.insert(
            cache_key,
            BlobCacheEntry {
                _source: source,
                cache,
            },
        );

        requests
            .into_iter()
            .map(|request| {
                let line = request
                    .source
                    .line_index(request.key.source_line)
                    .and_then(|index| lines.remove(&index))
                    .unwrap_or_else(|| request.plain_line());
                HighlightResult::new(request, line)
            })
            .collect()
    }
}

impl DiffHighlighter for BuiltinHighlighter {
    fn highlight_batch(&mut self, requests: Vec<HighlightRequest>) -> Vec<HighlightResult> {
        self.highlight_requests(requests)
    }
}

impl HighlightRequest {
    /// Returns the unhighlighted source row for this request.
    fn plain_line(&self) -> Line {
        self.source
            .line(self.key.source_line)
            .map(Line::new)
            .unwrap_or_default()
    }
}

impl HighlightResult {
    /// Pairs a highlighted line with the metadata copied from its request.
    pub fn new(request: HighlightRequest, line: Line) -> Self {
        Self {
            key: request.key,
            hunk: request.hunk,
            row: request.row,
            line,
        }
    }

    /// Returns a plain result for an unhighlightable request.
    fn plain(request: HighlightRequest) -> Self {
        let line = request.plain_line();
        Self::new(request, line)
    }
}

impl From<&HighlightRequest> for HighlightBatchKey {
    fn from(request: &HighlightRequest) -> Self {
        Self {
            file: request.key.file,
            side: request.key.side,
            syntax: request.key.syntax.clone(),
            theme: request.key.theme.clone(),
            path: request.path.clone(),
            source: request.source.id(),
        }
    }
}

/// Converts style spans into a TUI line.
fn line_from_spans(text: &str, spans: &[syntax::StyleSpan]) -> Line {
    if text.is_empty() || spans.is_empty() {
        return Line::new(text);
    }
    let mut line = Line::blank();
    let mut cursor = 0;

    for span in spans {
        if cursor < span.start {
            line.push(Label::new(&text[cursor..span.start]));
        }
        if span.start < span.end {
            line.push(Label::new(&text[span.start..span.end]).style(span.style.tui_style()));
        }
        cursor = span.end;
    }
    if cursor < text.len() {
        line.push(Label::new(&text[cursor..]));
    }
    line
}

/// Input fields used to create a [`HighlightKey`].
#[derive(Clone, Copy, Debug)]
pub struct HighlightKeyInput<'a> {
    /// File containing the row.
    pub file: FileId,
    /// Diff side to highlight.
    pub side: DiffSide,
    /// One-based source line number.
    pub source_line: u32,
    /// Source text.
    pub text: &'a str,
    /// Optional syntax override.
    pub syntax: Option<&'a str>,
    /// Theme name.
    pub theme: &'a str,
}

/// Converts syntax styles into TUI styles.
trait SyntaxStyleExt {
    /// Converts this syntax style into a TUI style.
    fn tui_style(self) -> Style;
}

impl SyntaxStyleExt for syntax::Style {
    fn tui_style(self) -> Style {
        let mut out = Style::default();
        if let Some(color) = self.foreground {
            out = out.fg(Color::RGB(color.r, color.g, color.b));
        }
        if self.font_style.contains(syntax::FontStyle::BOLD) {
            out = out.bold();
        }
        if self.font_style.contains(syntax::FontStyle::ITALIC) {
            out = out.italic();
        }
        if self.font_style.contains(syntax::FontStyle::UNDERLINE) {
            out = out.underline();
        }
        if self.font_style.contains(syntax::FontStyle::STRIKETHROUGH) {
            out = out.strikethrough();
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Decode;
    use std::str::FromStr;

    #[test]
    fn source_lines_before_head_are_absent() {
        let source = HighlightSource::new("two\nthree\n", 2);

        assert_eq!(source.line_index(1), None);
        assert_eq!(source.line(1), None);
        assert_eq!(source.line_index(2), Some(0));
        assert_eq!(source.line(2), Some("two"));
    }

    #[test]
    fn indexed_source_lines_match_rust_line_boundaries() {
        let source = HighlightSource::new("one\r\ntwo\n\nthree", 1);

        assert_eq!(source.line(1), Some("one"));
        assert_eq!(source.line(2), Some("two"));
        assert_eq!(source.line(3), Some(""));
        assert_eq!(source.line(4), Some("three"));
        assert_eq!(source.line(5), None);
    }

    #[test]
    fn file_highlight_source_spans_the_new_side() {
        let document = crate::DiffDocument::decode_str(
            "\
diff --git a/a.css b/a.css
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.css
+++ b/a.css
@@ -1,3 +1,3 @@
 .x {
-background: url(old.svg);
+background: url(new.svg);
 }
",
        )
        .unwrap();
        let source = document.files[0].highlight_source(DiffSide::New).unwrap();

        assert_eq!(source.head, 1);
        assert_eq!(source.line(1), Some(".x {"));
        assert_eq!(source.line(2), Some("background: url(new.svg);"));
        assert_eq!(source.line(3), Some("}"));
    }

    #[test]
    fn highlight_source_keeps_a_leading_blank_line() {
        // A hunk whose first source line is blank must not collapse it away,
        // or every later line index shifts up by one against its line number.
        // The blank context line is a single space; spell the fixture with
        // `concat!` so that space cannot be mistaken for trailing whitespace.
        let document = crate::DiffDocument::decode_str(concat!(
            "diff --git a/a.rs b/a.rs\n",
            "index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644\n",
            "--- a/a.rs\n",
            "+++ b/a.rs\n",
            "@@ -2,3 +2,3 @@\n",
            " \n",
            "-old\n",
            "+new\n",
            " tail\n",
        ))
        .unwrap();
        let hunk = &document.files[0].hunks[0];

        let source = hunk.highlight_source(DiffSide::New);
        assert_eq!(source.head, 2);
        assert_eq!(source.line(2), Some(""));
        assert_eq!(source.line(3), Some("new"));
        assert_eq!(source.line(4), Some("tail"));

        let file = document.files[0].highlight_source(DiffSide::New).unwrap();
        assert_eq!(file.line(2), Some(""));
        assert_eq!(file.line(3), Some("new"));
    }

    #[cfg(feature = "builtins")]
    #[test]
    fn css_custom_properties_use_variable_theme_style() {
        let grammar = syntax::Grammar::from_str(syntax::syntaxes::CSS).unwrap();
        let theme =
            syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap();
        let line = "  --color-background-light: #dad8d8;";
        let mut state = syntax::LineState::default();
        let mut tokenizer = syntax::LineTokenizer::new(&grammar);
        let _ = tokenizer.tokenize_line(&mut state, ":root {");
        let spans = tokenizer.tokenize_line(&mut state, line);
        let styles = theme.style_spans(&grammar, line, &spans);
        let custom_property = line.find("--color-background-light").unwrap();
        let style = styles
            .iter()
            .find(|style| style.start <= custom_property && style.end > custom_property)
            .unwrap();

        assert!(scopes_for_byte(&grammar, &spans, custom_property).contains(&"variable.css"));
        assert_eq!(
            style.style.foreground,
            Some(syntax::Rgb {
                r: 137,
                g: 180,
                b: 250
            })
        );
    }

    #[cfg(feature = "builtins")]
    #[test]
    fn css_var_references_use_variable_theme_style() {
        let grammar = syntax::Grammar::from_str(syntax::syntaxes::CSS).unwrap();
        let theme =
            syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap();
        let line = "  color: var(--color-dimmer);";
        let mut state = syntax::LineState::default();
        let mut tokenizer = syntax::LineTokenizer::new(&grammar);
        let _ = tokenizer.tokenize_line(&mut state, ".note-meta {");
        let spans = tokenizer.tokenize_line(&mut state, line);
        let styles = theme.style_spans(&grammar, line, &spans);
        let variable = line.find("--color-dimmer").unwrap();
        let style = styles
            .iter()
            .find(|style| style.start <= variable && style.end > variable)
            .unwrap();

        assert!(scopes_for_byte(&grammar, &spans, variable).contains(&"variable.argument.css"));
        assert_eq!(
            style.style.foreground,
            Some(syntax::Rgb {
                r: 235,
                g: 160,
                b: 172
            })
        );
    }

    #[cfg(feature = "builtins")]
    #[test]
    fn rust_signature_parameters_use_normal_theme_style() {
        let grammar = syntax::Grammar::from_str(syntax::syntaxes::RUST).unwrap();
        let theme =
            syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap();
        let line = "    mut cursor: String,";
        let mut state = syntax::LineState::default();
        let mut tokenizer = syntax::LineTokenizer::new(&grammar);
        let _ = tokenizer.tokenize_line(&mut state, "fn reconcile_with<C, E>(");
        let spans = tokenizer.tokenize_line(&mut state, line);
        let styles = theme.style_spans(&grammar, line, &spans);
        let parameter = line.find("cursor").unwrap();
        let style = styles
            .iter()
            .find(|style| style.start <= parameter && style.end > parameter)
            .unwrap();

        assert!(scopes_for_byte(&grammar, &spans, parameter).contains(&"variable.parameter.rust"));
        assert_eq!(
            style.style.foreground,
            Some(syntax::Rgb {
                r: 205,
                g: 214,
                b: 244
            })
        );
    }

    fn scopes_for_byte<'a>(
        grammar: &'a syntax::Grammar,
        spans: &'a [syntax::ScopeSpan],
        byte: usize,
    ) -> Vec<&'a str> {
        spans
            .iter()
            .filter(|span| span.start <= byte && span.end > byte)
            .filter_map(|span| grammar.scopes.get(span.scope.index()))
            .map(String::as_str)
            .collect()
    }
}