crates/highlight/src/blob.rs 14.3 KiB raw
1
//! Incremental highlighting over complete text blobs.
2
//!
3
//! This module sits above raw line tokenization and keeps the per-line parser
4
//! state needed by editor and pager workloads. Callers can ask for one line or
5
//! a visible range, and unchanged lines reuse cached start states and scope
6
//! spans instead of reparsing from the top of the file.
7
8
use std::ops::Range;
9
10
use crate::grammar::{Grammar, LineState, LineTokenizer, ScopeSpan};
11
use crate::theme::{StyleScratch, StyleSpan, Theme};
12
use crate::util::line_starts;
13
14
/// Scratch space for highlighting one line without reallocating per call.
15
///
16
/// A buffer holds the latest tokenization and styling results so callers can
17
/// reuse allocations while scanning many lines or repeatedly re-highlighting a
18
/// changing line.
19
#[derive(Debug, Default)]
20
pub struct LineBuffer {
21
    /// Current scope spans.
22
    pub scopes: Vec<ScopeSpan>,
23
    /// Current style spans.
24
    pub styles: Vec<StyleSpan>,
25
    /// Per-line scratch storage used when converting scope spans into style spans.
26
    style_scratch: StyleScratch,
27
}
28
29
/// Borrowed tokenization result for a line visited by a range highlighter.
30
///
31
/// This is the zero-copy callback view used when callers need grammar scopes
32
/// but not themed styles. The borrowed text and spans remain valid only for
33
/// the duration of the callback.
34
#[derive(Debug)]
35
pub struct LineTokens<'text, 'spans> {
36
    /// Zero-based line index in the blob.
37
    pub line_index: usize,
38
    /// Byte range of this line in the blob, excluding line terminators.
39
    pub byte_range: Range<usize>,
40
    /// Line text, excluding line terminators.
41
    pub text: &'text str,
42
    /// Scope spans for this line.
43
    pub scopes: &'spans [ScopeSpan],
44
}
45
46
/// Borrowed tokenization and styling result for a line visited by a range highlighter.
47
///
48
/// This is the zero-copy callback view used when callers need both grammar
49
/// scopes and theme-resolved style spans. The borrowed text and spans remain
50
/// valid only for the duration of the callback.
51
#[derive(Debug)]
52
pub struct StyledLine<'text, 'spans> {
53
    /// Zero-based line index in the blob.
54
    pub line_index: usize,
55
    /// Byte range of this line in the blob, excluding line terminators.
56
    pub byte_range: Range<usize>,
57
    /// Line text, excluding line terminators.
58
    pub text: &'text str,
59
    /// Scope spans for this line.
60
    pub scopes: &'spans [ScopeSpan],
61
    /// Styled spans for this line.
62
    pub styles: &'spans [StyleSpan],
63
}
64
65
/// Owned tokenization result for APIs that collect highlighted lines.
66
///
67
/// Unlike [`LineTokens`], this type owns its scope spans so callers can keep
68
/// the result after range traversal has moved on to another line.
69
#[derive(Clone, Debug, Eq, PartialEq)]
70
pub struct OwnedLineTokens {
71
    /// Zero-based line index in the blob.
72
    pub line_index: usize,
73
    /// Byte range of this line in the blob, excluding line terminators.
74
    pub byte_range: Range<usize>,
75
    /// Scope spans for this line.
76
    pub scopes: Vec<ScopeSpan>,
77
}
78
79
/// Owned per-line tokenization cache for [`BlobHighlighter`].
80
///
81
/// Callers that highlight the same source text repeatedly can keep one of
82
/// these between calls so the tokenizer state at the visible window is reused
83
/// instead of being rebuilt from the top of the file every time.
84
#[derive(Debug, Default)]
85
pub struct BlobCache {
86
    /// Byte offsets for each source line start.
87
    line_starts: Vec<usize>,
88
    /// Parser state at the start of each source line.
89
    states: Vec<Option<LineState>>,
90
    /// Cached scope spans for each source line.
91
    scopes: Vec<Option<Vec<ScopeSpan>>>,
92
    /// Reusable per-line scratch for styled range calls.
93
    buffer: LineBuffer,
94
}
95
96
/// Incremental highlighter for a complete text blob.
97
///
98
/// The highlighter caches parser states and per-line scope spans so callers can
99
/// ask for individual lines or ranges without reparsing the whole blob each
100
/// time. Editing callers should call [`BlobHighlighter::reset_text`] or
101
/// [`BlobHighlighter::invalidate_from`] to keep those caches aligned with the
102
/// backing text.
103
#[derive(Debug)]
104
pub struct BlobHighlighter<'text> {
105
    /// Reusable tokenizer for the backing grammar.
