BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / highlighter / highlighter.rs

highlighter.rs

highlighter.rs 69.7 KiB Download Raw
1#[cfg(test)]
2use crate::highlighter::HighlightTheme;
3use crate::highlighter::LanguageRegistry;
4
5use anyhow::{Context, Result, anyhow};
6use gpui::{HighlightStyle, SharedString};
7use gpui_base::input::RopeExt as _;
8use ropey::{ChunkCursor, Rope};
9use std::sync::Arc;
10use std::time::{Duration, Instant};
11use std::{
12 collections::{BTreeSet, HashMap},
13 ops::{ControlFlow, Range},
14};
15use sum_tree::Bias;
16use tree_sitter::{
17 InputEdit, ParseOptions, Parser, Point, Query, QueryCursor, StreamingIterator, Tree,
18};
19
20const MAX_INJECTION_RANGES: usize = 4096;
21const MAX_INJECTION_BYTES: usize = 512 * 1024;
22const MAX_INJECTION_LANGUAGE_BYTES: usize = 64;
23/// Parse attempts, not resulting layers: a failed parse still spends budget.
24/// Matches past it keep host highlighting but get no injected tokens.
25const MAX_NON_COMBINED_INJECTION_PARSES: usize = 512;
26const INJECTION_PARSE_TIMEOUT: Duration = Duration::from_millis(20);
27
28/// A syntax highlighter that supports incremental parsing, multiline text,
29/// and caching of highlight results.
30#[allow(unused)]
31pub struct SyntaxHighlighter {
32 language: SharedString,
33 query: Option<Query>,
34 /// The full injections query. This is used to build injection layers during parsing.
35 injections_query: Option<Arc<Query>>,
36
37 locals_pattern_index: usize,
38 highlights_pattern_index: usize,
39 // highlight_indices: Vec<Option<Highlight>>,
40 non_local_variable_patterns: Vec<bool>,
41 injection_content_capture_index: Option<u32>,
42 injection_language_capture_index: Option<u32>,
43 local_scope_capture_index: Option<u32>,
44 local_def_capture_index: Option<u32>,
45 local_def_value_capture_index: Option<u32>,
46 local_ref_capture_index: Option<u32>,
47
48 /// The last parsed source text.
49 text: Rope,
50 parser: Parser,
51 /// The last parsed tree.
52 tree: Option<Tree>,
53
54 /// Parsed injection trees.
55 /// These are built once in update() and queried multiple times in match_styles().
56 injection_layers: Vec<InjectionLayer>,
57}
58
59/// A parsed injection layer.
60/// Stores the parsed tree and the ranges it covers.
61pub(crate) struct InjectionLayer {
62 pub(crate) language_name: SharedString,
63 highlight_query: Arc<Query>,
64 pub(crate) ranges: Vec<tree_sitter::Range>,
65 pub(crate) byte_range: Range<usize>,
66 pub(crate) tree: Tree,
67 /// Whether this layer parses the ranges of every match combined.
68 pub(crate) combined: bool,
69}
70
71/// Data needed to compute injection layers on a background thread.
72pub(crate) struct InjectionParseData {
73 pub(crate) query: Arc<Query>,
74 pub(crate) content_capture_index: Option<u32>,
75 pub(crate) language_capture_index: Option<u32>,
76 /// Old injection layers, edited to match the text being parsed, whose
77 /// trees are reused as the old trees of the new layers.
78 pub(crate) old_layers: Vec<ReusableInjectionLayer>,
79}
80
81pub(crate) struct ReusableInjectionLayer {
82 pub(crate) language_name: SharedString,
83 highlight_query: Arc<Query>,
84 pub(crate) ranges: Vec<tree_sitter::Range>,
85 pub(crate) tree: Tree,
86 pub(crate) combined: bool,
87}
88
89impl From<InjectionLayer> for ReusableInjectionLayer {
90 fn from(layer: InjectionLayer) -> Self {
91 Self {
92 language_name: layer.language_name,
93 highlight_query: layer.highlight_query,
94 ranges: layer.ranges,
95 tree: layer.tree,
96 combined: layer.combined,
97 }
98 }
99}
100
101struct TextProvider<'a>(&'a Rope);
102struct ByteChunks<'a> {
103 cursor: ChunkCursor<'a>,
104 node_start: usize,
105 node_end: usize,
106 at_first: bool,
107}
108impl<'a> tree_sitter::TextProvider<&'a [u8]> for TextProvider<'a> {
109 type I = ByteChunks<'a>;
110
111 fn text(&mut self, node: tree_sitter::Node) -> Self::I {
112 let range = node.byte_range();
113 let cursor = self.0.chunk_cursor_at(range.start);
114
115 ByteChunks {
116 cursor,
117 node_start: range.start,
118 node_end: range.end,
119 at_first: true,
120 }
121 }
122}
123
124impl<'a> Iterator for ByteChunks<'a> {
125 type Item = &'a [u8];
126
127 fn next(&mut self) -> Option<Self::Item> {
128 if !self.at_first {
129 if !self.cursor.next() {
130 return None;
131 }
132 }
133 self.at_first = false;
134
135 let chunk_byte_start = self.cursor.byte_offset();
136 if chunk_byte_start >= self.node_end {
137 return None;
138 }
139
140 let chunk = self.cursor.chunk().as_bytes();
141
142 // Slice the chunk to only include bytes within the node's range.
143 let start_in_chunk = self.node_start.saturating_sub(chunk_byte_start);
144 let end_in_chunk = (self.node_end - chunk_byte_start).min(chunk.len());
145
146 if start_in_chunk >= end_in_chunk {
147 return None;
148 }
149
150 Some(&chunk[start_in_chunk..end_in_chunk])
151 }
152}
153
154/// Answer a tree-sitter read request at byte `offset`.
155///
156/// Tree-sitter reads bytes, not chars: a stale tree or stale included ranges
157/// can ask for an offset inside a multi-byte character. Slicing `&str` there
158/// panics, and a panic inside tree-sitter's `extern "C"` read callback aborts
159/// the process, so the chunk is sliced as bytes.
160pub(crate) fn parse_input_bytes(text: &Rope, offset: usize) -> &[u8] {
161 if offset >= text.len() {
162 return &[];
163 }
164
165 let (chunk, chunk_byte_ix) = text.chunk(offset);
166 &chunk.as_bytes()[offset - chunk_byte_ix..]
167}
168
169fn injection_range_len(range: &tree_sitter::Range) -> usize {
170 range.end_byte.saturating_sub(range.start_byte)
171}
172
173fn injection_ranges_byte_count(ranges: &[tree_sitter::Range]) -> usize {
174 ranges.iter().map(injection_range_len).sum()
175}
176
177fn bounding_byte_range(ranges: &[tree_sitter::Range]) -> Option<Range<usize>> {
178 let start = ranges.iter().map(|r| r.start_byte).min()?;
179 let end = ranges.iter().map(|r| r.end_byte).max()?;
180 Some(start..end)
181}
182
183fn injection_ranges_within_limits(ranges: &[tree_sitter::Range]) -> bool {
184 ranges.len() <= MAX_INJECTION_RANGES
185 && injection_ranges_byte_count(ranges) <= MAX_INJECTION_BYTES
186}
187
188/// Read a captured injection language without ever allocating an unbounded
189/// amount of source text. Language identifiers in fenced code blocks are tiny;
190/// longer captures cannot name a registered language and are ignored.
191///
192/// The range comes from a tree that can be stale relative to `text`; one that
193/// no longer lands on char boundaries cannot name a language either.
194fn captured_injection_language(text: &Rope, range: Range<usize>) -> Option<SharedString> {
195 if range.end > text.len()
196 || range.start >= range.end
197 || range.end.saturating_sub(range.start) > MAX_INJECTION_LANGUAGE_BYTES
198 || !text.is_char_boundary(range.start)
199 || !text.is_char_boundary(range.end)
200 {
201 return None;
202 }
203
204 let language = text.slice(range).to_string();
205 let language = language.trim();
206 (!language.is_empty()).then(|| SharedString::from(language.to_string()))
207}
208
209/// Combined markdown inline injections are parsed as one tree with
210/// `set_included_ranges`. If we include only the inline nodes that contain
211/// trigger bytes, the parser sees those ranges as adjacent and can merge a
212/// closing backtick from one list item with an opening backtick from the next.
213/// Re-inserting the separator bytes between retained inline ranges preserves
214/// the original boundaries.
215///
216/// The separator bytes count against the same `MAX_INJECTION_RANGES` /
217/// `MAX_INJECTION_BYTES` budget as the content ranges, so on a very large
218/// document the tail ranges may be dropped here even though `push_limited`
219/// already admitted them.
220fn normalize_combined_injection_ranges(
221 language_name: &SharedString,
222 ranges: Vec<tree_sitter::Range>,
223) -> Vec<tree_sitter::Range> {
224 if language_name.as_ref() != "markdown_inline" || ranges.len() <= 1 {
225 return ranges;
226 }
227
228 let mut normalized = Vec::with_capacity(ranges.len().min(MAX_INJECTION_RANGES));
229 let mut byte_count = 0usize;
230 let mut previous_range: Option<tree_sitter::Range> = None;
231
232 for range in ranges {
233 let mut pending_ranges = Vec::with_capacity(2);
234 if let Some(previous) = previous_range {
235 if previous.end_byte < range.start_byte {
236 pending_ranges.push(tree_sitter::Range {
237 start_byte: previous.end_byte,
238 end_byte: range.start_byte,
239 start_point: previous.end_point,
240 end_point: range.start_point,
241 });
242 }
243 }
244 pending_ranges.push(range);
245
246 let pending_len = pending_ranges
247 .iter()
248 .map(injection_range_len)
249 .sum::<usize>();
250 if normalized.len().saturating_add(pending_ranges.len()) > MAX_INJECTION_RANGES
251 || byte_count.saturating_add(pending_len) > MAX_INJECTION_BYTES
252 {
253 break;
254 }
255
256 byte_count += pending_len;
257 normalized.extend(pending_ranges);
258 previous_range = Some(range);
259 }
260
261 normalized
262}
263
264fn should_include_injection_range(
265 language_name: &SharedString,
266 range: &tree_sitter::Range,
267 text: &Rope,
268) -> bool {
269 if language_name.as_ref() != "markdown_inline" {
270 return true;
271 }
272
273 markdown_inline_range_has_trigger(text, range.start_byte..range.end_byte)
274}
275
276/// Returns whether an inline range contains any byte that could start a
277/// Markdown inline construct, so plain prose ranges skip the injected parse.
278///
279/// The byte set must stay a superset of the trigger characters for every node
280/// captured by `languages/markdown_inline/highlights.scm` (emphasis, code
281/// spans, links, images, autolinks). If that query gains a construct with a new
282/// trigger character (e.g. GFM bare autolinks), add it here or the construct
283/// will silently lose highlighting.
284///
285/// The range comes from a tree that can be stale relative to `text`, so it is
286/// clipped to the text's char boundaries before slicing.
287fn markdown_inline_range_has_trigger(text: &Rope, range: Range<usize>) -> bool {
288 let start = text.clip_offset(range.start, Bias::Left);
289 let end = text.clip_offset(range.end, Bias::Right).max(start);
290 text.slice(start..end).bytes().any(|byte| {
291 matches!(
292 byte,
293 b'*' | b'_' | b'`' | b'[' | b']' | b'(' | b')' | b'<' | b'>' | b'!' | b'~' | b'$'
294 )
295 })
296}
297
298#[derive(Debug, Default, Clone)]
299struct HighlightSummary {
300 count: usize,
301 start: usize,
302 end: usize,
303 min_start: usize,
304 max_end: usize,
305}
306
307/// The highlight item, the range is offset of the token in the tree.
308#[derive(Debug, Default, Clone)]
309struct HighlightItem {
310 /// The byte range of the highlight in the text.
311 range: Range<usize>,
312 /// The highlight name, like `function`, `string`, `comment`, etc.
313 name: SharedString,
314}
315
316impl HighlightItem {
317 pub fn new(range: Range<usize>, name: impl Into<SharedString>) -> Self {
318 Self {
319 range,
320 name: name.into(),
321 }
322 }
323}
324
325impl sum_tree::Item for HighlightItem {
326 type Summary = HighlightSummary;
327 fn summary(&self, _cx: &()) -> Self::Summary {
328 HighlightSummary {
329 count: 1,
330 start: self.range.start,
331 end: self.range.end,
332 min_start: self.range.start,
333 max_end: self.range.end,
334 }
335 }
336}
337
338impl sum_tree::Summary for HighlightSummary {
339 type Context<'a> = &'a ();
340 fn zero(_: Self::Context<'_>) -> Self {
341 HighlightSummary {
342 count: 0,
343 start: usize::MIN,
344 end: usize::MAX,
345 min_start: usize::MAX,
346 max_end: usize::MIN,
347 }
348 }
349
350 fn add_summary(&mut self, other: &Self, _: Self::Context<'_>) {
351 self.min_start = self.min_start.min(other.min_start);
352 self.max_end = self.max_end.max(other.max_end);
353 self.start = other.start;
354 self.end = other.end;
355 self.count += other.count;
356 }
357}
358
359impl<'a> sum_tree::Dimension<'a, HighlightSummary> for usize {
360 fn zero(_: &()) -> Self {
361 0
362 }
363
364 fn add_summary(&mut self, _: &'a HighlightSummary, _: &()) {}
365}
366
367impl<'a> sum_tree::Dimension<'a, HighlightSummary> for Range<usize> {
368 fn zero(_: &()) -> Self {
369 Default::default()
370 }
371
372 fn add_summary(&mut self, summary: &'a HighlightSummary, _: &()) {
373 self.start = summary.start;
374 self.end = summary.end;
375 }
376}
377
378impl SyntaxHighlighter {
379 /// Create a new SyntaxHighlighter for the given language.
380 pub fn new(lang: &str) -> Self {
381 match Self::build_for_language(&lang) {
382 Ok(result) => result,
383 Err(err) => {
384 tracing::warn!(
385 "SyntaxHighlighter init failed, fallback to use `text`, {}",
386 err
387 );
388 Self::build_for_language("text").unwrap()
389 }
390 }
391 }
392
393 /// Build an inert highlighter that never parses and creates no styles,
394 /// for languages without a grammar.
395 fn build_inert(language: SharedString) -> Self {
396 Self {
397 language,
398 query: None,
399 injections_query: None,
400 locals_pattern_index: 0,
401 highlights_pattern_index: 0,
402 non_local_variable_patterns: Vec::new(),
403 injection_content_capture_index: None,
404 injection_language_capture_index: None,
405 local_scope_capture_index: None,
406 local_def_capture_index: None,
407 local_def_value_capture_index: None,
408 local_ref_capture_index: None,
409 text: Rope::new(),
410 parser: Parser::new(),
411 tree: None,
412 injection_layers: Vec::new(),
413 }
414 }
415
416 /// Build the highlighter for the given language.
417 ///
418 /// https://github.com/tree-sitter/tree-sitter/blob/v0.26.8/crates/highlight/src/highlight.rs#L339
419 fn build_for_language(lang: &str) -> Result<Self> {
420 let Some(config) = LanguageRegistry::singleton().language(&lang) else {
421 return Err(anyhow!(
422 "language {:?} is not registered in `LanguageRegistry`",
423 lang
424 ));
425 };
426
427 // Languages without a parser (neither a statically linked grammar nor a
428 // registered parser factory) default to a highlighter that never parses
429 // and creates no styles.
430 if !LanguageRegistry::singleton().has_parser(lang) {
431 return Ok(Self::build_inert(config.name.clone()));
432 }
433
434 let (mut parser, grammar) = LanguageRegistry::singleton().parser(lang)?;
435 parser
436 .set_language(&grammar)
437 .context("parse set_language")?;
438
439 // Concatenate the query strings, keeping track of the start offset of each section.
440 let mut query_source = String::new();
441 query_source.push_str(&config.injections);
442 let locals_query_offset = query_source.len();
443 query_source.push_str(&config.locals);
444 let highlights_query_offset = query_source.len();
445 query_source.push_str(&config.highlights);
446
447 // Construct a single query by concatenating the three query strings, but record the
448 // range of pattern indices that belong to each individual string.
449 let mut query = Query::new(&grammar, &query_source).context("new query")?;
450
451 let mut locals_pattern_index = 0;
452 let mut highlights_pattern_index = 0;
453 for i in 0..(query.pattern_count()) {
454 let pattern_offset = query.start_byte_for_pattern(i);
455 if pattern_offset < highlights_query_offset {
456 if pattern_offset < highlights_query_offset {
457 highlights_pattern_index += 1;
458 }
459 if pattern_offset < locals_query_offset {
460 locals_pattern_index += 1;
461 }
462 }
463 }
464
465 let injections_query = if !config.injections.is_empty() {
466 Query::new(&grammar, &config.injections).ok().map(Arc::new)
467 } else {
468 None
469 };
470
471 // Injection layers are computed separately during parsing, so do not
472 // emit injection captures from the main highlight query.
473 for pattern_index in 0..locals_pattern_index {
474 query.disable_pattern(pattern_index);
475 }
476
477 // Find all of the highlighting patterns that are disabled for nodes that
478 // have been identified as local variables.
479 let non_local_variable_patterns = (0..query.pattern_count())
480 .map(|i| {
481 query
482 .property_predicates(i)
483 .iter()
484 .any(|(prop, positive)| !*positive && prop.key.as_ref() == "local")
485 })
486 .collect();
487
488 // Store the numeric ids for all of the special captures.
489 let injection_content_capture_index = injections_query.as_ref().and_then(|q| {
490 q.capture_names()
491 .iter()
492 .position(|name| *name == "injection.content")
493 .map(|i| i as u32)
494 });
495 let injection_language_capture_index = injections_query.as_ref().and_then(|q| {
496 q.capture_names()
497 .iter()
498 .position(|name| *name == "injection.language")
499 .map(|i| i as u32)
500 });
501 let mut local_def_capture_index = None;
502 let mut local_def_value_capture_index = None;
503 let mut local_ref_capture_index = None;
504 let mut local_scope_capture_index = None;
505 for (i, name) in query.capture_names().iter().enumerate() {
506 let i = Some(i as u32);
507 match *name {
508 "local.definition" => local_def_capture_index = i,
509 "local.definition-value" => local_def_value_capture_index = i,
510 "local.reference" => local_ref_capture_index = i,
511 "local.scope" => local_scope_capture_index = i,
512 _ => {}
513 }
514 }
515
516 // let highlight_indices = vec![None; query.capture_names().len()];
517
518 Ok(Self {
519 language: config.name.clone(),
520 query: Some(query),
521 injections_query,
522
523 locals_pattern_index,
524 highlights_pattern_index,
525 non_local_variable_patterns,
526 injection_content_capture_index,
527 injection_language_capture_index,
528 local_scope_capture_index,
529 local_def_capture_index,
530 local_def_value_capture_index,
531 local_ref_capture_index,
532 text: Rope::new(),
533 parser,
534 tree: None,
535 injection_layers: Vec::new(),
536 })
537 }
538
539 pub fn is_empty(&self) -> bool {
540 self.text.len() == 0
541 }
542
543 /// Get the parsed tree (if available)
544 pub fn tree(&self) -> Option<&Tree> {
545 self.tree.as_ref()
546 }
547
548 /// Apply only the structural `edit` to the existing tree and update the stored text,
549 /// without re-parsing.
550 pub fn edit_tree(&mut self, edit: Option<InputEdit>, text: &Rope) {
551 if let (Some(edit), Some(tree)) = (edit, self.tree.as_mut()) {
552 tree.edit(&edit);
553 }
554 self.edit_injection_layers(edit.as_ref());
555 self.text = text.clone();
556 }
557
558 /// Keep the injection layers in step with `edit`, the way `Tree::edit`
559 /// keeps a tree, so the next injection pass reuses their trees instead of
560 /// parsing every layer after the edit from scratch. Without an edit the
561 /// layers no longer describe the text and are dropped.
562 fn edit_injection_layers(&mut self, edit: Option<&InputEdit>) {
563 let Some(edit) = edit else {
564 self.injection_layers.clear();
565 return;
566 };
567
568 for layer in &mut self.injection_layers {
569 layer.tree.edit(edit);
570 for range in &mut layer.ranges {
571 edit.edit_range(range);
572 }
573 if let Some(byte_range) = bounding_byte_range(&layer.ranges) {
574 layer.byte_range = byte_range;
575 }
576 }
577 }
578
579 /// Returns the language name for this highlighter.
580 pub fn language(&self) -> &SharedString {
581 &self.language
582 }
583
584 /// Returns a reference to the current text.
585 pub fn text(&self) -> &Rope {
586 &self.text
587 }
588
589 /// Highlight the given text, returning a map from byte ranges to highlight captures.
590 ///
591 /// Uses incremental parsing by `edit` to efficiently update the highlighter's state.
592 /// When `timeout` is `Some`, aborts if parsing exceeds the given duration
593 /// and returns `false`. On timeout the old tree is preserved so highlighting
594 /// still works with stale data, but `self.text` is updated so that the
595 /// caller can send the current text to a background parse.
596 /// When `timeout` is `None`, parsing runs to completion and always returns `true`.
597 pub fn update(
598 &mut self,
599 edit: Option<InputEdit>,
600 text: &Rope,
601 timeout: Option<Duration>,
602 ) -> bool {
603 self.update_edits(edit.as_slice(), text, timeout)
604 }
605
606 /// Like [`Self::update`] for several edits, in the order they were applied
607 /// to reach `text`: the tree takes every edit, then reparses once. No
608 /// edits means the change is unknown, as `None` does for `update`.
609 pub(crate) fn update_edits(
610 &mut self,
611 edits: &[InputEdit],
612 text: &Rope,
613 timeout: Option<Duration>,
614 ) -> bool {
615 if self.text.eq(text) {
616 return true;
617 }
618
619 // If there's no grammar for the language, just update the text.
620 if self.parser.language().is_none() {
621 self.text = text.clone();
622 return true;
623 }
624
625 let full_edit;
626 let edits = if edits.is_empty() {
627 self.edit_injection_layers(None);
628 full_edit = [InputEdit {
629 start_byte: 0,
630 old_end_byte: 0,
631 new_end_byte: text.len(),
632 start_position: Point::new(0, 0),
633 old_end_position: Point::new(0, 0),
634 new_end_position: Point::new(0, 0),
635 }];
636 &full_edit[..]
637 } else {
638 for edit in edits {
639 self.edit_injection_layers(Some(edit));
640 }
641 edits
642 };
643
644 let mut old_tree = self
645 .tree
646 .take()
647 .unwrap_or(self.parser.parse("", None).unwrap());
648 for edit in edits {
649 old_tree.edit(edit);
650 }
651
652 let mut timed_out = false;
653 let start = Instant::now();
654 let mut progress = |_: &tree_sitter::ParseState| -> ControlFlow<()> {
655 let Some(budget) = timeout else {
656 return ControlFlow::Continue(());
657 };
658
659 if start.elapsed() > budget {
660 timed_out = true;
661 return ControlFlow::Break(()); // Cancel execution
662 }
663
664 ControlFlow::Continue(())
665 };
666
667 let options = ParseOptions::new().progress_callback(&mut progress);
668 let new_tree = self.parser.parse_with_options(
669 &mut move |offset, _| parse_input_bytes(text, offset),
670 Some(&old_tree),
671 Some(options),
672 );
673
674 if timed_out || new_tree.is_none() {
675 // Restore the old tree so highlighting continues with stale data.
676 self.tree = Some(old_tree);
677 self.text = text.clone();
678 return false;
679 }
680
681 let new_tree = new_tree.unwrap();
682 self.tree = Some(new_tree.clone());
683 self.text = text.clone();
684 self.parse_injection_layers(&new_tree);
685 true
686 }
687
688 /// Returns the data needed to compute injection layers on a background thread.
689 /// Returns `None` if this language has no injections.
690 pub(crate) fn injection_parse_data(&self) -> Option<InjectionParseData> {
691 let query = self.injections_query.clone()?;
692 Some(InjectionParseData {
693 query,
694 content_capture_index: self.injection_content_capture_index,
695 language_capture_index: self.injection_language_capture_index,
696 old_layers: self
697 .injection_layers
698 .iter()
699 .map(|layer| ReusableInjectionLayer {
700 language_name: layer.language_name.clone(),
701 highlight_query: layer.highlight_query.clone(),
702 ranges: layer.ranges.clone(),
703 tree: layer.tree.clone(),
704 combined: layer.combined,
705 })
706 .collect(),
707 })
708 }
709
710 /// Compute injection layers from a freshly-parsed main tree.
711 /// This is pure computation with no side effects and is safe to run on a
712 /// background thread.
713 pub(crate) fn compute_injection_layers(
714 data: InjectionParseData,
715 tree: &Tree,
716 text: &Rope,
717 ) -> Vec<InjectionLayer> {
718 struct CombinedRanges {
719 ranges: Vec<tree_sitter::Range>,
720 byte_count: usize,
721 }
722
723 impl CombinedRanges {
724 /// Ranges are already filtered by `should_include_injection_range`
725 /// before being pushed here; this only enforces the count/byte caps.
726 fn push_limited(&mut self, ranges: Vec<tree_sitter::Range>) {
727 for range in ranges {
728 if self.ranges.len() >= MAX_INJECTION_RANGES {
729 break;
730 }
731
732 let range_len = injection_range_len(&range);
733 if self.byte_count.saturating_add(range_len) > MAX_INJECTION_BYTES {
734 break;
735 }
736
737 self.byte_count += range_len;
738 self.ranges.push(range);
739 }
740 }
741 }
742
743 fn sort_ranges(ranges: &mut [tree_sitter::Range]) {
744 ranges.sort_unstable_by(|a, b| {
745 a.start_byte
746 .cmp(&b.start_byte)
747 .then_with(|| a.end_byte.cmp(&b.end_byte))
748 });
749 }
750
751 fn ranges_cache_key(ranges: &[tree_sitter::Range]) -> Vec<(usize, usize)> {
752 ranges.iter().map(|r| (r.start_byte, r.end_byte)).collect()
753 }
754
755 fn resolve_language(
756 language_name: &str,
757 query_cache: &mut HashMap<SharedString, Arc<Query>>,
758 ) -> Option<(SharedString, Arc<Query>)> {
759 let config = LanguageRegistry::singleton().language(language_name)?;
760 if let Some(query) = query_cache.get(&config.name) {
761 return Some((config.name, query.clone()));
762 }
763
764 let grammar = LanguageRegistry::singleton().grammar(language_name).ok()?;
765 let query = match Query::new(&grammar, &config.highlights) {
766 Ok(query) => Arc::new(query),
767 Err(error) => {
768 tracing::error!(
769 "failed to build injection query for {:?}: {:?}",
770 config.name,
771 error
772 );
773 return None;
774 }
775 };
776 query_cache.insert(config.name.clone(), query.clone());
777 Some((config.name, query))
778 }
779
780 let root_node = tree.root_node();
781 let mut cursor = QueryCursor::new();
782 let mut matches = cursor.matches(&data.query, root_node, TextProvider(text));
783
784 let mut combined_ranges: HashMap<SharedString, CombinedRanges> = HashMap::new();
785 // Old layers were edited along with the text, so a non-combined layer
786 // whose content did not change keeps exactly the same ranges.
787 let old_layer_trees: HashMap<_, _> = data
788 .old_layers
789 .iter()
790 .filter(|layer| !layer.combined)
791 .map(|layer| {
792 (
793 (layer.language_name.clone(), ranges_cache_key(&layer.ranges)),
794 &layer.tree,
795 )
796 })
797 .collect();
798 // A combined layer spans many matches, so an edit anywhere in them
799 // changes its ranges. Tree-sitter accepts an edited old tree whose
800 // included ranges differ and reparses only where they changed.
801 let old_combined_trees: HashMap<SharedString, &Tree> = data
802 .old_layers
803 .iter()
804 .filter(|layer| layer.combined)
805 .map(|layer| (layer.language_name.clone(), &layer.tree))
806 .collect();
807 // Query objects are relatively expensive. Reuse one Arc per language
808 // from the previous parse and compile only languages present in this
809 // document, rather than eagerly retaining every registered grammar.
810 let mut highlight_queries: HashMap<SharedString, Arc<Query>> = data
811 .old_layers
812 .iter()
813 .map(|layer| (layer.language_name.clone(), layer.highlight_query.clone()))
814 .collect();
815 // Cache raw names as well as canonical queries. Otherwise every fence with the
816 // same info string would lock the registry and clone its language configuration.
817 let mut resolved_languages: HashMap<SharedString, Option<(SharedString, Arc<Query>)>> =
818 HashMap::new();
819 let mut new_layers = Vec::new();
820 let mut non_combined_parses = 0usize;
821 while let Some(query_match) = matches.next() {
822 let mut language_name: Option<SharedString> = None;
823 let mut combined = false;
824 for prop in data.query.property_settings(query_match.pattern_index) {
825 match prop.key.as_ref() {
826 "injection.language" => {
827 language_name = prop
828 .value
829 .as_ref()
830 .map(|v| SharedString::from(v.to_string()));
831 }
832 "injection.combined" => combined = true,
833 _ => {}
834 }
835 }
836
837 // Skip rather than break, so later combined ranges are still collected.
838 if !combined && non_combined_parses >= MAX_NON_COMBINED_INJECTION_PARSES {
839 continue;
840 }
841
842 if language_name.is_none() {
843 language_name = query_match
844 .captures
845 .iter()
846 .find(|cap| Some(cap.index) == data.language_capture_index)
847 .and_then(|capture| {
848 captured_injection_language(text, capture.node.byte_range())
849 });
850 }
851
852 let Some(raw_language_name) = language_name else {
853 continue;
854 };
855 let resolved_language =
856 if let Some(resolved) = resolved_languages.get(&raw_language_name) {
857 resolved.clone()
858 } else {
859 let resolved = resolve_language(&raw_language_name, &mut highlight_queries);
860 resolved_languages.insert(raw_language_name, resolved.clone());
861 resolved
862 };
863 let Some((language_name, highlight_query)) = resolved_language else {
864 continue;
865 };
866
867 let mut ranges = query_match
868 .captures
869 .iter()
870 .filter(|cap| Some(cap.index) == data.content_capture_index)
871 .map(|capture| capture.node.range())
872 .collect::<Vec<_>>();
873
874 if ranges.is_empty() {
875 continue;
876 }
877 ranges.retain(|range| should_include_injection_range(&language_name, range, text));
878 if ranges.is_empty() {
879 continue;
880 }
881 sort_ranges(&mut ranges);
882
883 if combined {
884 combined_ranges
885 .entry(language_name.clone())
886 .or_insert_with(|| CombinedRanges {
887 ranges: Vec::new(),
888 byte_count: 0,
889 })
890 .push_limited(ranges);
891 } else {
892 if !injection_ranges_within_limits(&ranges) {
893 continue;
894 }
895
896 non_combined_parses += 1;
897 let old_tree = old_layer_trees
898 .get(&(language_name.clone(), ranges_cache_key(&ranges)))
899 .copied();
900 if let Some(layer) = Self::parse_injection_layer(
901 &language_name,
902 highlight_query,
903 ranges,
904 old_tree,
905 false,
906 text,
907 ) {
908 new_layers.push(layer);
909 }
910 }
911 }
912
913 for (language_name, combined) in combined_ranges {
914 let mut ranges = combined.ranges;
915 if ranges.is_empty() {
916 continue;
917 }
918 sort_ranges(&mut ranges);
919 ranges = normalize_combined_injection_ranges(&language_name, ranges);
920 if ranges.is_empty() {
921 continue;
922 }
923 let old_tree = old_combined_trees.get(&language_name).copied();
924 let Some(highlight_query) = highlight_queries.get(&language_name).cloned() else {
925 continue;
926 };
927 if let Some(layer) = Self::parse_injection_layer(
928 &language_name,
929 highlight_query,
930 ranges,
931 old_tree,
932 true,
933 text,
934 ) {
935 new_layers.push(layer);
936 }
937 }
938 new_layers.sort_by_key(|layer| layer.byte_range.start);
939 new_layers
940 }
941
942 /// Parse one injection layer over the given included ranges.
943 /// `old_tree`, when given, has been edited to match `text`.
944 fn parse_injection_layer(
945 language_name: &SharedString,
946 highlight_query: Arc<Query>,
947 ranges: Vec<tree_sitter::Range>,
948 old_tree: Option<&Tree>,
949 combined: bool,
950 text: &Rope,
951 ) -> Option<InjectionLayer> {
952 let (mut parser, grammar) = LanguageRegistry::singleton().parser(language_name).ok()?;
953 parser.set_language(&grammar).ok()?;
954 parser.set_included_ranges(&ranges).ok()?;
955 let parse_start = Instant::now();
956 let mut timed_out = false;
957 let mut progress = |_: &tree_sitter::ParseState| -> ControlFlow<()> {
958 if parse_start.elapsed() > INJECTION_PARSE_TIMEOUT {
959 timed_out = true;
960 ControlFlow::Break(())
961 } else {
962 ControlFlow::Continue(())
963 }
964 };
965 let options = ParseOptions::new().progress_callback(&mut progress);
966
967 let new_tree = parser.parse_with_options(
968 &mut |offset, _| parse_input_bytes(text, offset),
969 old_tree,
970 Some(options),
971 )?;
972 if timed_out {
973 return None;
974 }
975
976 let byte_range = bounding_byte_range(&ranges)?;
977 Some(InjectionLayer {
978 language_name: language_name.clone(),
979 highlight_query,
980 ranges,
981 byte_range,
982 tree: new_tree,
983 combined,
984 })
985 }
986
987 /// Apply a tree that was parsed on a background thread.
988 ///
989 /// `injection_layers` must also be pre-computed in the background via
990 /// [`compute_injection_layers`] to avoid blocking the main thread.
991 pub(crate) fn apply_background_tree(
992 &mut self,
993 tree: Tree,
994 text: &Rope,
995 injection_layers: Vec<InjectionLayer>,
996 ) {
997 // Only apply if the text still matches what was parsed.
998 if !self.text.eq(text) {
999 return;
1000 }
1001
1002 self.tree = Some(tree);
1003 self.injection_layers = injection_layers;
1004 }
1005
1006 /// Parse injection layers after the main tree is updated.
1007 /// pattern: parse once in update, query many times in render.
1008 fn parse_injection_layers(&mut self, tree: &Tree) {
1009 let Some(query) = self.injections_query.clone() else {
1010 self.injection_layers.clear();
1011 return;
1012 };
1013 // The old layers are replaced below, so move them instead of cloning.
1014 let data = InjectionParseData {
1015 query,
1016 content_capture_index: self.injection_content_capture_index,
1017 language_capture_index: self.injection_language_capture_index,
1018 old_layers: std::mem::take(&mut self.injection_layers)
1019 .into_iter()
1020 .map(ReusableInjectionLayer::from)
1021 .collect(),
1022 };
1023 self.injection_layers = Self::compute_injection_layers(data, tree, &self.text);
1024 }
1025
1026 /// Match the visible ranges of nodes in the Tree for highlighting.
1027 fn match_styles(&self, range: Range<usize>) -> Vec<HighlightItem> {
1028 let mut highlights = vec![];
1029 let mut injection_highlights = vec![];
1030 let Some(tree) = &self.tree else {
1031 return highlights;
1032 };
1033
1034 let Some(query) = &self.query else {
1035 return highlights;
1036 };
1037
1038 let root_node = tree.root_node();
1039 let source = &self.text;
1040
1041 // Query pre-parsed injection layers.
1042 let mut last_layer_start = 0;
1043 for layer in &self.injection_layers {
1044 debug_assert!(layer.byte_range.start >= last_layer_start);
1045 last_layer_start = layer.byte_range.start;
1046
1047 if layer.byte_range.end <= range.start {
1048 continue;
1049 }
1050
1051 // Layers are sorted by start byte in compute_injection_layers.
1052 if layer.byte_range.start >= range.end {
1053 break;
1054 }
1055
1056 let query = &layer.highlight_query;
1057
1058 let mut query_cursor = QueryCursor::new();
1059 query_cursor.set_byte_range(range.clone());
1060
1061 let mut matches =
1062 query_cursor.matches(query, layer.tree.root_node(), TextProvider(&self.text));
1063
1064 let mut last_end = 0usize;
1065 while let Some(m) = matches.next() {
1066 let allow_overlapping_captures = query
1067 .property_settings(m.pattern_index)
1068 .iter()
1069 .any(|prop| prop.key.as_ref() == "highlight.allow-overlap");
1070
1071 for cap in m.captures {
1072 let node_range = cap.node.start_byte()..cap.node.end_byte();
1073
1074 if !allow_overlapping_captures && node_range.start < last_end {
1075 continue;
1076 }
1077
1078 if let Some(highlight_name) = query.capture_names().get(cap.index as usize) {
1079 if !allow_overlapping_captures {
1080 last_end = node_range.end;
1081 }
1082 injection_highlights.push(HighlightItem::new(
1083 node_range,
1084 SharedString::from(highlight_name.to_string()),
1085 ));
1086 }
1087 }
1088 }
1089 }
1090
1091 let mut query_cursor = QueryCursor::new();
1092 query_cursor.set_byte_range(range.clone());
1093
1094 let mut matches = query_cursor.matches(query, root_node, TextProvider(source));
1095
1096 while let Some(query_match) = matches.next() {
1097 for cap in query_match.captures {
1098 let node = cap.node;
1099
1100 let Some(highlight_name) = query.capture_names().get(cap.index as usize) else {
1101 continue;
1102 };
1103
1104 let node_range: Range<usize> = node.start_byte()..node.end_byte();
1105 let highlight_name = SharedString::from(highlight_name.to_string());
1106
1107 // Merge near range and same highlight name
1108 let last_item = highlights.last();
1109 let last_range = last_item.map(|item| &item.range).unwrap_or(&(0..0));
1110 let last_highlight_name = last_item.map(|item| item.name.clone());
1111
1112 if last_range == &node_range {
1113 // case:
1114 // last_range: 213..220, last_highlight_name: Some("property")
1115 // last_range: 213..220, last_highlight_name: Some("string")
1116 highlights.push(HighlightItem::new(
1117 node_range,
1118 last_highlight_name.unwrap_or(highlight_name),
1119 ));
1120 } else {
1121 highlights.push(HighlightItem::new(node_range, highlight_name.clone()));
1122 }
1123 }
1124 }
1125
1126 // Injected languages are more specific than the host language. Keep
1127 // them last so their colors win over broad Markdown captures such as
1128 // `fenced_code_block @text.literal`.
1129 highlights.extend(injection_highlights);
1130
1131 // DO NOT REMOVE THIS PRINT, it's useful for debugging
1132 // for item in highlights {
1133 // println!("item: {:?}", item);
1134 // }
1135
1136 highlights
1137 }
1138
1139 /// Returns the syntax highlight styles for a range of text.
1140 ///
1141 /// The argument `range` is the range of bytes in the text to highlight.
1142 ///
1143 /// Returns a vector of tuples where each tuple contains:
1144 /// - A byte range relative to the text
1145 /// - The corresponding highlight style for that range
1146 ///
1147 /// # Example
1148 ///
1149 /// ```no_run
1150 /// # mod gpui_kit { pub extern crate gpui_component as component; }
1151 /// use gpui_kit::component::highlighter::{HighlightTheme, SyntaxHighlighter};
1152 /// use ropey::Rope;
1153 ///
1154 /// let code = "fn main() {\n println!(\"Hello\");\n}";
1155 /// let rope = Rope::from_str(code);
1156 /// let mut highlighter = SyntaxHighlighter::new("rust");
1157 /// highlighter.update(None, &rope, None);
1158 ///
1159 /// let theme = HighlightTheme::default_dark();
1160 /// let range = 0..code.len();
1161 /// let styles = highlighter.styles(&range, &*theme);
1162 /// ```
1163 pub fn styles(
1164 &self,
1165 range: &Range<usize>,
1166 theme: &dyn gpui_base::input::HighlightStyleResolver,
1167 ) -> Vec<(Range<usize>, HighlightStyle)> {
1168 let mut styles = vec![];
1169 let start_offset = range.start;
1170
1171 let highlights = self.match_styles(range.clone());
1172
1173 // let mut iter_count = 0;
1174 for item in highlights {
1175 // iter_count += 1;
1176 let node_range = &item.range;
1177 let name = &item.name;
1178
1179 // Avoid start larger than end
1180 let mut node_range = node_range.start.max(range.start)..node_range.end.min(range.end);
1181 if node_range.start > node_range.end {
1182 node_range.end = node_range.start;
1183 }
1184 // The tree can be stale while a background reparse is pending
1185 // (sync-parse timeout, or the large-text `edit_tree` path), so
1186 // node offsets may fall inside multi-byte characters of the
1187 // current text. Snap to char boundaries — text shaping panics on
1188 // a mid-char style boundary.
1189 node_range = self.text.clip_offset(node_range.start, Bias::Left)
1190 ..self.text.clip_offset(node_range.end, Bias::Right);
1191 if node_range.is_empty() {
1192 continue;
1193 }
1194
1195 styles.push((node_range, theme.style(name.as_ref()).unwrap_or_default()));
1196 }
1197
1198 // If the matched styles is empty, return a default range.
1199 if styles.len() == 0 {
1200 return vec![(start_offset..range.end, HighlightStyle::default())];
1201 }
1202
1203 let styles = unique_styles(&range, styles);
1204
1205 // NOTE: DO NOT remove this comment, it is used for debugging.
1206 // for style in &styles {
1207 // println!("---- style: {:?} - {:?}", style.0, style.1.color);
1208 // }
1209 // println!("--------------------------------");
1210
1211 styles
1212 }
1213}
1214
1215/// To merge intersection ranges, let the subsequent range cover
1216/// the previous overlapping range and split the previous range.
1217///
1218/// From:
1219///
1220/// AA
1221/// BBB
1222/// CCCCC
1223/// DD
1224/// EEEE
1225///
1226/// To:
1227///
1228/// AABCCDDCEEEE
1229pub(crate) fn unique_styles(
1230 total_range: &Range<usize>,
1231 styles: Vec<(Range<usize>, HighlightStyle)>,
1232) -> Vec<(Range<usize>, HighlightStyle)> {
1233 let styles: Vec<_> = styles
1234 .into_iter()
1235 .filter(|(range, _)| !range.is_empty())
1236 .collect();
1237
1238 if styles.is_empty() {
1239 return styles;
1240 }
1241
1242 // Create intervals: (position, is_start, style_index)
1243 let mut intervals: Vec<(usize, bool, usize)> = Vec::with_capacity(styles.len() * 2 + 2);
1244 for (i, (range, _)) in styles.iter().enumerate() {
1245 intervals.push((range.start, true, i));
1246 intervals.push((range.end, false, i));
1247 }
1248
1249 intervals.push((total_range.start, true, usize::MAX));
1250 intervals.push((total_range.end, false, usize::MAX));
1251
1252 // Sort by position, with ends before starts at same position
1253 // This ensures we close ranges before opening new ones at the same position
1254 intervals.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
1255
1256 // Track significant intervals (where style ranges end) for merging decisions
1257 let mut significant_intervals: BTreeSet<usize> = BTreeSet::new();
1258 for (range, _) in &styles {
1259 significant_intervals.insert(range.end);
1260 }
1261
1262 let mut result: Vec<(Range<usize>, HighlightStyle)> = Vec::new();
1263 let mut active_styles: Vec<usize> = Vec::new();
1264 let mut last_pos = total_range.start;
1265
1266 for (pos, is_start, style_idx) in intervals {
1267 // Skip total_range boundaries in active set management
1268 let is_boundary = style_idx == usize::MAX;
1269
1270 if pos > last_pos {
1271 let interval = last_pos..pos;
1272 let combined_style = if active_styles.is_empty() {
1273 HighlightStyle::default()
1274 } else {
1275 let mut combined = HighlightStyle::default();
1276 for &idx in &active_styles {
1277 merge_highlight_style(&mut combined, &styles[idx].1);
1278 }
1279 combined
1280 };
1281 result.push((interval, combined_style));
1282 }
1283
1284 if !is_boundary {
1285 if is_start {
1286 active_styles.push(style_idx);
1287 } else {
1288 active_styles.retain(|&i| i != style_idx);
1289 }
1290 }
1291
1292 last_pos = pos;
1293 }
1294
1295 // Merge adjacent ranges with the same style, but not across significant boundaries
1296 let mut merged: Vec<(Range<usize>, HighlightStyle)> = Vec::with_capacity(result.len());
1297 for (range, style) in result {
1298 if let Some((last_range, last_style)) = merged.last_mut() {
1299 if last_range.end == range.start
1300 && *last_style == style
1301 && !significant_intervals.contains(&range.start)
1302 {
1303 // Merge adjacent ranges with same style, but not across significant boundaries
1304 last_range.end = range.end;
1305 continue;
1306 }
1307 }
1308 merged.push((range, style));
1309 }
1310
1311 merged
1312}
1313
1314/// Merge other style (Other on top)
1315fn merge_highlight_style(style: &mut HighlightStyle, other: &HighlightStyle) {
1316 if let Some(color) = other.color {
1317 style.color = Some(color);
1318 }
1319 if let Some(font_weight) = other.font_weight {
1320 style.font_weight = Some(font_weight);
1321 }
1322 if let Some(font_style) = other.font_style {
1323 style.font_style = Some(font_style);
1324 }
1325 if let Some(background_color) = other.background_color {
1326 style.background_color = Some(background_color);
1327 }
1328 if let Some(underline) = other.underline {
1329 style.underline = Some(underline);
1330 }
1331 if let Some(strikethrough) = other.strikethrough {
1332 style.strikethrough = Some(strikethrough);
1333 }
1334 if let Some(fade_out) = other.fade_out {
1335 style.fade_out = Some(fade_out);
1336 }
1337}
1338
1339#[cfg(test)]
1340mod tests {
1341 use gpui::Hsla;
1342
1343 use super::*;
1344 use crate::Colorize as _;
1345
1346 fn color_style(color: Hsla) -> HighlightStyle {
1347 let mut style = HighlightStyle::default();
1348 style.color = Some(color);
1349 style
1350 }
1351
1352 #[test]
1353 fn test_parse_input_bytes_inside_multibyte_char() {
1354 // Stale trees make tree-sitter read from offsets inside a character;
1355 // the read callback must return bytes instead of panicking.
1356 let rope = Rope::from("let s = \"你好\";");
1357 let start = "let s = \"".len();
1358 assert_eq!(
1359 parse_input_bytes(&rope, start + 1),
1360 &"你好\";".as_bytes()[1..]
1361 );
1362 assert_eq!(parse_input_bytes(&rope, rope.len()), b"");
1363 assert_eq!(parse_input_bytes(&rope, rope.len() + 4), b"");
1364 }
1365
1366 #[test]
1367 fn test_injection_ranges_inside_multibyte_char() {
1368 // Injection ranges come from a tree that can be stale relative to the
1369 // text, so they may start or end inside a character (#3315).
1370 let rope = Rope::from("# 你\n*a*");
1371 let inside = "# ".len() + 1;
1372
1373 assert!(!markdown_inline_range_has_trigger(
1374 &rope,
1375 inside..inside + 1
1376 ));
1377 assert!(markdown_inline_range_has_trigger(&rope, inside..rope.len()));
1378 assert!(markdown_inline_range_has_trigger(
1379 &rope,
1380 inside..rope.len() + 4
1381 ));
1382 assert!(!markdown_inline_range_has_trigger(
1383 &rope,
1384 rope.len() + 1..rope.len() + 4
1385 ));
1386
1387 assert_eq!(captured_injection_language(&rope, inside..rope.len()), None);
1388 assert_eq!(
1389 captured_injection_language(&rope, "# ".len()..inside + 2),
1390 Some("你".into())
1391 );
1392 }
1393
1394 #[test]
1395 fn test_plain_text_never_parses() {
1396 // "text" has no grammar, the highlighter shouldn't parse.
1397 let mut highlighter = SyntaxHighlighter::new("text");
1398 let rope = Rope::from("hello {\"a\": 1}\nworld");
1399 assert!(highlighter.update(None, &rope, None));
1400 assert!(highlighter.tree().is_none());
1401 assert_eq!(highlighter.text().to_string(), rope.to_string());
1402
1403 let theme = HighlightTheme::default_dark();
1404 let styles = highlighter.styles(&(0..rope.len()), theme.as_ref());
1405 assert_eq!(styles, vec![(0..rope.len(), HighlightStyle::default())]);
1406
1407 // Unregistered languages fall back to plain text.
1408 let mut highlighter = SyntaxHighlighter::new("no-such-language");
1409 assert!(highlighter.update(None, &rope, None));
1410 assert!(highlighter.tree().is_none());
1411 }
1412
1413 /// While a background reparse is pending (sync-parse timeout, or the
1414 /// large-text `edit_tree` path), `styles()` serves ranges from a stale
1415 /// tree. Those must still land on char boundaries of the current text,
1416 /// or text shaping panics on multi-byte characters.
1417 #[cfg(feature = "tree-sitter-languages")]
1418 #[test]
1419 fn test_stale_tree_styles_snap_to_char_boundaries() {
1420 let mut highlighter = SyntaxHighlighter::new("markdown");
1421 let old = Rope::from("# hello world\n*emphasis* and `code` here\n");
1422 assert!(highlighter.update(None, &old, None));
1423 assert!(highlighter.tree().is_some());
1424
1425 // Swap the text without reparsing: the tree is now stale and its node
1426 // offsets point into the middle of the new text's CJK characters.
1427 let new = Rope::from("# 你好,世界\n你好,*世界* 与 `代码`\n");
1428 highlighter.edit_tree(None, &new);
1429
1430 let theme = HighlightTheme::default_dark();
1431 let styles = highlighter.styles(&(0..new.len()), theme.as_ref());
1432 assert!(!styles.is_empty());
1433 for (range, _) in &styles {
1434 assert!(
1435 new.is_char_boundary(range.start) && new.is_char_boundary(range.end),
1436 "style range {range:?} is not on char boundaries of the current text"
1437 );
1438 }
1439 }
1440
1441 #[cfg(feature = "tree-sitter-languages")]
1442 fn has_highlight_covering(
1443 highlights: &[HighlightItem],
1444 source: &str,
1445 text: &str,
1446 highlight_name: &str,
1447 ) -> bool {
1448 let start = source.find(text).expect("text should exist in source");
1449 let end = start + text.len();
1450 highlights.iter().any(|item| {
1451 item.name.as_ref() == highlight_name
1452 && item.range.start <= start
1453 && item.range.end >= end
1454 })
1455 }
1456
1457 #[track_caller]
1458 fn assert_unique_styles(
1459 range: Range<usize>,
1460 left: Vec<(Range<usize>, HighlightStyle)>,
1461 right: Vec<(Range<usize>, HighlightStyle)>,
1462 ) {
1463 fn color_name(c: Option<Hsla>) -> String {
1464 match c {
1465 Some(c) => {
1466 if c == gpui::red() {
1467 "red".to_string()
1468 } else if c == gpui::green() {
1469 "green".to_string()
1470 } else if c == gpui::blue() {
1471 "blue".to_string()
1472 } else {
1473 c.to_hex()
1474 }
1475 }
1476 None => "clean".to_string(),
1477 }
1478 }
1479
1480 let left = unique_styles(&range, left);
1481 if left.len() != right.len() {
1482 println!("\n---------------------------------------------");
1483 for (range, style) in left.iter() {
1484 println!("({:?}, {})", range, color_name(style.color));
1485 }
1486 println!("---------------------------------------------");
1487 panic!("left {} styles, right {} styles", left.len(), right.len());
1488 }
1489 for (left, right) in left.into_iter().zip(right) {
1490 if left.1.color != right.1.color || left.0 != right.0 {
1491 panic!(
1492 "\n left: ({:?}, {})\nright: ({:?}, {})\n",
1493 left.0,
1494 color_name(left.1.color),
1495 right.0,
1496 color_name(right.1.color)
1497 );
1498 }
1499 }
1500 }
1501
1502 #[test]
1503 #[cfg(feature = "tree-sitter-languages")]
1504 fn test_html_style_injects_css_highlights() {
1505 let html = r#"<style>
1506.card { color: #336699; }
1507</style>
1508"#;
1509
1510 let rope = Rope::from_str(html);
1511 let mut highlighter = SyntaxHighlighter::new("html");
1512 highlighter.update(None, &rope, None);
1513
1514 let highlights = highlighter.match_styles(0..html.len());
1515
1516 assert!(
1517 has_highlight_covering(&highlights, html, "color", "property"),
1518 "CSS property names inside style elements should be highlighted"
1519 );
1520 assert!(
1521 has_highlight_covering(&highlights, html, "#336699", "string.special"),
1522 "CSS color values inside style elements should be highlighted"
1523 );
1524 }
1525
1526 #[test]
1527 #[cfg(feature = "tree-sitter-languages")]
1528 fn test_html_script_injects_javascript_highlights() {
1529 let html = r#"<script>
1530const answer = 42;
1531console.log(answer);
1532</script>
1533"#;
1534
1535 let rope = Rope::from_str(html);
1536 let mut highlighter = SyntaxHighlighter::new("html");
1537 highlighter.update(None, &rope, None);
1538
1539 let highlights = highlighter.match_styles(0..html.len());
1540
1541 assert!(
1542 has_highlight_covering(&highlights, html, "const", "keyword"),
1543 "JavaScript keywords inside script elements should be highlighted"
1544 );
1545 assert!(
1546 has_highlight_covering(&highlights, html, "answer", "variable"),
1547 "JavaScript identifiers inside script elements should be highlighted"
1548 );
1549 }
1550
1551 #[test]
1552 #[cfg(feature = "tree-sitter-languages")]
1553 fn test_kotlin_highlights_string_templates() {
1554 let kotlin = "fun greet(name: String) = \"hi $name, ${name.length}\"\n";
1555
1556 let rope = Rope::from_str(kotlin);
1557 let mut highlighter = SyntaxHighlighter::new("kotlin");
1558 highlighter.update(None, &rope, None);
1559
1560 let highlights = highlighter.match_styles(0..kotlin.len());
1561
1562 assert!(
1563 has_highlight_covering(&highlights, kotlin, "fun", "keyword"),
1564 "Kotlin keywords should be highlighted"
1565 );
1566 assert!(
1567 has_highlight_covering(&highlights, kotlin, "$", "punctuation.special"),
1568 "A string template's `$` should be highlighted"
1569 );
1570 assert!(
1571 has_highlight_covering(&highlights, kotlin, "${", "punctuation.special"),
1572 "A string template's `${{` should be highlighted"
1573 );
1574 }
1575
1576 #[test]
1577 #[cfg(feature = "tree-sitter-languages")]
1578 fn test_markdown_fenced_code_injects_captured_language() {
1579 let markdown = "```rs\nfn first() {}\n```\n\n```rust\nfn second() {}\n```\n";
1580 let rope = Rope::from_str(markdown);
1581 let mut highlighter = SyntaxHighlighter::new("markdown");
1582
1583 assert!(highlighter.update(None, &rope, None));
1584
1585 let rust_layers = highlighter
1586 .injection_layers
1587 .iter()
1588 .filter(|layer| layer.language_name.as_ref() == "rust")
1589 .collect::<Vec<_>>();
1590 assert_eq!(rust_layers.len(), 2);
1591 assert!(
1592 Arc::ptr_eq(
1593 &rust_layers[0].highlight_query,
1594 &rust_layers[1].highlight_query
1595 ),
1596 "fences using the same canonical language should share one highlight query"
1597 );
1598
1599 let highlights = highlighter.match_styles(0..markdown.len());
1600 for function in ["first", "second"] {
1601 assert!(
1602 has_highlight_covering(&highlights, markdown, function, "function"),
1603 "Rust function {function:?} should be highlighted inside its fence"
1604 );
1605 }
1606
1607 let theme = HighlightTheme::default_dark();
1608 let styles = highlighter.styles(&(0..markdown.len()), theme.as_ref());
1609 let keyword_start = markdown.find("fn first").unwrap();
1610 let keyword_color = theme.style("keyword").and_then(|style| style.color);
1611 assert!(styles.iter().any(|(range, style)| {
1612 range.start <= keyword_start
1613 && range.end >= keyword_start + 2
1614 && style.color == keyword_color
1615 }));
1616 }
1617
1618 /// Injection layers are edited along with the text and reused as old
1619 /// trees. Every edit must highlight exactly like a from-scratch parse.
1620 #[test]
1621 #[cfg(feature = "tree-sitter-languages")]
1622 fn test_incremental_injection_layers_match_fresh_parse() {
1623 fn point_at(text: &str, offset: usize) -> Point {
1624 let before = &text[..offset];
1625 let row = before.matches('\n').count();
1626 let column = offset - before.rfind('\n').map_or(0, |ix| ix + 1);
1627 Point::new(row, column)
1628 }
1629
1630 let mut source = String::from(
1631 "# Title\n\nSome *emphasis* and `code`.\n\n```rust\nfn first() {}\n```\n\n\
1632 More **bold** text.\n\n```html\n<b>x</b>\n```\n",
1633 );
1634 let mut highlighter = SyntaxHighlighter::new("markdown");
1635 assert!(highlighter.update(None, &Rope::from_str(&source), None));
1636
1637 let theme = HighlightTheme::default_dark();
1638 for (target, replacement) in [
1639 // Before every layer, shifting all of them.
1640 ("# Title", "# Longer title"),
1641 // Inside a fence.
1642 ("fn first", "fn renamed_first"),
1643 // Inside the combined inline text.
1644 ("*emphasis*", "*more emphasis*"),
1645 // Adds a new inline range to the combined layer.
1646 ("text.", "text with `span`."),
1647 // Inside the last fence, adding a line.
1648 ("<b>x</b>", "<i>y</i>\n<b>x</b>"),
1649 // A deletion before every layer.
1650 ("# Longer title\n\n", ""),
1651 ] {
1652 let start = source.find(target).expect("target should exist in source");
1653 let end = start + target.len();
1654 let new_source = format!("{}{}{}", &source[..start], replacement, &source[end..]);
1655 let new_end = start + replacement.len();
1656 let edit = InputEdit {
1657 start_byte: start,
1658 old_end_byte: end,
1659 new_end_byte: new_end,
1660 start_position: point_at(&source, start),
1661 old_end_position: point_at(&source, end),
1662 new_end_position: point_at(&new_source, new_end),
1663 };
1664 source = new_source;
1665
1666 let rope = Rope::from_str(&source);
1667 assert!(highlighter.update(Some(edit), &rope, None));
1668 let mut fresh = SyntaxHighlighter::new("markdown");
1669 assert!(fresh.update(None, &rope, None));
1670 assert_eq!(
1671 highlighter.styles(&(0..rope.len()), theme.as_ref()),
1672 fresh.styles(&(0..rope.len()), theme.as_ref()),
1673 "styles differ after replacing {target:?} with {replacement:?}"
1674 );
1675 }
1676 }
1677
1678 #[test]
1679 #[cfg(feature = "tree-sitter-languages")]
1680 fn test_markdown_unknown_fence_language_does_not_allocate_layer() {
1681 let markdown = "```not-a-registered-language\nplain content\n```\n";
1682 let rope = Rope::from_str(markdown);
1683 let mut highlighter = SyntaxHighlighter::new("markdown");
1684
1685 assert!(highlighter.update(None, &rope, None));
1686 assert!(
1687 highlighter
1688 .injection_layers
1689 .iter()
1690 .all(|layer| { layer.language_name.as_ref() != "not-a-registered-language" })
1691 );
1692 }
1693
1694 #[test]
1695 #[cfg(feature = "tree-sitter-languages")]
1696 fn test_markdown_fenced_code_highlights_blocks_beyond_previous_limit() {
1697 const FENCE_COUNT: usize = 384;
1698 const _: () = assert!(FENCE_COUNT <= MAX_NON_COMBINED_INJECTION_PARSES);
1699 let markdown = (0..FENCE_COUNT)
1700 .map(|i| format!("```rust\nfn function_{i}() {{}}\n```\n"))
1701 .collect::<String>();
1702 let rope = Rope::from_str(&markdown);
1703 let mut highlighter = SyntaxHighlighter::new("markdown");
1704
1705 assert!(highlighter.update(None, &rope, None));
1706 assert_eq!(highlighter.injection_layers.len(), FENCE_COUNT);
1707 assert!(
1708 highlighter
1709 .injection_layers
1710 .iter()
1711 .all(|layer| layer.language_name.as_ref() == "rust")
1712 );
1713
1714 let highlights = highlighter.match_styles(0..markdown.len());
1715 assert!(has_highlight_covering(
1716 &highlights,
1717 &markdown,
1718 "function_383",
1719 "function"
1720 ));
1721 }
1722
1723 #[test]
1724 #[cfg(feature = "tree-sitter-languages")]
1725 fn test_markdown_fenced_code_injection_layers_are_bounded() {
1726 const FENCE_COUNT: usize = MAX_NON_COMBINED_INJECTION_PARSES + 128;
1727 // The paragraph trails the fences so the combined match is only reached
1728 // once the non-combined budget is already exhausted.
1729 let markdown = format!(
1730 "{}\nparagraph *inline*\n",
1731 (0..FENCE_COUNT)
1732 .map(|i| format!("```rust\nfn function_{i}() {{}}\n```\n"))
1733 .collect::<String>()
1734 );
1735 let rope = Rope::from_str(&markdown);
1736 let mut highlighter = SyntaxHighlighter::new("markdown");
1737
1738 assert!(highlighter.update(None, &rope, None));
1739 assert_eq!(
1740 highlighter
1741 .injection_layers
1742 .iter()
1743 .filter(|layer| layer.language_name.as_ref() == "rust")
1744 .count(),
1745 MAX_NON_COMBINED_INJECTION_PARSES
1746 );
1747 assert!(
1748 highlighter
1749 .injection_layers
1750 .iter()
1751 .any(|layer| layer.language_name.as_ref() == "markdown_inline"),
1752 "the non-combined budget should not starve combined injection layers"
1753 );
1754
1755 let highlights = highlighter.match_styles(0..markdown.len());
1756 assert!(has_highlight_covering(
1757 &highlights,
1758 &markdown,
1759 "function_0",
1760 "function"
1761 ));
1762 assert!(
1763 !has_highlight_covering(
1764 &highlights,
1765 &markdown,
1766 &format!("function_{}", FENCE_COUNT - 1),
1767 "function"
1768 ),
1769 "fences past the budget keep host highlighting but get no injected tokens"
1770 );
1771 }
1772
1773 #[test]
1774 #[cfg(feature = "tree-sitter-languages")]
1775 fn test_php_combined_injection_closing_tags() {
1776 let php_code = r#"<?php
1777$x = 1;
1778?>
1779<html>
1780<body>
1781 <h1><?php echo "Hello"; ?></h1>
1782 <ul>
1783 <?php foreach ($items as $item): ?>
1784 <li><?php echo $item; ?></li>
1785 <?php endforeach; ?>
1786 </ul>
1787</body>
1788</html>
1789"#;
1790
1791 let rope = Rope::from_str(php_code);
1792 let mut highlighter = SyntaxHighlighter::new("php");
1793 highlighter.update(None, &rope, None);
1794
1795 let full_range = 0..php_code.len();
1796 let highlights = highlighter.match_styles(full_range);
1797
1798 // Verify all closing HTML tags are highlighted
1799 let closing_tags = ["</h1>", "</li>", "</ul>", "</body>", "</html>"];
1800 for tag in closing_tags {
1801 let pos = php_code.find(tag).unwrap();
1802 let tag_name_start = pos + 2; // after "</"
1803 let tag_name_end = tag_name_start + tag.len() - 3; // before ">"
1804
1805 let has_highlight = highlights
1806 .iter()
1807 .any(|item| item.range.start <= tag_name_start && item.range.end >= tag_name_end);
1808
1809 assert!(
1810 has_highlight,
1811 "closing tag {} at byte {} should be highlighted",
1812 tag, pos
1813 );
1814 }
1815 }
1816
1817 #[test]
1818 #[cfg(feature = "tree-sitter-languages")]
1819 fn test_markdown_inline_injection_layers_are_bounded() {
1820 let markdown = (0..(MAX_INJECTION_RANGES + 1024))
1821 .map(|i| format!("paragraph {i} *x*\n\n"))
1822 .collect::<String>();
1823 let rope = Rope::from_str(markdown.as_str());
1824 let mut highlighter = SyntaxHighlighter::new("markdown");
1825
1826 assert!(highlighter.update(None, &rope, None));
1827 assert!(
1828 highlighter.injection_layers.len() <= 1,
1829 "markdown_inline should be combined instead of one layer per inline node"
1830 );
1831
1832 if let Some(layer) = highlighter
1833 .injection_layers
1834 .iter()
1835 .find(|layer| layer.language_name.as_ref() == "markdown_inline")
1836 {
1837 assert!(layer.ranges.len() <= MAX_INJECTION_RANGES);
1838 assert!(injection_ranges_byte_count(&layer.ranges) <= MAX_INJECTION_BYTES);
1839 }
1840
1841 let plain_markdown = (0..1024)
1842 .map(|i| format!("paragraph {i} plain\n\n"))
1843 .collect::<String>();
1844 let plain_rope = Rope::from_str(plain_markdown.as_str());
1845 let mut plain_highlighter = SyntaxHighlighter::new("markdown");
1846
1847 assert!(plain_highlighter.update(None, &plain_rope, None));
1848 assert!(
1849 plain_highlighter
1850 .injection_layers
1851 .iter()
1852 .all(|layer| layer.language_name.as_ref() != "markdown_inline"),
1853 "plain inline ranges should not create markdown_inline injection layers"
1854 );
1855 }
1856
1857 #[test]
1858 #[cfg(feature = "tree-sitter-languages")]
1859 fn test_markdown_inline_code_spans_in_list_items() {
1860 let markdown = "- `one`\n- `two`\n- `three`\n\nLater `four`\n";
1861 let rope = Rope::from_str(markdown);
1862 let mut highlighter = SyntaxHighlighter::new("markdown");
1863 highlighter.update(None, &rope, None);
1864
1865 let highlights = highlighter.match_styles(0..markdown.len());
1866 for text in ["one", "two", "three", "four"] {
1867 assert!(
1868 has_highlight_covering(&highlights, markdown, text, "text.code.span"),
1869 "{text:?} should be highlighted as a code span"
1870 );
1871 }
1872
1873 let prose_start = markdown.find("Later").unwrap();
1874 let prose_end = prose_start + "Later".len();
1875 assert!(
1876 !highlights.iter().any(|item| {
1877 item.name.as_ref() == "text.code.span"
1878 && item.range.start <= prose_start
1879 && item.range.end >= prose_end
1880 }),
1881 "plain prose after the list should not be highlighted as a code span"
1882 );
1883 }
1884
1885 #[test]
1886 #[cfg(feature = "tree-sitter-languages")]
1887 fn test_highlight_allow_overlap_property_combines_nested_captures() {
1888 let markdown = "This has **_bold and italic_** and **bold _with_ italic** text.";
1889 let rope = Rope::from_str(markdown);
1890 let mut highlighter = SyntaxHighlighter::new("markdown");
1891 highlighter.update(None, &rope, None);
1892
1893 let theme = HighlightTheme::default_dark();
1894 let styles = highlighter.styles(&(0..markdown.len()), theme.as_ref());
1895 for text in ["bold and italic", "with"] {
1896 let start = markdown.find(text).unwrap();
1897 let end = start + text.len();
1898
1899 assert!(
1900 styles.iter().any(|(range, style)| {
1901 range.start <= start
1902 && range.end >= end
1903 && style.font_weight == Some(gpui::FontWeight::BOLD)
1904 && style.font_style == Some(gpui::FontStyle::Italic)
1905 }),
1906 "{text:?} should combine bold and italic styles"
1907 );
1908 }
1909
1910 let highlights = highlighter.match_styles(0..markdown.len());
1911 let delimiter_start = markdown.find("_with_").unwrap();
1912 let delimiter_end = delimiter_start + "_".len();
1913
1914 assert!(
1915 highlights.iter().any(|item| {
1916 item.name.as_ref() == "punctuation.delimiter"
1917 && item.range.start <= delimiter_start
1918 && item.range.end >= delimiter_end
1919 }),
1920 "overlap-enabled captures should not hide nested delimiter highlights"
1921 );
1922 }
1923
1924 #[test]
1925 fn test_unique_styles() {
1926 let red = color_style(gpui::red());
1927 let green = color_style(gpui::green());
1928 let blue = color_style(gpui::blue());
1929 let clean = HighlightStyle::default();
1930
1931 assert_unique_styles(
1932 0..65,
1933 vec![
1934 (2..10, clean),
1935 (2..10, clean),
1936 (5..11, red),
1937 (2..6, clean),
1938 (10..15, green),
1939 (15..30, clean),
1940 (29..35, blue),
1941 (35..40, green),
1942 (45..60, blue),
1943 ],
1944 vec![
1945 (0..5, clean),
1946 (5..6, red),
1947 (6..10, red),
1948 (10..11, green),
1949 (11..15, green),
1950 (15..29, clean),
1951 (29..30, blue),
1952 (30..35, blue),
1953 (35..40, green),
1954 (40..45, clean),
1955 (45..60, blue),
1956 (60..65, clean),
1957 ],
1958 );
1959
1960 assert_unique_styles(
1961 0..10,
1962 vec![(2..2, red), (4..6, green)],
1963 vec![(0..4, clean), (4..6, green), (6..10, clean)],
1964 );
1965 }
1966}