diff: Add highlight source-range machinery

517a81c7c1d61cca5ba86c6fda91104a8bfa919d
Tracks source ranges for visible diff rows so highlighting can run on precise
file spans.
Alexis Sellier committed ago 1 parent ee12de9c
crates/diff/benches/render.rs +6 -1
534 534
    viewer.apply(DiffAction::Resize, area);
535 535
}
536 536
537 537
/// Converts a highlight request into a deterministic synthetic result.
538 538
fn highlight_result(request: HighlightRequest) -> HighlightResult {
539 +
    let line = request
540 +
        .source
541 +
        .line(request.key.source_line)
542 +
        .unwrap_or_default();
543 +
539 544
    HighlightResult {
540 545
        key: request.key,
541 -
        line: Line::new(Label::from(request.text).fg(Color::Yellow)),
546 +
        line: Line::new(Label::from(line).fg(Color::Yellow)),
542 547
    }
543 548
}
544 549
545 550
/// Creates a deterministic Git-style unified diff.
546 551
fn synthetic_diff(shape: DiffShape) -> String {
src/file_{file:04}.rs\n" +0 -0
crates/diff/src/highlight.rs +202 -99
1 1
//! Highlight request and result protocol for diff rendering.
2 2
3 -
use std::collections::hash_map::DefaultHasher;
3 +
use std::collections::{BTreeMap, hash_map::DefaultHasher};
4 4
use std::hash::{Hash, Hasher as _};
5 5
use std::path::PathBuf;
6 +
use std::sync::Arc;
6 7
7 8
use rustik_highlight as syntax;
8 9
use rustik_tui as tui;
9 10
use rustik_tui::{Color, Label, Line, Style};
10 11
11 12
use crate::{FileId, HunkId, RowId};
12 13
13 14
/// Built-in fallback theme name.
14 15
const BUILTIN_THEME_NAME: &str = "rustik";
15 -
16 16
/// Built-in syntax theme JSON.
17 17
const BUILTIN_THEME: &str = include_str!("rustik.json");
18 18
19 19
/// Side of the diff used as syntax-highlighting source context.
20 20
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
51 51
pub struct HighlightRequest {
52 52
    /// Stable cache key for this request.
53 53
    pub key: HighlightKey,
54 54
    /// Source path used for syntax inference.
55 55
    pub path: Option<PathBuf>,
56 -
    /// Source text without a trailing line terminator.
57 -
    pub text: String,
56 +
    /// Source-side text used for range highlighting.
57 +
    pub source: HighlightSource,
58 58
}
59 59
60 60
/// Highlighted line returned by a worker.
61 61
#[derive(Clone, Debug)]
62 62
pub struct HighlightResult {
64 64
    pub key: HighlightKey,
65 65
    /// Renderable highlighted line.
66 66
    pub line: tui::Line,
67 67
}
68 68
69 +
/// File-side source text used to highlight a diff row with surrounding context.
70 +
#[derive(Clone, Debug, Eq, PartialEq)]
71 +
pub struct HighlightSource {
72 +
    /// Source-side text assembled from the diff.
73 +
    pub text: Arc<str>,
74 +
    /// Source line represented by the head of [`HighlightSource::text`].
75 +
    pub head: u32,
76 +
}
77 +
69 78
/// Pure built-in highlighter for visible diff rows.
70 79
#[derive(Debug)]
71 80
pub struct BuiltinHighlighter {
72 81
    /// Grammar and theme registry.
73 82
    registry: syntax::Registry,
74 -
    /// Reusable line scratch buffer.
75 -
    line: syntax::LineBuffer,
83 +
    /// Theme used when requests ask for automatic theme selection.
84 +
    default_theme: String,
85 +
}
86 +
87 +
/// Grouping key for requests that can share one range highlighter.
88 +
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
89 +
struct HighlightBatchKey {
90 +
    /// File containing the requested rows.
91 +
    file: FileId,
92 +
    /// Source side containing the requested rows.
93 +
    side: DiffSide,
94 +
    /// Syntax key requested by the viewer.
95 +
    syntax: String,
96 +
    /// Theme key requested by the viewer.
97 +
    theme: String,
98 +
    /// Path used for syntax inference.
99 +
    path: Option<PathBuf>,
100 +
    /// Source allocation identity.
101 +
    source: HighlightSourceId,
102 +
}
103 +
104 +
/// Allocation identity for source text shared by highlight requests.
105 +
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
106 +
struct HighlightSourceId {
107 +
    /// Address of the source text allocation.
108 +
    ptr: usize,
109 +
    /// Length of the source text allocation.
110 +
    len: usize,
111 +
    /// Source line represented by the head of the source text.
112 +
    head: u32,
76 113
}
77 114
78 115
impl HighlightKey {
79 116
    /// Creates a key for a row of source text.
80 117
    pub fn new(input: HighlightKeyInput<'_>) -> Self {
92 129
            theme: input.theme.to_owned(),
93 130
        }
94 131
    }
95 132
}
96 133
134 +
impl HighlightSource {
135 +
    /// Creates source text beginning at a source line.
136 +
    pub fn new(text: impl Into<Arc<str>>, head: u32) -> Self {
137 +
        Self {
138 +
            text: text.into(),
139 +
            head,
140 +
        }
141 +
    }
142 +
143 +
    /// Returns the zero-based source-text line index for a source line.
144 +
    pub fn line_index(&self, source_line: u32) -> Option<usize> {
145 +
        (source_line >= self.head).then_some((source_line - self.head) as usize)
146 +
    }
147 +
148 +
    /// Returns one source line without its trailing line terminator.
149 +
    pub fn line(&self, source_line: u32) -> Option<&str> {
150 +
        self.line_index(source_line)
151 +
            .and_then(|index| self.text.lines().nth(index))
152 +
    }
153 +
154 +
    /// Returns a compact identity for grouping requests that share this source.
155 +
    fn id(&self) -> HighlightSourceId {
156 +
        HighlightSourceId {
157 +
            ptr: self.text.as_ptr() as usize,
158 +
            len: self.text.len(),
159 +
            head: self.head,
160 +
        }
161 +
    }
162 +
}
163 +
97 164
impl BuiltinHighlighter {
98 -
    /// Loads the built-in grammar and theme support.
99 -
    pub fn new() -> Result<Self, syntax::Error> {
100 -
        let mut registry = syntax::Registry::with_builtin_syntaxes();
101 -
        registry.add_theme_json(BUILTIN_THEME)?;
102 -
        Ok(Self {
165 +
    /// Creates a highlighter from caller-loaded grammars and themes.
166 +
    pub fn new(registry: syntax::Registry, default_theme: impl Into<String>) -> Self {
167 +
        Self {
103 168
            registry,
104 -
            line: syntax::LineBuffer::default(),
105 -
        })
169 +
            default_theme: default_theme.into(),
170 +
        }
106 171
    }
107 172
108 173
    /// Highlights one request.
109 174
    pub fn highlight(&mut self, request: HighlightRequest) -> HighlightResult {
110 -
        let line = self.highlight_line(&request);
111 -
        HighlightResult {
112 -
            key: request.key,
113 -
            line,
114 -
        }
175 +
        self.highlight_group(vec![request]).remove(0)
115 176
    }
116 177
117 178
    /// Highlights multiple requests.
118 -
    pub fn highlight_requests<'a, I>(
119 -
        &'a mut self,
120 -
        requests: I,
121 -
    ) -> impl Iterator<Item = HighlightResult> + 'a
179 +
    pub fn highlight_requests<I>(&mut self, requests: I) -> impl Iterator<Item = HighlightResult>
122 180
    where
123 -
        I: IntoIterator<Item = HighlightRequest> + 'a,
181 +
        I: IntoIterator<Item = HighlightRequest>,
124 182
    {
125 -
        requests.into_iter().map(|request| self.highlight(request))
183 +
        let mut batches: BTreeMap<HighlightBatchKey, Vec<HighlightRequest>> = BTreeMap::new();
184 +
        for request in requests {
185 +
            batches
186 +
                .entry(HighlightBatchKey::from(&request))
187 +
                .or_default()
188 +
                .push(request);
189 +
        }
190 +
191 +
        batches
192 +
            .into_values()
193 +
            .flat_map(|requests| self.highlight_group(requests))
194 +
            .collect::<Vec<_>>()
195 +
            .into_iter()
126 196
    }
127 197
128 -
    /// Highlights a request into a TUI line.
129 -
    fn highlight_line(&mut self, request: &HighlightRequest) -> Line {
198 +
    /// Highlights grouped requests with one range highlighter.
199 +
    fn highlight_group(&mut self, requests: Vec<HighlightRequest>) -> Vec<HighlightResult> {
200 +
        let Some(first) = requests.first() else {
201 +
            return Vec::new();
202 +
        };
130 203
        let Ok(grammar) = self.registry.query(syntax::GrammarQuery {
131 -
            syntax: (request.key.syntax != "auto").then_some(request.key.syntax.as_str()),
132 -
            path: request.path.as_deref(),
133 -
            first_line: Some(&request.text),
204 +
            syntax: (first.key.syntax != "auto").then_some(first.key.syntax.as_str()),
205 +
            path: first.path.as_deref(),
206 +
            first_line: first.source.text.lines().next(),
134 207
        }) else {
135 -
            return Line::new(request.text.clone());
208 +
            return requests.into_iter().map(HighlightResult::plain).collect();
136 209
        };
137 -
        let theme_name = if request.key.theme == "auto" {
138 -
            BUILTIN_THEME_NAME
210 +
        let theme_name = if first.key.theme == "auto" {
211 +
            self.default_theme.as_str()
139 212
        } else {
140 -
            &request.key.theme
213 +
            &first.key.theme
141 214
        };
142 215
        let Ok(theme) = self.registry.theme_by_name(theme_name) else {
143 -
            return Line::new(request.text.clone());
216 +
            return requests.into_iter().map(HighlightResult::plain).collect();
144 217
        };
145 -
        let mut state = syntax::LineState::default();
146 -
        self.line.clear();
147 -
        let (_, spans) = self
148 -
            .line
149 -
            .highlight(grammar, theme, &mut state, &request.text);
150 -
151 -
        if request.text.is_empty() || spans.is_empty() {
152 -
            return Line::new(request.text.clone());
153 -
        }
154 -
        let mut line = Line::blank();
155 -
        let mut cursor = 0;
156 -
157 -
        for span in spans {
158 -
            if cursor < span.start {
159 -
                line.push(Label::new(&request.text[cursor..span.start]));
160 -
            }
161 -
            if span.start < span.end {
162 -
                line.push(
163 -
                    Label::new(&request.text[span.start..span.end]).style(span.style.tui_style()),
164 -
                );
165 -
            }
166 -
            cursor = span.end;
218 +
        let range = requests.iter().filter_map(|request| {
219 +
            request
220 +
                .source
221 +
                .line_index(request.key.source_line)
222 +
                .map(|line| line..line.saturating_add(1))
223 +
        });
224 +
        let mut start = usize::MAX;
225 +
        let mut end = 0;
226 +
        for range in range {
227 +
            start = start.min(range.start);
228 +
            end = end.max(range.end);
167 229
        }
168 -
        if cursor < request.text.len() {
169 -
            line.push(Label::new(&request.text[cursor..]));
230 +
        if start >= end {
231 +
            return requests.into_iter().map(HighlightResult::plain).collect();
170 232
        }
171 -
        line
233 +
        let mut lines = BTreeMap::new();
234 +
        let mut blob = syntax::BlobHighlighter::new(grammar, first.source.text.as_ref());
235 +
        blob.highlight_styled_range(theme, start..end, |line| {
236 +
            lines.insert(line.line_index, line_from_spans(line.text, line.styles));
237 +
        });
238 +
239 +
        requests
240 +
            .into_iter()
241 +
            .map(|request| {
242 +
                let line = request
243 +
                    .source
244 +
                    .line_index(request.key.source_line)
245 +
                    .and_then(|index| lines.remove(&index))
246 +
                    .unwrap_or_else(|| request.plain_line());
247 +
                HighlightResult {
248 +
                    key: request.key,
249 +
                    line,
250 +
                }
251 +
            })
252 +
            .collect()
172 253
    }
173 254
}
174 255
175 256
impl Default for BuiltinHighlighter {
176 257
    fn default() -> Self {
177 -
        Self::new().unwrap_or_else(|_| Self {
178 -
            registry: syntax::Registry::with_builtin_syntaxes(),
179 -
            line: syntax::LineBuffer::default(),
180 -
        })
258 +
        let mut registry = syntax::Registry::with_builtin_syntaxes();
259 +
        if registry.add_theme_json(BUILTIN_THEME).is_err() {
260 +
            registry = syntax::Registry::with_builtin_syntaxes();
261 +
        }
262 +
        Self::new(registry, BUILTIN_THEME_NAME)
263 +
    }
264 +
}
265 +
266 +
impl HighlightRequest {
267 +
    /// Returns the unhighlighted source row for this request.
268 +
    fn plain_line(&self) -> Line {
269 +
        self.source
270 +
            .line(self.key.source_line)
271 +
            .map(Line::new)
272 +
            .unwrap_or_default()
273 +
    }
274 +
}
275 +
276 +
impl HighlightResult {
277 +
    /// Returns a plain result for an unhighlightable request.
278 +
    fn plain(request: HighlightRequest) -> Self {
279 +
        let line = request.plain_line();
280 +
        Self {
281 +
            key: request.key,
282 +
            line,
283 +
        }
181 284
    }
182 285
}
183 286
287 +
impl From<&HighlightRequest> for HighlightBatchKey {
288 +
    fn from(request: &HighlightRequest) -> Self {
289 +
        Self {
290 +
            file: request.key.file,
291 +
            side: request.key.side,
292 +
            syntax: request.key.syntax.clone(),
293 +
            theme: request.key.theme.clone(),
294 +
            path: request.path.clone(),
295 +
            source: request.source.id(),
296 +
        }
297 +
    }
298 +
}
299 +
300 +
/// Converts style spans into a TUI line.
301 +
fn line_from_spans(text: &str, spans: &[syntax::StyleSpan]) -> Line {
302 +
    if text.is_empty() || spans.is_empty() {
303 +
        return Line::new(text);
304 +
    }
305 +
    let mut line = Line::blank();
306 +
    let mut cursor = 0;
307 +
308 +
    for span in spans {
309 +
        if cursor < span.start {
310 +
            line.push(Label::new(&text[cursor..span.start]));
311 +
        }
312 +
        if span.start < span.end {
313 +
            line.push(Label::new(&text[span.start..span.end]).style(span.style.tui_style()));
314 +
        }
315 +
        cursor = span.end;
316 +
    }
317 +
    if cursor < text.len() {
318 +
        line.push(Label::new(&text[cursor..]));
319 +
    }
320 +
    line
321 +
}
322 +
184 323
/// Input fields used to create a [`HighlightKey`].
185 324
#[derive(Clone, Copy, Debug)]
186 325
pub struct HighlightKeyInput<'a> {
187 326
    /// File containing the row.
188 327
    pub file: FileId,
227 366
            out = out.strikethrough();
228 367
        }
229 368
        out
230 369
    }
231 370
}
232 -
233 -
#[cfg(test)]
234 -
#[allow(clippy::expect_used)]
235 -
mod tests {
236 -
    use super::*;
237 -
238 -
    #[test]
239 -
    fn builtin_highlighter_renders_json_with_styles() {
240 -
        let mut highlighter = BuiltinHighlighter::new().expect("highlighter loads");
241 -
        let request = HighlightRequest {
242 -
            key: HighlightKey::new(HighlightKeyInput {
243 -
                file: FileId::new(0),
244 -
                hunk: HunkId::new(0),
245 -
                row: RowId::new(0),
246 -
                side: DiffSide::New,
247 -
                source_line: 1,
248 -
                text: "{\"ok\": true}",
249 -
                syntax: Some("json"),
250 -
                theme: "rustik",
251 -
            }),
252 -
            path: Some(PathBuf::from("data.json")),
253 -
            text: "{\"ok\": true}".to_owned(),
254 -
        };
255 -
256 -
        let result = highlighter.highlight(request);
257 -
258 -
        assert_eq!(result.line.to_string(), "{\"ok\": true}");
259 -
        assert!(
260 -
            result
261 -
                .line
262 -
                .labels()
263 -
                .iter()
264 -
                .any(|label| label.paint.style().fg_color() != Color::Unset)
265 -
        );
266 -
    }
267 -
}
crates/diff/src/lib.rs +1 -1
21 21
    FileMode, FileStats, Hunk, HunkHeader, HunkId, Oid, OidError, RowId, Stats,
22 22
};
23 23
pub use encode::Encode;
24 24
pub use highlight::{
25 25
    BuiltinHighlighter, DiffSide, HighlightKey, HighlightKeyInput, HighlightRequest,
26 -
    HighlightResult,
26 +
    HighlightResult, HighlightSource,
27 27
};
28 28
pub use renderer::{DiffAction, DiffFocus, DiffOptions, DiffState, DiffViewer, ViewChange};
crates/diff/src/renderer.rs +69 -4
10 10
};
11 11
12 12
use crate::highlight::{HighlightKeyInput, HighlightResult};
13 13
use crate::{
14 14
    DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff, FileId, FileKind, HighlightKey,
15 -
    HighlightRequest, Hunk, HunkId, RowId,
15 +
    HighlightRequest, HighlightSource, Hunk, HunkId, RowId,
16 16
};
17 17
18 18
/// Minimum width before the renderer attempts table-style diff rows.
19 19
const MIN_RENDER_COLS: usize = 12;
20 20
/// Width of old and new line number cells.
39 39
const NO_NEWLINE_MARKER: &str = "\\ No newline at end of file";
40 40
/// Marker cell shown between hunks in the diff marker column.
41 41
const HUNK_GAP_MARKER_CELL: &str = " ⋮ ";
42 42
/// Default highlight lookahead after the visible viewport.
43 43
const DEFAULT_HIGHLIGHT_LOOKAHEAD: usize = 4;
44 -
/// Default syntax theme name stored in highlight keys.
45 -
const DEFAULT_THEME: &str = "rustik";
44 +
/// Default syntax theme selection stored in highlight keys.
45 +
const DEFAULT_THEME: &str = "auto";
46 46
/// Number of rows in a sticky file header.
47 47
const STICKY_HEADER_ROWS: usize = 3;
48 48
49 49
/// Mutable read-only diff viewport state.
50 50
#[derive(Clone, Debug, Default, Eq, PartialEq)]
299 299
        let visible = (start..start.saturating_add(take))
