1use std::collections::{BTreeMap, hash_map::DefaultHasher};
4use std::hash::{Hash, Hasher};
5use std::path::PathBuf;
6use std::sync::Arc;
7
8use rustik_highlight as syntax;
9use rustik_tui as tui;
10use rustik_tui::{Color, Label, Line, Style};
11
12use crate::{DiffLine, FileDiff, FileId, Hunk, HunkId, RowId};
13
14#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
16pub enum DiffSide {
17 Old,
19 New,
21}
22
23#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
25pub struct HighlightKey {
26 pub file: FileId,
28 pub side: DiffSide,
30 pub source_line: u32,
32 pub text_hash: u64,
34 pub syntax: String,
36 pub theme: String,
38}
39
40#[derive(Clone, Debug, Eq, PartialEq)]
42pub struct HighlightRequest {
43 pub key: HighlightKey,
45 pub hunk: HunkId,
47 pub row: RowId,
49 pub path: Option<PathBuf>,
51 pub source: HighlightSource,
53}
54
55#[derive(Clone, Debug)]
57pub struct HighlightResult {
58 pub key: HighlightKey,
60 pub hunk: HunkId,
62 pub row: RowId,
64 pub line: tui::Line,
66}
67
68#[derive(Clone, Debug, Eq, PartialEq)]
70pub struct HighlightSource {
71 pub text: Arc<str>,
73 pub head: u32,
75}
76
77#[derive(Debug)]
79pub struct BuiltinHighlighter {
80 registry: syntax::Registry,
82 default_theme: String,
84 blob_caches: BTreeMap<BlobCacheKey, BlobCacheEntry>,
86}
87
88#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
90struct BlobCacheKey {
91 grammar: String,
93 text_ptr: usize,
95 text_len: usize,
97}
98
99#[derive(Debug)]
101struct BlobCacheEntry {
102 _source: Arc<str>,
104 cache: syntax::BlobCache,
106}
107
108pub trait DiffHighlighter {
110 fn highlight_batch(&mut self, requests: Vec<HighlightRequest>) -> Vec<HighlightResult>;
112}
113
114#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
116struct HighlightBatchKey {
117 file: FileId,
119 side: DiffSide,
121 syntax: String,
123 theme: String,
125 path: Option<PathBuf>,
127 source: HighlightSourceId,
129}
130
131#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
133struct HighlightSourceId {
134 ptr: usize,
136 len: usize,
138 head: u32,
140}
141
142impl HighlightKey {
143 pub fn new(input: HighlightKeyInput<'_>) -> Self {
145 let mut hasher = DefaultHasher::new();
146 input.text.hash(&mut hasher);
147
148 Self {
149 file: input.file,
150 side: input.side,
151 source_line: input.source_line,
152 text_hash: hasher.finish(),
153 syntax: input.syntax.unwrap_or("auto").to_owned(),
154 theme: input.theme.to_owned(),
155 }
156 }
157}
158
159impl HighlightSource {
160 pub fn new(text: impl Into<Arc<str>>, head: u32) -> Self {
162 Self {
163 text: text.into(),
164 head,
165 }
166 }
167
168 pub fn line_index(&self, source_line: u32) -> Option<usize> {
170 source_line.checked_sub(self.head).map(|line| line as usize)
171 }
172
173 pub fn line(&self, source_line: u32) -> Option<&str> {
175 self.line_index(source_line)
176 .and_then(|index| self.text.lines().nth(index))
177 }
178
179 fn id(&self) -> HighlightSourceId {
181 HighlightSourceId {
182 ptr: self.text.as_ptr() as usize,
183 len: self.text.len(),
184 head: self.head,
185 }
186 }
187}
188
189impl Hunk {
190 pub fn highlight_source(&self, side: DiffSide) -> HighlightSource {
192 let text = side_lines(self, side).collect::<Vec<_>>().join("\n");
193 HighlightSource::new(text, hunk_head(self, side))
194 }
195}
196
197impl FileDiff {
198 pub fn source_path(&self, side: DiffSide) -> Option<PathBuf> {
200 let (primary, fallback) = match side {
201 DiffSide::Old => (&self.header.old_path, &self.header.new_path),
202 DiffSide::New => (&self.header.new_path, &self.header.old_path),
203 };
204 primary.clone().or_else(|| fallback.clone())
205 }
206
207 pub fn highlight_source(&self, side: DiffSide) -> Option<HighlightSource> {
211 let mut lines: Vec<&str> = Vec::new();
212 let mut head = None;
213 let mut next_line = None;
214
215 for hunk in &self.hunks {
216 let hunk_head = hunk_head(hunk, side);
217 if next_line.is_some_and(|line| line != hunk_head) {
218 return None;
219 }
220 head.get_or_insert(hunk_head);
221 lines.extend(side_lines(hunk, side));
222 let len = hunk
223 .lines
224 .iter()
225 .map(|line| source_len(line, side))
226 .sum::<u32>();
227 next_line = Some(hunk_head + len);
228 }
229 head.map(|head| HighlightSource::new(lines.join("\n"), head))
230 }
231}
232
233fn side_lines(hunk: &Hunk, side: DiffSide) -> impl Iterator<Item = &str> {
238 hunk.lines
239 .iter()
240 .filter(move |line| source_len(line, side) != 0)
241 .map(|line| line.text.as_str())
242}
243
244fn hunk_head(hunk: &Hunk, side: DiffSide) -> u32 {
246 match side {
247 DiffSide::Old => hunk.header.old_line_no,
248 DiffSide::New => hunk.header.new_line_no,
249 }
250}
251
252fn source_len(line: &DiffLine, side: DiffSide) -> u32 {
254 match side {
255 DiffSide::Old => line.kind.old_len(),
256 DiffSide::New => line.kind.new_len(),
257 }
258}
259
260impl BuiltinHighlighter {
261 pub fn new(registry: syntax::Registry, default_theme: impl Into<String>) -> Self {
263 Self {
264 registry,
265 default_theme: default_theme.into(),
266 blob_caches: BTreeMap::new(),
267 }
268 }
269
270 pub fn ensure_grammar(&mut self, grammar: syntax::Grammar) {
272 if self.registry.grammar_by_name(&grammar.name).is_err() {
273 self.registry.add_grammar(grammar);
274 }
275 }
276
277 pub fn highlight(&mut self, request: HighlightRequest) -> HighlightResult {
279 self.highlight_group(vec![request]).remove(0)
280 }
281
282 pub fn highlight_requests<I>(&mut self, requests: I) -> Vec<HighlightResult>
284 where
285 I: IntoIterator<Item = HighlightRequest>,
286 {
287 let mut batches: BTreeMap<HighlightBatchKey, Vec<HighlightRequest>> = BTreeMap::new();
288 for request in requests {
289 batches
290 .entry(HighlightBatchKey::from(&request))
291 .or_default()
292 .push(request);
293 }
294
295 batches
296 .into_values()
297 .flat_map(|requests| self.highlight_group(requests))
298 .collect()
299 }
300
301 fn highlight_group(&mut self, requests: Vec<HighlightRequest>) -> Vec<HighlightResult> {
303 let Some(first) = requests.first() else {
304 return Vec::new();
305 };
306 let Ok(grammar) = self.registry.query(syntax::GrammarQuery {
307 syntax: (first.key.syntax != "auto").then_some(first.key.syntax.as_str()),
308 path: first.path.as_deref(),
309 head: first.source.text.lines().next(),
310 }) else {
311 return requests.into_iter().map(HighlightResult::plain).collect();
312 };
313 let theme_name = if first.key.theme == "auto" {
314 self.default_theme.as_str()
315 } else {
316 &first.key.theme
317 };
318 let Ok(theme) = self.registry.theme_by_name(theme_name) else {
319 return requests.into_iter().map(HighlightResult::plain).collect();
320 };
321 let range = requests.iter().filter_map(|request| {
322 request
323 .source
324 .line_index(request.key.source_line)
325 .map(|line| line..line.saturating_add(1))
326 });
327 let mut start = usize::MAX;
328 let mut end = 0;
329 for range in range {
330 start = start.min(range.start);
331 end = end.max(range.end);
332 }
333 if start >= end {
334 return requests.into_iter().map(HighlightResult::plain).collect();
335 }
336 let source = first.source.text.clone();
337 let cache_key = BlobCacheKey {
338 grammar: grammar.name.clone(),
339 text_ptr: source.as_ptr() as usize,
340 text_len: source.len(),
341 };
342 let cache = self
343 .blob_caches
344 .remove(&cache_key)
345 .map(|entry| entry.cache)
346 .unwrap_or_default();
347
348 let mut lines = BTreeMap::new();
349 let cache = {
350 let mut blob = syntax::BlobHighlighter::with_cache(grammar, source.as_ref(), cache);
351 blob.highlight_styled_range(theme, start..end, |line| {
352 lines.insert(line.line_index, line_from_spans(line.text, line.styles));
353 });
354 blob.into_cache()
355 };
356 self.blob_caches.insert(
357 cache_key,
358 BlobCacheEntry {
359 _source: source,
360 cache,
361 },
362 );
363
364 requests
365 .into_iter()
366 .map(|request| {
367 let line = request
368 .source
369 .line_index(request.key.source_line)
370 .and_then(|index| lines.remove(&index))
371 .unwrap_or_else(|| request.plain_line());
372 HighlightResult::new(request, line)
373 })
374 .collect()
375 }
376}
377
378impl DiffHighlighter for BuiltinHighlighter {
379 fn highlight_batch(&mut self, requests: Vec<HighlightRequest>) -> Vec<HighlightResult> {
380 self.highlight_requests(requests)
381 }
382}
383
384impl HighlightRequest {
385 fn plain_line(&self) -> Line {
387 self.source
388 .line(self.key.source_line)
389 .map(Line::new)
390 .unwrap_or_default()
391 }
392}
393
394impl HighlightResult {
395 pub fn new(request: HighlightRequest, line: Line) -> Self {
397 Self {
398 key: request.key,
399 hunk: request.hunk,
400 row: request.row,
401 line,
402 }
403 }
404
405 fn plain(request: HighlightRequest) -> Self {
407 let line = request.plain_line();
408 Self::new(request, line)
409 }
410}
411
412impl From<&HighlightRequest> for HighlightBatchKey {
413 fn from(request: &HighlightRequest) -> Self {
414 Self {
415 file: request.key.file,
416 side: request.key.side,
417 syntax: request.key.syntax.clone(),
418 theme: request.key.theme.clone(),
419 path: request.path.clone(),
420 source: request.source.id(),
421 }
422 }
423}
424
425fn line_from_spans(text: &str, spans: &[syntax::StyleSpan]) -> Line {
427 if text.is_empty() || spans.is_empty() {
428 return Line::new(text);
429 }
430 let mut line = Line::blank();
431 let mut cursor = 0;
432
433 for span in spans {
434 if cursor < span.start {
435 line.push(Label::new(&text[cursor..span.start]));
436 }
437 if span.start < span.end {
438 line.push(Label::new(&text[span.start..span.end]).style(span.style.tui_style()));
439 }
440 cursor = span.end;
441 }
442 if cursor < text.len() {
443 line.push(Label::new(&text[cursor..]));
444 }
445 line
446}
447
448#[derive(Clone, Copy, Debug)]
450pub struct HighlightKeyInput<'a> {
451 pub file: FileId,
453 pub side: DiffSide,
455 pub source_line: u32,
457 pub text: &'a str,
459 pub syntax: Option<&'a str>,
461 pub theme: &'a str,
463}
464
465trait SyntaxStyleExt {
467 fn tui_style(self) -> Style;
469}
470
471impl SyntaxStyleExt for syntax::Style {
472 fn tui_style(self) -> Style {
473 let mut out = Style::default();
474 if let Some(color) = self.foreground {
475 out = out.fg(Color::RGB(color.r, color.g, color.b));
476 }
477 if self.font_style.contains(syntax::FontStyle::BOLD) {
478 out = out.bold();
479 }
480 if self.font_style.contains(syntax::FontStyle::ITALIC) {
481 out = out.italic();
482 }
483 if self.font_style.contains(syntax::FontStyle::UNDERLINE) {
484 out = out.underline();
485 }
486 if self.font_style.contains(syntax::FontStyle::STRIKETHROUGH) {
487 out = out.strikethrough();
488 }
489 out
490 }
491}
492
493#[cfg(test)]
494mod tests {
495 use super::*;
496 use crate::Decode;
497 use std::str::FromStr;
498
499 #[test]
500 fn source_lines_before_head_are_absent() {
501 let source = HighlightSource::new("two\nthree\n", 2);
502
503 assert_eq!(source.line_index(1), None);
504 assert_eq!(source.line(1), None);
505 assert_eq!(source.line_index(2), Some(0));
506 assert_eq!(source.line(2), Some("two"));
507 }
508
509 #[test]
510 fn file_highlight_source_spans_the_new_side() {
511 let document = crate::DiffDocument::decode_str(
512 "\
513diff --git a/a.css b/a.css
514index 1111111..2222222 100644
515--- a/a.css
516+++ b/a.css
517@@ -1,3 +1,3 @@
518 .x {
519-background: url(old.svg);
520+background: url(new.svg);
521 }
522",
523 )
524 .unwrap();
525 let source = document.files[0].highlight_source(DiffSide::New).unwrap();
526
527 assert_eq!(source.head, 1);
528 assert_eq!(source.line(1), Some(".x {"));
529 assert_eq!(source.line(2), Some("background: url(new.svg);"));
530 assert_eq!(source.line(3), Some("}"));
531 }
532
533 #[test]
534 fn highlight_source_keeps_a_leading_blank_line() {
535 let document = crate::DiffDocument::decode_str(concat!(
540 "diff --git a/a.rs b/a.rs\n",
541 "index 1111111..2222222 100644\n",
542 "--- a/a.rs\n",
543 "+++ b/a.rs\n",
544 "@@ -2,3 +2,3 @@\n",
545 " \n",
546 "-old\n",
547 "+new\n",
548 " tail\n",
549 ))
550 .unwrap();
551 let hunk = &document.files[0].hunks[0];
552
553 let source = hunk.highlight_source(DiffSide::New);
554 assert_eq!(source.head, 2);
555 assert_eq!(source.line(2), Some(""));
556 assert_eq!(source.line(3), Some("new"));
557 assert_eq!(source.line(4), Some("tail"));
558
559 let file = document.files[0].highlight_source(DiffSide::New).unwrap();
560 assert_eq!(file.line(2), Some(""));
561 assert_eq!(file.line(3), Some("new"));
562 }
563
564 #[test]
565 fn css_custom_properties_use_variable_theme_style() {
566 let grammar = syntax::Grammar::from_str(syntax::syntaxes::CSS).unwrap();
567 let theme =
568 syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap();
569 let line = " --color-background-light: #dad8d8;";
570 let mut state = syntax::LineState::default();
571 let mut tokenizer = syntax::LineTokenizer::new(&grammar);
572 let _ = tokenizer.tokenize_line(&mut state, ":root {");
573 let spans = tokenizer.tokenize_line(&mut state, line);
574 let styles = theme.style_spans(&grammar, line, &spans);
575 let custom_property = line.find("--color-background-light").unwrap();
576 let style = styles
577 .iter()
578 .find(|style| style.start <= custom_property && style.end > custom_property)
579 .unwrap();
580
581 assert!(scopes_for_byte(&grammar, &spans, custom_property).contains(&"variable.css"));
582 assert_eq!(
583 style.style.foreground,
584 Some(syntax::Rgb {
585 r: 137,
586 g: 180,
587 b: 250
588 })
589 );
590 }
591
592 #[test]
593 fn css_var_references_use_variable_theme_style() {
594 let grammar = syntax::Grammar::from_str(syntax::syntaxes::CSS).unwrap();
595 let theme =
596 syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap();
597 let line = " color: var(--color-dimmer);";
598 let mut state = syntax::LineState::default();
599 let mut tokenizer = syntax::LineTokenizer::new(&grammar);
600 let _ = tokenizer.tokenize_line(&mut state, ".note-meta {");
601 let spans = tokenizer.tokenize_line(&mut state, line);
602 let styles = theme.style_spans(&grammar, line, &spans);
603 let variable = line.find("--color-dimmer").unwrap();
604 let style = styles
605 .iter()
606 .find(|style| style.start <= variable && style.end > variable)
607 .unwrap();
608
609 assert!(scopes_for_byte(&grammar, &spans, variable).contains(&"variable.argument.css"));
610 assert_eq!(
611 style.style.foreground,
612 Some(syntax::Rgb {
613 r: 235,
614 g: 160,
615 b: 172
616 })
617 );
618 }
619
620 fn scopes_for_byte<'a>(
621 grammar: &'a syntax::Grammar,
622 spans: &'a [syntax::ScopeSpan],
623 byte: usize,
624 ) -> Vec<&'a str> {
625 spans
626 .iter()
627 .filter(|span| span.start <= byte && span.end > byte)
628 .filter_map(|span| grammar.scopes.get(span.scope.index()))
629 .map(String::as_str)
630 .collect()
631 }
632}