Debian Codegraph @

helix-core/src/syntax.rs

raw symbols SCIP
1 pub mod config;
2
3 use std::{
4 borrow::Cow,
5 collections::HashMap,
6 fmt, iter,
7 ops::{self, RangeBounds},
8 path::Path,
9 sync::Arc,
10 time::Duration,
11 };
12
13 use anyhow::{Context, Result};
14 use arc_swap::{ArcSwap, Guard};
15 use config::{Configuration, FileType, LanguageConfiguration, LanguageServerConfiguration};
16 use foldhash::HashSet;
17 use helix_loader::grammar::get_language;
18 use helix_stdx::rope::RopeSliceExt as _;
19 use once_cell::sync::OnceCell;
20 use ropey::RopeSlice;
21 use tree_house::{
22 highlighter,
23 query_iter::QueryIter,
24 tree_sitter::{
25 query::{InvalidPredicateError, UserPredicate},
26 Capture, Grammar, InactiveQueryCursor, InputEdit, Node, Pattern, Query, RopeInput, Tree,
27 },
28 Error, InjectionLanguageMarker, LanguageConfig as SyntaxConfig, Layer,
29 };
30
31 use crate::{indent::IndentQuery, tree_sitter, ChangeSet, Language};
32
33 pub use tree_house::{
34 highlighter::{Highlight, HighlightEvent},
35 query_iter::{CapturedMatch, QueryIterEvent, QueryMatchIter, QueryMatchIterEvent},
36 Error as HighlighterError, LanguageLoader, TreeCursor, TREE_SITTER_MATCH_LIMIT,
37 };
38
39 #[derive(Debug)]
40 pub struct LanguageData {
41 config: Arc<LanguageConfiguration>,
42 syntax: OnceCell<Option<SyntaxConfig>>,
43 indent_query: OnceCell<Option<IndentQuery>>,
44 textobject_query: OnceCell<Option<TextObjectQuery>>,
45 tag_query: OnceCell<Option<TagQuery>>,
46 rainbow_query: OnceCell<Option<RainbowQuery>>,
47 }
48
49 impl LanguageData {
50 fn new(config: LanguageConfiguration) -> Self {
51 Self {
52 config: Arc::new(config),
53 syntax: OnceCell::new(),
54 indent_query: OnceCell::new(),
55 textobject_query: OnceCell::new(),
56 tag_query: OnceCell::new(),
57 rainbow_query: OnceCell::new(),
58 }
59 }
60
61 pub fn config(&self) -> &Arc<LanguageConfiguration> {
62 &self.config
63 }
64
65 /// Loads the grammar and compiles the highlights, injections and locals for the language.
66 /// This function should only be used by this module or the xtask crate.
67 pub fn compile_syntax_config(
68 config: &LanguageConfiguration,
69 loader: &Loader,
70 ) -> Result<Option<SyntaxConfig>> {
71 let name = &config.language_id;
72 let parser_name = config.grammar.as_deref().unwrap_or(name);
73 let Some(grammar) = get_language(parser_name)? else {
74 log::info!("Skipping syntax config for '{name}' because the parser's shared library does not exist");
75 return Ok(None);
76 };
77 let highlight_query_text = read_query(name, "highlights.scm");
78 let injection_query_text = read_query(name, "injections.scm");
79 let local_query_text = read_query(name, "locals.scm");
80 let config = SyntaxConfig::new(
81 grammar,
82 &highlight_query_text,
83 &injection_query_text,
84 &local_query_text,
85 )
86 .with_context(|| format!("Failed to compile highlights for '{name}'"))?;
87
88 reconfigure_highlights(&config, &loader.scopes());
89
90 Ok(Some(config))
91 }
92
93 fn syntax_config(&self, loader: &Loader) -> Option<&SyntaxConfig> {
94 self.syntax
95 .get_or_init(|| {
96 Self::compile_syntax_config(&self.config, loader)
97 .map_err(|err| {
98 log::error!("{err:#}");
99 })
100 .ok()
101 .flatten()
102 })
103 .as_ref()
104 }
105
106 /// Compiles the indents.scm query for a language.
107 /// This function should only be used by this module or the xtask crate.
108 pub fn compile_indent_query(
109 grammar: Grammar,
110 config: &LanguageConfiguration,
111 ) -> Result<Option<IndentQuery>> {
112 let name = &config.language_id;
113 let text = read_query(name, "indents.scm");
114 if text.is_empty() {
115 return Ok(None);
116 }
117 let indent_query = IndentQuery::new(grammar, &text)
118 .with_context(|| format!("Failed to compile indents.scm query for '{name}'"))?;
119 Ok(Some(indent_query))
120 }
121
122 fn indent_query(&self, loader: &Loader) -> Option<&IndentQuery> {
123 self.indent_query
124 .get_or_init(|| {
125 let grammar = self.syntax_config(loader)?.grammar;
126 Self::compile_indent_query(grammar, &self.config)
127 .map_err(|err| {
128 log::error!("{err}");
129 })
130 .ok()
131 .flatten()
132 })
133 .as_ref()
134 }
135
136 /// Compiles the textobjects.scm query for a language.
137 /// This function should only be used by this module or the xtask crate.
138 pub fn compile_textobject_query(
139 grammar: Grammar,
140 config: &LanguageConfiguration,
141 ) -> Result<Option<TextObjectQuery>> {
142 let name = &config.language_id;
143 let text = read_query(name, "textobjects.scm");
144 if text.is_empty() {
145 return Ok(None);
146 }
147 let query = Query::new(grammar, &text, |_, _| Ok(()))
148 .with_context(|| format!("Failed to compile textobjects.scm queries for '{name}'"))?;
149 Ok(Some(TextObjectQuery::new(query)))
150 }
151
152 fn textobject_query(&self, loader: &Loader) -> Option<&TextObjectQuery> {
153 self.textobject_query
154 .get_or_init(|| {
155 let grammar = self.syntax_config(loader)?.grammar;
156 Self::compile_textobject_query(grammar, &self.config)
157 .map_err(|err| {
158 log::error!("{err}");
159 })
160 .ok()
161 .flatten()
162 })
163 .as_ref()
164 }
165
166 /// Compiles the tags.scm query for a language.
167 /// This function should only be used by this module or the xtask crate.
168 pub fn compile_tag_query(
169 grammar: Grammar,
170 config: &LanguageConfiguration,
171 ) -> Result<Option<TagQuery>> {
172 let name = &config.language_id;
173 let text = read_query(name, "tags.scm");
174 if text.is_empty() {
175 return Ok(None);
176 }
177 let query = Query::new(grammar, &text, |_pattern, predicate| match predicate {
178 // TODO: these predicates are allowed in tags.scm queries but not yet used.
179 UserPredicate::IsPropertySet { key: "local", .. } => Ok(()),
180 UserPredicate::Other(pred) => match pred.name() {
181 "strip!" | "select-adjacent!" => Ok(()),
182 _ => Err(InvalidPredicateError::unknown(predicate)),
183 },
184 _ => Err(InvalidPredicateError::unknown(predicate)),
185 })
186 .with_context(|| format!("Failed to compile tags.scm query for '{name}'"))?;
187 Ok(Some(TagQuery { query }))
188 }
189
190 fn tag_query(&self, loader: &Loader) -> Option<&TagQuery> {
191 self.tag_query
192 .get_or_init(|| {
193 let grammar = self.syntax_config(loader)?.grammar;
194 Self::compile_tag_query(grammar, &self.config)
195 .map_err(|err| {
196 log::error!("{err}");
197 })
198 .ok()
199 .flatten()
200 })
201 .as_ref()
202 }
203
204 /// Compiles the rainbows.scm query for a language.
205 /// This function should only be used by this module or the xtask crate.
206 pub fn compile_rainbow_query(
207 grammar: Grammar,
208 config: &LanguageConfiguration,
209 ) -> Result<Option<RainbowQuery>> {
210 let name = &config.language_id;
211 let text = read_query(name, "rainbows.scm");
212 if text.is_empty() {
213 return Ok(None);
214 }
215 let rainbow_query = RainbowQuery::new(grammar, &text)
216 .with_context(|| format!("Failed to compile rainbows.scm query for '{name}'"))?;
217 Ok(Some(rainbow_query))
218 }
219
220 fn rainbow_query(&self, loader: &Loader) -> Option<&RainbowQuery> {
221 self.rainbow_query
222 .get_or_init(|| {
223 let grammar = self.syntax_config(loader)?.grammar;
224 Self::compile_rainbow_query(grammar, &self.config)
225 .map_err(|err| {
226 log::error!("{err}");
227 })
228 .ok()
229 .flatten()
230 })
231 .as_ref()
232 }
233
234 fn reconfigure(&self, scopes: &[String]) {
235 if let Some(Some(config)) = self.syntax.get() {
236 reconfigure_highlights(config, scopes);
237 }
238 }
239 }
240
241 fn reconfigure_highlights(config: &SyntaxConfig, recognized_names: &[String]) {
242 config.configure(move |capture_name| {
243 let capture_parts: Vec<_> = capture_name.split('.').collect();
244
245 let mut best_index = None;
246 let mut best_match_len = 0;
247 for (i, recognized_name) in recognized_names.iter().enumerate() {
248 let mut len = 0;
249 let mut matches = true;
250 for (i, part) in recognized_name.split('.').enumerate() {
251 match capture_parts.get(i) {
252 Some(capture_part) if *capture_part == part => len += 1,
253 _ => {
254 matches = false;
255 break;
256 }
257 }
258 }
259 if matches && len > best_match_len {
260 best_index = Some(i);
261 best_match_len = len;
262 }
263 }
264 best_index.map(|idx| Highlight::new(idx as u32))
265 });
266 }
267
268 pub fn read_query(lang: &str, query_filename: &str) -> String {
269 tree_house::read_query(lang, |language| {
270 helix_loader::grammar::load_runtime_file(language, query_filename).unwrap_or_default()
271 })
272 }
273
274 #[derive(Debug, Default)]
275 pub struct Loader {
276 languages: Vec<LanguageData>,
277 languages_by_extension: HashMap<String, Language>,
278 languages_by_shebang: HashMap<String, Language>,
279 languages_glob_matcher: FileTypeGlobMatcher,
280 language_server_configs: HashMap<String, LanguageServerConfiguration>,
281 scopes: ArcSwap<Vec<String>>,
282 }
283
284 pub type LoaderError = globset::Error;
285
286 impl Loader {
287 pub fn new(config: Configuration) -> Result<Self, LoaderError> {
288 let mut languages = Vec::with_capacity(config.language.len());
289 let mut languages_by_extension = HashMap::new();
290 let mut languages_by_shebang = HashMap::new();
291 let mut file_type_globs = Vec::new();
292
293 for mut config in config.language {
294 let language = Language(languages.len() as u32);
295 config.language = Some(language);
296
297 for file_type in &config.file_types {
298 match file_type {
299 FileType::Extension(extension) => {
300 languages_by_extension.insert(extension.clone(), language);
301 }
302 FileType::Glob(glob) => {
303 file_type_globs.push(FileTypeGlob::new(glob.to_owned(), language));
304 }
305 };
306 }
307 for shebang in &config.shebangs {
308 languages_by_shebang.insert(shebang.clone(), language);
309 }
310
311 languages.push(LanguageData::new(config));
312 }
313
314 Ok(Self {
315 languages,
316 languages_by_extension,
317 languages_by_shebang,
318 languages_glob_matcher: FileTypeGlobMatcher::new(file_type_globs)?,
319 language_server_configs: config.language_server,
320 scopes: ArcSwap::from_pointee(Vec::new()),
321 })
322 }
323
324 pub fn languages(&self) -> impl ExactSizeIterator<Item = (Language, &LanguageData)> {
325 self.languages
326 .iter()
327 .enumerate()
328 .map(|(idx, data)| (Language(idx as u32), data))
329 }
330
331 pub fn language_configs(&self) -> impl ExactSizeIterator<Item = &LanguageConfiguration> {
332 self.languages.iter().map(|language| &*language.config)
333 }
334
335 pub fn language(&self, lang: Language) -> &LanguageData {
336 &self.languages[lang.idx()]
337 }
338
339 pub fn language_for_name(&self, name: impl PartialEq<String>) -> Option<Language> {
340 self.languages.iter().enumerate().find_map(|(idx, config)| {
341 (name == config.config.language_id).then_some(Language(idx as u32))
342 })
343 }
344
345 pub fn language_for_scope(&self, scope: &str) -> Option<Language> {
346 self.languages.iter().enumerate().find_map(|(idx, config)| {
347 (scope == config.config.scope).then_some(Language(idx as u32))
348 })
349 }
350
351 pub fn language_for_match(&self, text: RopeSlice) -> Option<Language> {
352 // PERF: If the name matches up with the id, then this saves the need to do expensive regex.
353 let shortcircuit = self.language_for_name(text);
354 if shortcircuit.is_some() {
355 return shortcircuit;
356 }
357
358 // If the name did not match up with a known id, then match on injection regex.
359
360 let mut best_match_length = 0;
361 let mut best_match_position = None;
362 for (idx, data) in self.languages.iter().enumerate() {
363 if let Some(injection_regex) = &data.config.injection_regex {
364 if let Some(mat) = injection_regex.find(text.regex_input()) {
365 let length = mat.end() - mat.start();
366 if length > best_match_length {
367 best_match_position = Some(idx);
368 best_match_length = length;
369 }
370 }
371 }
372 }
373
374 best_match_position.map(|i| Language(i as u32))
375 }
376
377 pub fn language_for_filename(&self, path: &Path) -> Option<Language> {
378 // Find all the language configurations that match this file name
379 // or a suffix of the file name.
380
381 // TODO: content_regex handling conflict resolution
382 self.languages_glob_matcher
383 .language_for_path(path)
384 .or_else(|| {
385 path.extension()
386 .and_then(|extension| extension.to_str())
387 .and_then(|extension| self.languages_by_extension.get(extension).copied())
388 })
389 }
390
391 pub fn language_for_shebang(&self, text: RopeSlice) -> Option<Language> {
392 // NOTE: this is slightly different than the one for injection markers in tree-house. It
393 // is anchored at the beginning.
394 use helix_stdx::rope::Regex;
395 use once_cell::sync::Lazy;
396 const SHEBANG: &str = r"^#!\s*(?:\S*[/\\](?:env\s+(?:\-\S+\s+)*)?)?([^\s\.\d]+)";
397 static SHEBANG_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(SHEBANG).unwrap());
398
399 let marker = SHEBANG_REGEX
400 .captures_iter(regex_cursor::Input::new(text))
401 .map(|cap| text.byte_slice(cap.get_group(1).unwrap().range()))
402 .next()?;
403 self.language_for_shebang_marker(marker)
404 }
405
406 fn language_for_shebang_marker(&self, marker: RopeSlice) -> Option<Language> {
407 let shebang: Cow<str> = marker.into();
408 self.languages_by_shebang.get(shebang.as_ref()).copied()
409 }
410
411 pub fn indent_query(&self, lang: Language) -> Option<&IndentQuery> {
412 self.language(lang).indent_query(self)
413 }
414
415 pub fn textobject_query(&self, lang: Language) -> Option<&TextObjectQuery> {
416 self.language(lang).textobject_query(self)
417 }
418
419 pub fn tag_query(&self, lang: Language) -> Option<&TagQuery> {
420 self.language(lang).tag_query(self)
421 }
422
423 fn rainbow_query(&self, lang: Language) -> Option<&RainbowQuery> {
424 self.language(lang).rainbow_query(self)
425 }
426
427 pub fn language_server_configs(&self) -> &HashMap<String, LanguageServerConfiguration> {
428 &self.language_server_configs
429 }
430
431 pub fn scopes(&self) -> Guard<Arc<Vec<String>>> {
432 self.scopes.load()
433 }
434
435 pub fn set_scopes(&self, scopes: Vec<String>) {
436 self.scopes.store(Arc::new(scopes));
437
438 // Reconfigure existing grammars
439 for data in &self.languages {
440 data.reconfigure(&self.scopes());
441 }
442 }
443 }
444
445 impl LanguageLoader for Loader {
446 fn language_for_marker(&self, marker: InjectionLanguageMarker) -> Option<Language> {
447 match marker {
448 InjectionLanguageMarker::Name(name) => self.language_for_name(name),
449 InjectionLanguageMarker::Match(text) => self.language_for_match(text),
450 InjectionLanguageMarker::Filename(text) => {
451 let path: Cow<str> = text.into();
452 self.language_for_filename(Path::new(path.as_ref()))
453 }
454 InjectionLanguageMarker::Shebang(text) => self.language_for_shebang_marker(text),
455 }
456 }
457
458 fn get_config(&self, lang: Language) -> Option<&SyntaxConfig> {
459 self.languages[lang.idx()].syntax_config(self)
460 }
461 }
462
463 #[derive(Debug)]
464 struct FileTypeGlob {
465 glob: globset::Glob,
466 language: Language,
467 }
468
469 impl FileTypeGlob {
470 pub fn new(glob: globset::Glob, language: Language) -> Self {
471 Self { glob, language }
472 }
473 }
474
475 #[derive(Debug)]
476 struct FileTypeGlobMatcher {
477 matcher: globset::GlobSet,
478 file_types: Vec<FileTypeGlob>,
479 }
480
481 impl Default for FileTypeGlobMatcher {
482 fn default() -> Self {
483 Self {
484 matcher: globset::GlobSet::empty(),
485 file_types: Default::default(),
486 }
487 }
488 }
489
490 impl FileTypeGlobMatcher {
491 fn new(file_types: Vec<FileTypeGlob>) -> Result<Self, globset::Error> {
492 let mut builder = globset::GlobSetBuilder::new();
493 for file_type in &file_types {
494 builder.add(file_type.glob.clone());
495 }
496
497 Ok(Self {
498 matcher: builder.build()?,
499 file_types,
500 })
501 }
502
503 fn language_for_path(&self, path: &Path) -> Option<Language> {
504 self.matcher
505 .matches(path)
506 .iter()
507 .filter_map(|idx| self.file_types.get(*idx))
508 .max_by_key(|file_type| file_type.glob.glob().len())
509 .map(|file_type| file_type.language)
510 }
511 }
512
513 #[derive(Debug)]
514 pub struct Syntax {
515 inner: tree_house::Syntax,
516 }
517
518 const PARSE_TIMEOUT: Duration = Duration::from_millis(500); // half a second is pretty generous
519
520 impl Syntax {
521 pub fn new(source: RopeSlice, language: Language, loader: &Loader) -> Result<Self, Error> {
522 let inner = tree_house::Syntax::new(source, language, PARSE_TIMEOUT, loader)?;
523 Ok(Self { inner })
524 }
525
526 pub fn update(
527 &mut self,
528 old_source: RopeSlice,
529 source: RopeSlice,
530 changeset: &ChangeSet,
531 loader: &Loader,
532 ) -> Result<(), Error> {
533 let edits = generate_edits(old_source, changeset);
534 if edits.is_empty() {
535 Ok(())
536 } else {
537 self.inner.update(source, PARSE_TIMEOUT, &edits, loader)
538 }
539 }
540
541 pub fn layer(&self, layer: Layer) -> &tree_house::LayerData {
542 self.inner.layer(layer)
543 }
544
545 pub fn root_layer(&self) -> Layer {
546 self.inner.root()
547 }
548
549 /// Finds the smallest injection layer which fully includes the range `start..=end`.
550 ///
551 /// This is the same as using the last item in the `layers_for_byte_range` iterator.
552 pub fn layer_for_byte_range(&self, start: u32, end: u32) -> Layer {
553 self.inner.layer_for_byte_range(start, end)
554 }
555
556 /// Returns an iterator of layers which **fully include** the byte range `start..=end`.
557 ///
558 /// The iterator is non-empty and the root is always the first element. Other layers are
559 /// returned in decreasing order based on the size of each layer. I.e. the last element is
560 /// the smallest layer including the byte range.
561 pub fn layers_for_byte_range(
562 &self,
563 start: u32,
564 end: u32,
565 ) -> impl Iterator<Item = Layer> + use<'_> {
566 self.inner.layers_for_byte_range(start, end)
567 }
568
569 pub fn root_language(&self) -> Language {
570 self.layer(self.root_layer()).language
571 }
572
573 pub fn tree(&self) -> &Tree {
574 self.inner.tree()
575 }
576
577 pub fn tree_for_byte_range(&self, start: u32, end: u32) -> &Tree {
578 self.inner.tree_for_byte_range(start, end)
579 }
580
581 pub fn named_descendant_for_byte_range(&self, start: u32, end: u32) -> Option<Node<'_>> {
582 self.inner.named_descendant_for_byte_range(start, end)
583 }
584
585 pub fn descendant_for_byte_range(&self, start: u32, end: u32) -> Option<Node<'_>> {
586 self.inner.descendant_for_byte_range(start, end)
587 }
588
589 pub fn walk(&self) -> TreeCursor<'_> {
590 self.inner.walk()
591 }
592
593 pub fn highlighter<'a>(
594 &'a self,
595 source: RopeSlice<'a>,
596 loader: &'a Loader,
597 range: impl RangeBounds<u32>,
598 ) -> Highlighter<'a> {
599 Highlighter::new(&self.inner, source, loader, range)
600 }
601
602 pub fn query_iter<'a, QueryLoader, LayerState, Range>(
603 &'a self,
604 source: RopeSlice<'a>,
605 loader: QueryLoader,
606 range: Range,
607 ) -> QueryIter<'a, 'a, QueryLoader, LayerState>
608 where
609 QueryLoader: FnMut(Language) -> Option<&'a Query> + 'a,
610 LayerState: Default,
611 Range: RangeBounds<u32>,
612 {
613 QueryIter::new(&self.inner, source, loader, range)
614 }
615
616 pub fn tags<'a>(
617 &'a self,
618 source: RopeSlice<'a>,
619 loader: &'a Loader,
620 range: impl RangeBounds<u32>,
621 ) -> QueryMatchIter<'a, 'a, impl FnMut(Language) -> Option<&'a Query> + 'a, ()> {
622 QueryMatchIter::new(
623 &self.inner,
624 source,
625 |lang| loader.tag_query(lang).map(|q| &q.query),
626 range,
627 )
628 }
629
630 pub fn rainbow_highlights(
631 &self,
632 source: RopeSlice,
633 rainbow_length: usize,
634 loader: &Loader,
635 range: impl RangeBounds<u32>,
636 ) -> OverlayHighlights {
637 struct RainbowScope<'tree> {
638 end: u32,
639 node: Option<Node<'tree>>,
640 highlight: Highlight,
641 }
642
643 let mut scope_stack = Vec::<RainbowScope>::new();
644 let mut highlights = Vec::new();
645 let mut query_iter = self.query_iter::<_, (), _>(
646 source,
647 |lang| loader.rainbow_query(lang).map(|q| &q.query),
648 range,
649 );
650
651 while let Some(event) = query_iter.next() {
652 let QueryIterEvent::Match(mat) = event else {
653 continue;
654 };
655
656 let rainbow_query = loader
657 .rainbow_query(query_iter.current_language())
658 .expect("language must have a rainbow query to emit matches");
659
660 let byte_range = mat.node.byte_range();
661 // Pop any scopes that end before this capture begins.
662 while scope_stack
663 .last()
664 .is_some_and(|scope| byte_range.start >= scope.end)
665 {
666 scope_stack.pop();
667 }
668
669 let capture = Some(mat.capture);
670 if capture == rainbow_query.scope_capture {
671 scope_stack.push(RainbowScope {
672 end: byte_range.end,
673 node: if rainbow_query
674 .include_children_patterns
675 .contains(&mat.pattern)
676 {
677 None
678 } else {
679 Some(mat.node.clone())
680 },
681 highlight: Highlight::new((scope_stack.len() % rainbow_length) as u32),
682 });
683 } else if capture == rainbow_query.bracket_capture {
684 if let Some(scope) = scope_stack.last() {
685 if !scope
686 .node
687 .as_ref()
688 .is_some_and(|node| mat.node.parent().as_ref() != Some(node))
689 {
690 let start = source
691 .byte_to_char(source.floor_char_boundary(byte_range.start as usize));
692 let end =
693 source.byte_to_char(source.ceil_char_boundary(byte_range.end as usize));
694 highlights.push((scope.highlight, start..end));
695 }
696 }
697 }
698 }
699
700 OverlayHighlights::Heterogenous { highlights }
701 }
702 }
703
704 pub type Highlighter<'a> = highlighter::Highlighter<'a, 'a, Loader>;
705
706 fn generate_edits(old_text: RopeSlice, changeset: &ChangeSet) -> Vec<InputEdit> {
707 use crate::Operation::*;
708 use tree_sitter::Point;
709
710 let mut old_pos = 0;
711
712 let mut edits = Vec::new();
713
714 if changeset.changes.is_empty() {
715 return edits;
716 }
717
718 let mut iter = changeset.changes.iter().peekable();
719
720 // TODO; this is a lot easier with Change instead of Operation.
721 while let Some(change) = iter.next() {
722 let len = match change {
723 Delete(i) | Retain(i) => *i,
724 Insert(_) => 0,
725 };
726 let mut old_end = old_pos + len;
727
728 match change {
729 Retain(_) => {}
730 Delete(_) => {
731 let start_byte = old_text.char_to_byte(old_pos) as u32;
732 let old_end_byte = old_text.char_to_byte(old_end) as u32;
733
734 // deletion
735 edits.push(InputEdit {
736 start_byte, // old_pos to byte
737 old_end_byte, // old_end to byte
738 new_end_byte: start_byte, // old_pos to byte
739 start_point: Point::ZERO,
740 old_end_point: Point::ZERO,
741 new_end_point: Point::ZERO,
742 });
743 }
744 Insert(s) => {
745 let start_byte = old_text.char_to_byte(old_pos) as u32;
746
747 // a subsequent delete means a replace, consume it
748 if let Some(Delete(len)) = iter.peek() {
749 old_end = old_pos + len;
750 let old_end_byte = old_text.char_to_byte(old_end) as u32;
751
752 iter.next();
753
754 // replacement
755 edits.push(InputEdit {
756 start_byte, // old_pos to byte
757 old_end_byte, // old_end to byte
758 new_end_byte: start_byte + s.len() as u32, // old_pos to byte + s.len()
759 start_point: Point::ZERO,
760 old_end_point: Point::ZERO,
761 new_end_point: Point::ZERO,
762 });
763 } else {
764 // insert
765 edits.push(InputEdit {
766 start_byte, // old_pos to byte
767 old_end_byte: start_byte, // same
768 new_end_byte: start_byte + s.len() as u32, // old_pos + s.len()
769 start_point: Point::ZERO,
770 old_end_point: Point::ZERO,
771 new_end_point: Point::ZERO,
772 });
773 }
774 }
775 }
776 old_pos = old_end;
777 }
778 edits
779 }
780
781 /// A set of "overlay" highlights and ranges they apply to.
782 ///
783 /// As overlays, the styles for the given `Highlight`s are merged on top of the syntax highlights.
784 #[derive(Debug)]
785 pub enum OverlayHighlights {
786 /// All highlights use a single `Highlight`.
787 ///
788 /// Note that, currently, all ranges are assumed to be non-overlapping. This could change in
789 /// the future though.
790 Homogeneous {
791 highlight: Highlight,
792 ranges: Vec<ops::Range<usize>>,
793 },
794 /// A collection of different highlights for given ranges.
795 ///
796 /// Note that the ranges **must be non-overlapping**.
797 Heterogenous {
798 highlights: Vec<(Highlight, ops::Range<usize>)>,
799 },
800 }
801
802 impl OverlayHighlights {
803 pub fn single(highlight: Highlight, range: ops::Range<usize>) -> Self {
804 Self::Homogeneous {
805 highlight,
806 ranges: vec![range],
807 }
808 }
809
810 fn is_empty(&self) -> bool {
811 match self {
812 Self::Homogeneous { ranges, .. } => ranges.is_empty(),
813 Self::Heterogenous { highlights } => highlights.is_empty(),
814 }
815 }
816 }
817
818 #[derive(Debug)]
819 struct Overlay {
820 highlights: OverlayHighlights,
821 /// The position of the highlighter into the Vec of ranges of the overlays.
822 ///
823 /// Used by the `OverlayHighlighter`.
824 idx: usize,
825 /// The currently active highlight (and the ending character index) for this overlay.
826 ///
827 /// Used by the `OverlayHighlighter`.
828 active_highlight: Option<(Highlight, usize)>,
829 }
830
831 impl Overlay {
832 fn new(highlights: OverlayHighlights) -> Option<Self> {
833 (!highlights.is_empty()).then_some(Self {
834 highlights,
835 idx: 0,
836 active_highlight: None,
837 })
838 }
839
840 fn current(&self) -> Option<(Highlight, ops::Range<usize>)> {
841 match &self.highlights {
842 OverlayHighlights::Homogeneous { highlight, ranges } => ranges
843 .get(self.idx)
844 .map(|range| (*highlight, range.clone())),
845 OverlayHighlights::Heterogenous { highlights } => highlights.get(self.idx).cloned(),
846 }
847 }
848
849 fn start(&self) -> Option<usize> {
850 match &self.highlights {
851 OverlayHighlights::Homogeneous { ranges, .. } => {
852 ranges.get(self.idx).map(|range| range.start)
853 }
854 OverlayHighlights::Heterogenous { highlights } => highlights
855 .get(self.idx)
856 .map(|(_highlight, range)| range.start),
857 }
858 }
859 }
860
861 /// A collection of highlights to apply when rendering which merge on top of syntax highlights.
862 #[derive(Debug)]
863 pub struct OverlayHighlighter {
864 overlays: Vec<Overlay>,
865 next_highlight_start: usize,
866 next_highlight_end: usize,
867 }
868
869 impl OverlayHighlighter {
870 pub fn new(overlays: impl IntoIterator<Item = OverlayHighlights>) -> Self {
871 let overlays: Vec<_> = overlays.into_iter().filter_map(Overlay::new).collect();
872 let next_highlight_start = overlays
873 .iter()
874 .filter_map(|overlay| overlay.start())
875 .min()
876 .unwrap_or(usize::MAX);
877
878 Self {
879 overlays,
880 next_highlight_start,
881 next_highlight_end: usize::MAX,
882 }
883 }
884
885 /// The current position in the overlay highlights.
886 ///
887 /// This method is meant to be used when treating this type as a cursor over the overlay
888 /// highlights.
889 ///
890 /// `usize::MAX` is returned when there are no more overlay highlights.
891 pub fn next_event_offset(&self) -> usize {
892 self.next_highlight_start.min(self.next_highlight_end)
893 }
894
895 pub fn advance(&mut self) -> (HighlightEvent, impl Iterator<Item = Highlight> + '_) {
896 let mut refresh = false;
897 let prev_stack_size = self
898 .overlays
899 .iter()
900 .filter(|overlay| overlay.active_highlight.is_some())
901 .count();
902 let pos = self.next_event_offset();
903
904 if self.next_highlight_end == pos {
905 for overlay in self.overlays.iter_mut() {
906 if overlay
907 .active_highlight
908 .is_some_and(|(_highlight, end)| end == pos)
909 {
910 overlay.active_highlight.take();
911 }
912 }
913
914 refresh = true;
915 }
916
917 while self.next_highlight_start == pos {
918 let mut activated_idx = usize::MAX;
919 for (idx, overlay) in self.overlays.iter_mut().enumerate() {
920 let Some((highlight, range)) = overlay.current() else {
921 continue;
922 };
923 if range.start != self.next_highlight_start {
924 continue;
925 }
926
927 // If this overlay has a highlight at this start index, set its active highlight
928 // and increment the cursor position within the overlay.
929 overlay.active_highlight = Some((highlight, range.end));
930 overlay.idx += 1;
931
932 activated_idx = activated_idx.min(idx);
933 }
934
935 // If `self.next_highlight_start == pos` that means that some overlay was ready to
936 // emit a highlight, so `activated_idx` must have been set to an existing index.
937 assert!(
938 (0..self.overlays.len()).contains(&activated_idx),
939 "expected an overlay to highlight (at pos {pos}, there are {} overlays)",
940 self.overlays.len()
941 );
942
943 // If any overlays are active after the (lowest) one which was just activated, the
944 // highlights need to be refreshed.
945 refresh |= self.overlays[activated_idx..]
946 .iter()
947 .any(|overlay| overlay.active_highlight.is_some());
948
949 self.next_highlight_start = self
950 .overlays
951 .iter()
952 .filter_map(|overlay| overlay.start())
953 .min()
954 .unwrap_or(usize::MAX);
955 }
956
957 self.next_highlight_end = self
958 .overlays
959 .iter()
960 .filter_map(|overlay| Some(overlay.active_highlight?.1))
961 .min()
962 .unwrap_or(usize::MAX);
963
964 let (event, start) = if refresh {
965 (HighlightEvent::Refresh, 0)
966 } else {
967 (HighlightEvent::Push, prev_stack_size)
968 };
969
970 (
971 event,
972 self.overlays
973 .iter()
974 .flat_map(|overlay| overlay.active_highlight)
975 .map(|(highlight, _end)| highlight)
976 .skip(start),
977 )
978 }
979 }
980
981 #[derive(Debug)]
982 pub enum CapturedNode<'a> {
983 Single(Node<'a>),
984 /// Guaranteed to be not empty
985 Grouped(Vec<Node<'a>>),
986 }
987
988 impl CapturedNode<'_> {
989 pub fn start_byte(&self) -> usize {
990 match self {
991 Self::Single(n) => n.start_byte() as usize,
992 Self::Grouped(ns) => ns[0].start_byte() as usize,
993 }
994 }
995
996 pub fn end_byte(&self) -> usize {
997 match self {
998 Self::Single(n) => n.end_byte() as usize,
999 Self::Grouped(ns) => ns.last().unwrap().end_byte() as usize,
1000 }
1001 }
1002
1003 pub fn byte_range(&self) -> ops::Range<usize> {
1004 self.start_byte()..self.end_byte()
1005 }
1006 }
1007
1008 #[derive(Debug)]
1009 pub struct TextObjectQuery {
1010 query: Query,
1011 }
1012
1013 impl TextObjectQuery {
1014 pub fn new(query: Query) -> Self {
1015 Self { query }
1016 }
1017
1018 /// Run the query on the given node and return sub nodes which match given
1019 /// capture ("function.inside", "class.around", etc).
1020 ///
1021 /// Captures may contain multiple nodes by using quantifiers (+, *, etc),
1022 /// and support for this is partial and could use improvement.
1023 ///
1024 /// ```query
1025 /// (comment)+ @capture
1026 ///
1027 /// ; OR
1028 /// (
1029 /// (comment)*
1030 /// .
1031 /// (function)
1032 /// ) @capture
1033 /// ```
1034 pub fn capture_nodes<'a>(
1035 &'a self,
1036 capture_name: &str,
1037 node: &Node<'a>,
1038 slice: RopeSlice<'a>,
1039 ) -> Option<impl Iterator<Item = CapturedNode<'a>>> {
1040 self.capture_nodes_any(&[capture_name], node, slice)
1041 }
1042
1043 /// Find the first capture that exists out of all given `capture_names`
1044 /// and return sub nodes that match this capture.
1045 pub fn capture_nodes_any<'a>(
1046 &'a self,
1047 capture_names: &[&str],
1048 node: &Node<'a>,
1049 slice: RopeSlice<'a>,
1050 ) -> Option<impl Iterator<Item = CapturedNode<'a>>> {
1051 let capture = capture_names
1052 .iter()
1053 .find_map(|cap| self.query.get_capture(cap))?;
1054
1055 let mut cursor = InactiveQueryCursor::new(0..u32::MAX, TREE_SITTER_MATCH_LIMIT)
1056 .execute_query(&self.query, node, RopeInput::new(slice));
1057 let capture_node = iter::from_fn(move || {
1058 let mat = cursor.next_match()?;
1059 Some(mat.nodes_for_capture(capture).cloned().collect())
1060 })
1061 .filter_map(move |nodes: Vec<_>| {
1062 if nodes.len() > 1 {
1063 Some(CapturedNode::Grouped(nodes))
1064 } else {
1065 nodes.into_iter().map(CapturedNode::Single).next()
1066 }
1067 });
1068 Some(capture_node)
1069 }
1070 }
1071
1072 #[derive(Debug)]
1073 pub struct TagQuery {
1074 pub query: Query,
1075 }
1076
1077 pub fn pretty_print_tree<W: fmt::Write>(fmt: &mut W, node: Node) -> fmt::Result {
1078 if node.child_count() == 0 {
1079 if node_is_visible(&node) {
1080 write!(fmt, "({})", node.kind())
1081 } else {
1082 write!(fmt, "\"{}\"", format_anonymous_node_kind(node.kind()))
1083 }
1084 } else {
1085 pretty_print_tree_impl(fmt, &mut node.walk(), 0)
1086 }
1087 }
1088
1089 fn node_is_visible(node: &Node) -> bool {
1090 node.is_named() && node.grammar().node_kind_is_visible(node.kind_id())
1091 }
1092
1093 fn format_anonymous_node_kind(kind: &str) -> Cow<'_, str> {
1094 if kind.contains('"') || kind.contains('\\') {
1095 Cow::Owned(kind.replace('\\', "\\\\").replace('"', "\\\""))
1096 } else {
1097 Cow::Borrowed(kind)
1098 }
1099 }
1100
1101 fn pretty_print_tree_impl<W: fmt::Write>(
1102 fmt: &mut W,
1103 cursor: &mut tree_sitter::TreeCursor,
1104 depth: usize,
1105 ) -> fmt::Result {
1106 let node = cursor.node();
1107 let visible = node_is_visible(&node);
1108
1109 if visible {
1110 let indentation_columns = depth * 2;
1111 write!(fmt, "{:indentation_columns$}", "")?;
1112
1113 if let Some(field_name) = cursor.field_name() {
1114 write!(fmt, "{}: ", field_name)?;
1115 }
1116
1117 write!(fmt, "({}", node.kind())?;
1118 } else {
1119 write!(fmt, " \"{}\"", format_anonymous_node_kind(node.kind()))?;
1120 }
1121
1122 // Handle children.
1123 if cursor.goto_first_child() {
1124 loop {
1125 if node_is_visible(&cursor.node()) {
1126 fmt.write_char('\n')?;
1127 }
1128
1129 pretty_print_tree_impl(fmt, cursor, depth + 1)?;
1130
1131 if !cursor.goto_next_sibling() {
1132 break;
1133 }
1134 }
1135
1136 let moved = cursor.goto_parent();
1137 // The parent of the first child must exist, and must be `node`.
1138 debug_assert!(moved);
1139 debug_assert!(cursor.node() == node);
1140 }
1141
1142 if visible {
1143 fmt.write_char(')')?;
1144 }
1145
1146 Ok(())
1147 }
1148
1149 /// Finds the child of `node` which contains the given byte range.
1150 pub fn child_for_byte_range<'a>(node: &Node<'a>, range: ops::Range<u32>) -> Option<Node<'a>> {
1151 for child in node.children() {
1152 let child_range = child.byte_range();
1153
1154 if range.start >= child_range.start && range.end <= child_range.end {
1155 return Some(child);
1156 }
1157 }
1158
1159 None
1160 }
1161
1162 #[derive(Debug)]
1163 pub struct RainbowQuery {
1164 query: Query,
1165 include_children_patterns: HashSet<Pattern>,
1166 scope_capture: Option<Capture>,
1167 bracket_capture: Option<Capture>,
1168 }
1169
1170 impl RainbowQuery {
1171 fn new(grammar: Grammar, source: &str) -> Result<Self, tree_sitter::query::ParseError> {
1172 let mut include_children_patterns = HashSet::default();
1173
1174 let query = Query::new(grammar, source, |pattern, predicate| match predicate {
1175 UserPredicate::SetProperty {
1176 key: "rainbow.include-children",
1177 val,
1178 } => {
1179 if val.is_some() {
1180 return Err(
1181 "property 'rainbow.include-children' does not take an argument".into(),
1182 );
1183 }
1184 include_children_patterns.insert(pattern);
1185 Ok(())
1186 }
1187 _ => Err(InvalidPredicateError::unknown(predicate)),
1188 })?;
1189
1190 Ok(Self {
1191 include_children_patterns,
1192 scope_capture: query.get_capture("rainbow.scope"),
1193 bracket_capture: query.get_capture("rainbow.bracket"),
1194 query,
1195 })
1196 }
1197 }
1198
1199 #[cfg(test)]
1200 mod test {
1201 use once_cell::sync::Lazy;
1202
1203 use super::*;
1204 use crate::{Rope, Transaction};
1205
1206 static LOADER: Lazy<Loader> = Lazy::new(crate::config::default_lang_loader);
1207
1208 #[test]
1209 fn test_textobject_queries() {
1210 let query_str = r#"
1211 (line_comment)+ @quantified_nodes
1212 ((line_comment)+) @quantified_nodes_grouped
1213 ((line_comment) (line_comment)) @multiple_nodes_grouped
1214 "#;
1215 let source = Rope::from_str(
1216 r#"
1217 /// a comment on
1218 /// multiple lines
1219 "#,
1220 );
1221
1222 let language = LOADER.language_for_name("rust").unwrap();
1223 let grammar = LOADER.get_config(language).unwrap().grammar;
1224 let query = Query::new(grammar, query_str, |_, _| Ok(())).unwrap();
1225 let textobject = TextObjectQuery::new(query);
1226 let syntax = Syntax::new(source.slice(..), language, &LOADER).unwrap();
1227
1228 let root = syntax.tree().root_node();
1229 let test = |capture, range| {
1230 let matches: Vec<_> = textobject
1231 .capture_nodes(capture, &root, source.slice(..))
1232 .unwrap()
1233 .collect();
1234
1235 assert_eq!(
1236 matches[0].byte_range(),
1237 range,
1238 "@{} expected {:?}",
1239 capture,
1240 range
1241 )
1242 };
1243
1244 test("quantified_nodes", 1..37);
1245 test("quantified_nodes_grouped", 1..37);
1246 // TODO: the query for this works instead as
1247 // ```
1248 // ((line_comment) @capture (line_comment) @capture)
1249 // ```
1250 // The query used in this test case only captures the first line_comment node.
1251 // Determine if this behavior is intentional in tree-sitter.
1252 // test("multiple_nodes_grouped", 1..37);
1253 }
1254
1255 #[test]
1256 fn test_input_edits() {
1257 use tree_sitter::{InputEdit, Point};
1258
1259 let doc = Rope::from("hello world!\ntest 123");
1260 let transaction = Transaction::change(
1261 &doc,
1262 vec![(6, 11, Some("test".into())), (12, 17, None)].into_iter(),
1263 );
1264 let edits = generate_edits(doc.slice(..), transaction.changes());
1265 // transaction.apply(&mut state);
1266
1267 assert_eq!(
1268 edits,
1269 &[
1270 InputEdit {
1271 start_byte: 6,
1272 old_end_byte: 11,
1273 new_end_byte: 10,
1274 start_point: Point::ZERO,
1275 old_end_point: Point::ZERO,
1276 new_end_point: Point::ZERO
1277 },
1278 InputEdit {
1279 start_byte: 12,
1280 old_end_byte: 17,
1281 new_end_byte: 12,
1282 start_point: Point::ZERO,
1283 old_end_point: Point::ZERO,
1284 new_end_point: Point::ZERO
1285 }
1286 ]
1287 );
1288
1289 // Testing with the official example from tree-sitter
1290 let mut doc = Rope::from("fn test() {}");
1291 let transaction =
1292 Transaction::change(&doc, vec![(8, 8, Some("a: u32".into()))].into_iter());
1293 let edits = generate_edits(doc.slice(..), transaction.changes());
1294 transaction.apply(&mut doc);
1295
1296 assert_eq!(doc, "fn test(a: u32) {}");
1297 assert_eq!(
1298 edits,
1299 &[InputEdit {
1300 start_byte: 8,
1301 old_end_byte: 8,
1302 new_end_byte: 14,
1303 start_point: Point::ZERO,
1304 old_end_point: Point::ZERO,
1305 new_end_point: Point::ZERO
1306 }]
1307 );
1308 }
1309
1310 #[track_caller]
1311 fn assert_pretty_print(
1312 language_name: &str,
1313 source: &str,
1314 expected: &str,
1315 start: usize,
1316 end: usize,
1317 ) {
1318 let source = Rope::from_str(source);
1319 let language = LOADER.language_for_name(language_name).unwrap();
1320 let syntax = Syntax::new(source.slice(..), language, &LOADER).unwrap();
1321
1322 let root = syntax
1323 .tree()
1324 .root_node()
1325 .descendant_for_byte_range(start as u32, end as u32)
1326 .unwrap();
1327
1328 let mut output = String::new();
1329 pretty_print_tree(&mut output, root).unwrap();
1330
1331 assert_eq!(expected, output);
1332 }
1333
1334 #[test]
1335 fn test_pretty_print() {
1336 let source = r#"// Hello"#;
1337 assert_pretty_print("rust", source, "(line_comment \"//\")", 0, source.len());
1338
1339 // A large tree should be indented with fields:
1340 let source = r#"fn main() {
1341 println!("Hello, World!");
1342 }"#;
1343 assert_pretty_print(
1344 "rust",
1345 source,
1346 concat!(
1347 "(function_item \"fn\"\n",
1348 " name: (identifier)\n",
1349 " parameters: (parameters \"(\" \")\")\n",
1350 " body: (block \"{\"\n",
1351 " (expression_statement\n",
1352 " (macro_invocation\n",
1353 " macro: (identifier) \"!\"\n",
1354 " (token_tree \"(\"\n",
1355 " (string_literal \"\\\"\"\n",
1356 " (string_content) \"\\\"\") \")\")) \";\") \"}\"))",
1357 ),
1358 0,
1359 source.len(),
1360 );
1361
1362 // Selecting a token should print just that token:
1363 let source = r#"fn main() {}"#;
1364 assert_pretty_print("rust", source, r#""fn""#, 0, 1);
1365
1366 // Error nodes are printed as errors:
1367 let source = r#"}{"#;
1368 assert_pretty_print("rust", source, "(ERROR \"}\" \"{\")", 0, source.len());
1369
1370 // Fields broken under unnamed nodes are determined correctly.
1371 // In the following source, `object` belongs to the `singleton_method`
1372 // rule but `name` and `body` belong to an unnamed helper `_method_rest`.
1373 // This can cause a bug with a pretty-printing implementation that
1374 // uses `Node::field_name_for_child` to determine field names but is
1375 // fixed when using `tree_sitter::TreeCursor::field_name`.
1376 let source = "def self.method_name
1377 true
1378 end";
1379 assert_pretty_print(
1380 "ruby",
1381 source,
1382 concat!(
1383 "(singleton_method \"def\"\n",
1384 " object: (self) \".\"\n",
1385 " name: (identifier)\n",
1386 " body: (body_statement\n",
1387 " (true)) \"end\")"
1388 ),
1389 0,
1390 source.len(),
1391 );
1392 }
1393 }