300 300
            .filter_map(|row| self.render_row(row, ScrollView::body_cols(area))?.diff)
301 301
            .collect::<Vec<_>>();
302 302
303 303
        let mut requests = Vec::new();
304 +
        let mut sources = BTreeMap::new();
304 305
        for meta in visible {
305 306
            let key = HighlightKey::new(HighlightKeyInput {
306 307
                file: meta.file,
307 308
                hunk: meta.hunk,
308 309
                row: meta.row,
314 315
            });
315 316
            if self.highlights.contains_key(&key) || self.pending_highlights.contains(&key) {
316 317
                continue;
317 318
            }
318 319
            self.pending_highlights.insert(key.clone());
320 +
            let source = sources
321 +
                .entry((meta.file, meta.side))
322 +
                .or_insert_with(|| self.highlight_source(meta.file, meta.side))
323 +
                .clone();
319 324
            requests.push(HighlightRequest {
320 325
                key,
321 326
                path: meta.path,
322 -
                text: meta.text,
327 +
                source,
323 328
            });
324 329
        }
325 330
        requests
326 331
    }
327 332
364 369
365 370
        self.file_row_location(row)
366 371
            .map(|location| self.render_file_row(location, cols))
367 372
    }
368 373
374 +
    /// Returns source-side text for highlighting a file side.