106
    tokenizer: LineTokenizer<'text>,
107
    /// Backing source text.
108
    text: &'text str,
109
    /// Per-line cache that may be reused across constructions.
110
    cache: BlobCache,
111
}
112
113
impl LineBuffer {
114
    /// Clears all buffered spans while retaining allocations.
115
    pub fn clear(&mut self) {
116
        self.scopes.clear();
117
        self.styles.clear();
118
        self.style_scratch.clear_line();
119
    }
120
121
    /// Tokenizes one line into this reusable buffer.
122
    pub fn tokenize<'a>(
123
        &'a mut self,
124
        grammar: &Grammar,
125
        state: &mut LineState,
126
        line: &str,
127
    ) -> &'a [ScopeSpan] {
128
        grammar.tokenize_line_into(state, line, &mut self.scopes);
129
        &self.scopes
130
    }
131
132
    /// Applies a theme to this buffer's current scope spans.
133
    pub fn style<'a>(
134
        &'a mut self,
135
        grammar: &Grammar,
136
        theme: &Theme,
137
        line: &str,
138
    ) -> &'a [StyleSpan] {
139
        theme.style_line_into(
140
            grammar,
141
            line,
142
            &self.scopes,
143
            &mut self.style_scratch,
144
            &mut self.styles,
145
        );
146
        &self.styles
147
    }
148
149
    /// Tokenizes and styles one line into this reusable buffer.
150
    pub fn highlight<'a>(
151
        &'a mut self,
152
        grammar: &Grammar,
153
        theme: &Theme,
154
        state: &mut LineState,
155
        line: &str,
156
    ) -> (&'a [ScopeSpan], &'a [StyleSpan]) {
157
        grammar.tokenize_line_into(state, line, &mut self.scopes);
158
        self.style(grammar, theme, line);
159
        (&self.scopes, &self.styles)
160
    }
161
}
162
163
impl<'text> BlobHighlighter<'text> {
164
    /// Creates a blob highlighter with an empty per-line cache.
165
    pub fn new(grammar: &'text Grammar, text: &'text str) -> Self {
166
        Self::with_cache(grammar, text, BlobCache::default())
167
    }
168
169
    /// Creates a blob highlighter that reuses a caller-owned per-line cache.
170
    pub fn with_cache(grammar: &'text Grammar, text: &'text str, mut cache: BlobCache) -> Self {
171
        cache.reset_for(text);
172
        Self {
173
            tokenizer: LineTokenizer::new(grammar),
174
            text,
175
            cache,
176
        }
177
    }
178
179
    /// Returns the per-line cache so it can be reused on the next call.
180
    pub fn into_cache(self) -> BlobCache {
181
        self.cache
182
    }
183
184
    /// Replaces the blob text and clears cached line states.
185
    pub fn reset_text(&mut self, text: &'text str) {
186
        self.text = text;
187
        self.cache.reset_for(text);
188
    }
189
190
    /// Returns the number of highlightable lines in the blob.
191
    pub fn line_count(&self) -> usize {
192
        self.cache.line_starts.len()
193
    }
194
195
    /// Returns a line by index, excluding line terminators.
196
    pub fn line(&self, line: usize) -> Option<&'text str> {
197
        let range = self.line_byte_range(line)?;
198
        Some(&self.text[range])
199
    }
200
201
    /// Returns a line's byte range, excluding line terminators.