375 +
    fn highlight_source(&self, file: FileId, side: DiffSide) -> HighlightSource {
376 +
        self.document
377 +
            .files
378 +
            .iter()
379 +
            .find(|candidate| candidate.id == file)
380 +
            .map(|file| file.highlight_source(side))
381 +
            .unwrap_or_else(|| HighlightSource::new("", 1))
382 +
    }
383 +
369 384
    /// Returns one rendered row inside a file card.
370 385
    fn render_file_row(&self, location: FileRowLocation<'_>, cols: usize) -> RenderRow {
371 386
        let file = location.file;
372 387
        let border = Self::file_border();
373 388
        let inner_cols = cols.saturating_sub(2);
885 900
                .clone()
886 901
                .or_else(|| self.header.old_path.clone()),
887 902
        }
888 903
    }
889 904
905 +
    /// Returns source-side text assembled from this diff's hunks.
906 +
    fn highlight_source(&self, side: DiffSide) -> HighlightSource {
907 +
        let head = self
908 +
            .hunks
909 +
            .first()
910 +
            .map(|hunk| hunk.source_start(side))
911 +
            .unwrap_or(1);
912 +
        let mut line_no = head;
913 +
        let mut text = String::new();
914 +
915 +
        for hunk in &self.hunks {
916 +
            let hunk_line = hunk.source_start(side);
917 +
            while line_no < hunk_line {
918 +
                text.push('\n');
919 +
                line_no += 1;
920 +
            }
921 +
            for line in &hunk.lines {
922 +
                if line.kind.appears_on(side) {
923 +
                    text.push_str(&line.text);
924 +
                    text.push('\n');
925 +
                    line_no += 1;
926 +
                }
927 +
            }
928 +
        }
929 +
930 +
        HighlightSource::new(text, head)
931 +
    }