202
    pub fn line_byte_range(&self, line: usize) -> Option<Range<usize>> {
203
        (line < self.line_count()).then(|| self.line_range_unchecked(line))
204
    }
205
206
    /// Returns whether a start state for `line` is already cached.
207
    pub fn is_state_cached(&self, line: usize) -> bool {
208
        self.cache.states.get(line).is_some_and(Option::is_some)
209
    }
210
211
    /// Invalidates cached states after a changed line.
212
    pub fn invalidate_from(&mut self, line: usize) {
213
        let start = line.saturating_add(1).min(self.cache.states.len());
214
        for state in &mut self.cache.states[start..] {
215
            *state = None;
216
        }
217
        let start = line.min(self.cache.scopes.len());
218
        for scopes in &mut self.cache.scopes[start..] {
219
            *scopes = None;
220
        }
221
    }
222
223
    /// Ensures the parser state at the start of `line` is cached.
224
    pub fn ensure_state(&mut self, line: usize) -> Option<&LineState> {
225
        if line > self.line_count() {
226
            return None;
227
        }
228
        if self.cache.states[line].is_none() {
229
            let state = self.compute_state(line)?;
230
            self.cache.states[line] = Some(state);
231
        }
232
        self.cache.states[line].as_ref()
233
    }
234
235
    /// Tokenizes one line into a caller-owned buffer.
236
    pub fn highlight_line_into(&mut self, line: usize, scopes: &mut Vec<ScopeSpan>) -> bool {
237
        if line >= self.line_count() {
238
            scopes.clear();
239
            return false;
240
        }
241
        let Some(mut state) = self.ensure_state(line).cloned() else {
242
            scopes.clear();
243
            return false;
244
        };
245
        let range = self.line_range_unchecked(line);
246
        let text = &self.text[range];
247
248
        tokenize_or_cache_into(
249
            &mut self.tokenizer,
250
            &mut self.cache.states,
251
            &mut self.cache.scopes,
252
            &mut state,
253
            line,
254
            text,
255
            scopes,
256
        );
257
        true
258
    }
259
260
    /// Tokenizes a line range and invokes `f` for each requested line.
261
    pub fn highlight_range<F>(&mut self, range: Range<usize>, mut f: F)
262
    where
263
        F: FnMut(LineTokens<'_, '_>),
264
    {
265
        let start = range.start.min(self.line_count());
266
        let end = range.end.min(self.line_count());
267
        if start >= end {
268
            return;
269
        }
270
        let Some(mut state) = self.ensure_state(start).cloned() else {
271
            return;
272
        };
273
274
        let mut scopes = Vec::new();
275
        for line_index in start..end {
276
            let byte_range = self.line_range_unchecked(line_index);
277
            let text = &self.text[byte_range.clone()];
278
279
            tokenize_or_cache_into(
280
                &mut self.tokenizer,
281
                &mut self.cache.states,
282
                &mut self.cache.scopes,
283
                &mut state,
284
                line_index,
285
                text,
286
                &mut scopes,
287
            );
288
            f(LineTokens {
289
                line_index,
290
                byte_range,
291
                text,
292
                scopes: &scopes,
293
            });
294
        }
295
    }
296
297
    /// Tokenizes and styles a line range and invokes `f` for each requested line.
298
    pub fn highlight_styled_range<F>(&mut self, theme: &Theme, range: Range<usize>, mut f: F)
299
    where
300
        F: FnMut(StyledLine<'_, '_>),
301
    {
302
        let start = range.start.min(self.line_count());
303
        let end = range.end.min(self.line_count());
304
        if start >= end {
305
            return;
306
        }
307
        let Some(mut state) = self.ensure_state(start).cloned() else {
308
            return;
309
        };
310
311
        let grammar = self.tokenizer.grammar;
312
        for line_index in start..end {
313
            let byte_range = self.line_range_unchecked(line_index);
314
            let text = &self.text[byte_range.clone()];
315
316
            tokenize_or_cache_into(
317
                &mut self.tokenizer,
318
                &mut self.cache.states,
319
                &mut self.cache.scopes,
320
                &mut state,
321
                line_index,
322
                text,
323
                &mut self.cache.buffer.scopes,
324
            );
325
            self.cache.buffer.style(grammar, theme, text);
326
327
            f(StyledLine {
328
                line_index,
329
                byte_range,
330
                text,
331
                scopes: &self.cache.buffer.scopes,
332
                styles: &self.cache.buffer.styles,
333
            });
334
        }
335
    }