932 +
890 933
    /// Returns a file header line.
891 934
    fn header_line(&self, cols: usize) -> Line {
892 935
        let mut left = Line::blank();
893 936
        left.push(Label::from_char(FILE_MARKER).fg(colors::fixed::DIM));
894 937
        left.push(Label::space());
978 1021
        path.map_or_else(|| "<unknown>".to_owned(), |path| path.display().to_string())
979 1022
    }
980 1023
}
981 1024
982 1025
impl crate::Hunk {
1026 +
    /// Returns the starting line for a source side.
1027 +
    fn source_start(&self, side: DiffSide) -> u32 {
1028 +
        match side {
1029 +
            DiffSide::Old => self.header.old_line_no,
1030 +
            DiffSide::New => self.header.new_line_no,
1031 +
        }
1032 +
    }
1033 +
983 1034
    /// Returns a hunk header line.
984 1035
    fn header_line(&self) -> Line {
985 1036
        Line::new(Label::new(&self.header_text()).fg(colors::fixed::FAINT))
986 1037
    }
987 1038
998 1049
            format!("{prefix} {}", header.text)
999 1050
        }
1000 1051
    }
1001 1052
}
1002 1053
1054 +
impl DiffLineKind {
1055 +
    /// Returns whether this line exists on a source side.
1056 +
    fn appears_on(self, side: DiffSide) -> bool {
1057 +
        match (self, side) {
1058 +
            (Self::Addition, DiffSide::New)
1059 +
            | (Self::Deletion, DiffSide::Old)
1060 +
            | (Self::Context, _) => true,
1061 +
            (Self::Addition, DiffSide::Old)
1062 +
            | (Self::Deletion, DiffSide::New)
1063 +
            | (Self::NoNewline, _) => false,
1064 +
        }
1065 +
    }
1066 +
}
1067 +
1003 1068
impl DiffLineMeta {
1004 1069
    /// Creates metadata for a source row.
1005 1070
    fn new(
1006 1071
        file: &FileDiff,
1007 1072
        hunk: HunkId,
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0