336
337
    /// Tokenizes a line range into an owned output vector.
338
    pub fn highlight_range_into(&mut self, range: Range<usize>, output: &mut Vec<OwnedLineTokens>) {
339
        output.clear();
340
341
        self.highlight_range(range, |line| {
342
            output.push(OwnedLineTokens {
343
                line_index: line.line_index,
344
                byte_range: line.byte_range,
345
                scopes: line.scopes.to_vec(),
346
            });
347
        });
348
    }
349
350
    /// Returns newly allocated token data for a line range.
351
    pub fn highlighted_range(&mut self, range: Range<usize>) -> Vec<OwnedLineTokens> {
352
        let mut output = Vec::new();
353
        self.highlight_range_into(range, &mut output);
354
        output
355
    }
356
357
    /// Computes the parser state at the start of `line` from the nearest cached predecessor.
358
    fn compute_state(&mut self, line: usize) -> Option<LineState> {
359
        let mut index = line;
360
        while index > 0 && self.cache.states[index].is_none() {
361
            index -= 1;
362
        }
363
        let mut state = self.cache.states[index].clone().unwrap_or_default();
364
        let mut scratch = Vec::new();
365
366
        while index < line {
367
            let range = self.line_range_unchecked(index);
368
            let text = &self.text[range];
369
370
            self.tokenizer
371
                .tokenize_line_into(&mut state, text, &mut scratch);
372
373
            index += 1;
374
            self.cache.states[index] = Some(state.clone());
375
        }
376
        Some(state)
377
    }
378
379
    /// Returns a line's byte range without checking that the line index exists.
380
    fn line_range_unchecked(&self, line: usize) -> Range<usize> {
381
        let start = self.cache.line_starts[line];
382
        let mut end = self
383
            .cache
384
            .line_starts
385
            .get(line + 1)
386
            .copied()
387
            .unwrap_or(self.text.len());
388
        let bytes = self.text.as_bytes();
389
        if end > start && bytes[end - 1] == b'\n' {
390
            end -= 1;
391
        }
392
        if end > start && bytes[end - 1] == b'\r' {
393
            end -= 1;
394
        }
395
        start..end
396
    }
397
}
398
399
impl BlobCache {
400
    /// Rebuilds this cache if `text` has a different line layout.
401
    fn reset_for(&mut self, text: &str) {
402
        let line_starts = line_starts(text);
403
        if self.line_starts == line_starts {
404
            return;
405
        }
406
        self.line_starts = line_starts;
407
        self.states.clear();
408
        self.states.resize(self.line_starts.len() + 1, None);
409
        self.states[0] = Some(LineState::default());
410
        self.scopes.clear();
411
        self.scopes.resize(self.line_starts.len(), None);
412
        self.buffer.clear();
413
    }
414
}
415
416
/// Tokenizes a line or copies its cached scopes and following parser state.
417
fn tokenize_or_cache_into(
418
    tokenizer: &mut LineTokenizer<'_>,
419
    states: &mut [Option<LineState>],
420
    scopes_cache: &mut [Option<Vec<ScopeSpan>>],
421
    state: &mut LineState,
422
    line_index: usize,
423
    text: &str,
424
    out: &mut Vec<ScopeSpan>,
425
) {
426
    if let Some(cached) = scopes_cache[line_index].as_ref()
427
        && let Some(next_state) = states[line_index + 1].as_ref()
428
    {
429
        out.clone_from(cached);
430
        *state = next_state.clone();
431
    } else {
432
        tokenizer.tokenize_line_into(state, text, out);
433
434
        states[line_index + 1] = Some(state.clone());
435
        scopes_cache[line_index] = Some(out.clone());
436
    }
437
}