1mod buffer;
2mod diagnostic_set;
3mod highlight_map;
4mod outline;
5pub mod proto;
6mod syntax_map;
7
8#[cfg(test)]
9mod buffer_tests;
10
11use anyhow::{anyhow, Context, Result};
12use async_trait::async_trait;
13use client::http::HttpClient;
14use collections::HashMap;
15use futures::{
16 future::{BoxFuture, Shared},
17 FutureExt, TryFutureExt,
18};
19use gpui::{MutableAppContext, Task};
20use highlight_map::HighlightMap;
21use lazy_static::lazy_static;
22use parking_lot::{Mutex, RwLock};
23use postage::watch;
24use regex::Regex;
25use serde::{de, Deserialize, Deserializer};
26use serde_json::Value;
27use std::{
28 any::Any,
29 cell::RefCell,
30 fmt::Debug,
31 hash::Hash,
32 mem,
33 ops::Range,
34 path::{Path, PathBuf},
35 str,
36 sync::{
37 atomic::{AtomicUsize, Ordering::SeqCst},
38 Arc,
39 },
40};
41use syntax_map::SyntaxSnapshot;
42use theme::{SyntaxTheme, Theme};
43use tree_sitter::{self, Query};
44use unicase::UniCase;
45use util::ResultExt;
46
47#[cfg(any(test, feature = "test-support"))]
48use futures::channel::mpsc;
49
50pub use buffer::Operation;
51pub use buffer::*;
52pub use diagnostic_set::DiagnosticEntry;
53pub use outline::{Outline, OutlineItem};
54pub use tree_sitter::{Parser, Tree};
55
56thread_local! {
57 static PARSER: RefCell<Parser> = RefCell::new(Parser::new());
58}
59
60lazy_static! {
61 pub static ref NEXT_GRAMMAR_ID: AtomicUsize = Default::default();
62 pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(
63 LanguageConfig {
64 name: "Plain Text".into(),
65 ..Default::default()
66 },
67 None,
68 ));
69}
70
71pub trait ToLspPosition {
72 fn to_lsp_position(self) -> lsp::Position;
73}
74
75#[derive(Clone, Debug, PartialEq, Eq, Hash)]
76pub struct LanguageServerName(pub Arc<str>);
77
78/// Represents a Language Server, with certain cached sync properties.
79/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
80/// once at startup, and caches the results.
81pub struct CachedLspAdapter {
82 pub name: LanguageServerName,
83 pub server_args: Vec<String>,
84 pub initialization_options: Option<Value>,
85 pub disk_based_diagnostic_sources: Vec<String>,
86 pub disk_based_diagnostics_progress_token: Option<String>,
87 pub language_ids: HashMap<String, String>,
88 pub adapter: Box<dyn LspAdapter>,
89}
90
91impl CachedLspAdapter {
92 pub async fn new<T: LspAdapter>(adapter: T) -> Arc<Self> {
93 let adapter = Box::new(adapter);
94 let name = adapter.name().await;
95 let server_args = adapter.server_args().await;
96 let initialization_options = adapter.initialization_options().await;
97 let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources().await;
98 let disk_based_diagnostics_progress_token =
99 adapter.disk_based_diagnostics_progress_token().await;
100 let language_ids = adapter.language_ids().await;
101
102 Arc::new(CachedLspAdapter {
103 name,
104 server_args,
105 initialization_options,
106 disk_based_diagnostic_sources,
107 disk_based_diagnostics_progress_token,
108 language_ids,
109 adapter,
110 })
111 }
112
113 pub async fn fetch_latest_server_version(
114 &self,
115 http: Arc<dyn HttpClient>,
116 ) -> Result<Box<dyn 'static + Send + Any>> {
117 self.adapter.fetch_latest_server_version(http).await
118 }
119
120 pub async fn fetch_server_binary(
121 &self,
122 version: Box<dyn 'static + Send + Any>,
123 http: Arc<dyn HttpClient>,
124 container_dir: PathBuf,
125 ) -> Result<PathBuf> {
126 self.adapter
127 .fetch_server_binary(version, http, container_dir)
128 .await
129 }
130
131 pub async fn cached_server_binary(&self, container_dir: PathBuf) -> Option<PathBuf> {
132 self.adapter.cached_server_binary(container_dir).await
133 }
134
135 pub async fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
136 self.adapter.process_diagnostics(params).await
137 }
138
139 pub async fn process_completion(&self, completion_item: &mut lsp::CompletionItem) {
140 self.adapter.process_completion(completion_item).await
141 }
142
143 pub async fn label_for_completion(
144 &self,
145 completion_item: &lsp::CompletionItem,
146 language: &Arc<Language>,
147 ) -> Option<CodeLabel> {
148 self.adapter
149 .label_for_completion(completion_item, language)
150 .await
151 }
152
153 pub async fn label_for_symbol(
154 &self,
155 name: &str,
156 kind: lsp::SymbolKind,
157 language: &Arc<Language>,
158 ) -> Option<CodeLabel> {
159 self.adapter.label_for_symbol(name, kind, language).await
160 }
161}
162
163#[async_trait]
164pub trait LspAdapter: 'static + Send + Sync {
165 async fn name(&self) -> LanguageServerName;
166
167 async fn fetch_latest_server_version(
168 &self,
169 http: Arc<dyn HttpClient>,
170 ) -> Result<Box<dyn 'static + Send + Any>>;
171
172 async fn fetch_server_binary(
173 &self,
174 version: Box<dyn 'static + Send + Any>,
175 http: Arc<dyn HttpClient>,
176 container_dir: PathBuf,
177 ) -> Result<PathBuf>;
178
179 async fn cached_server_binary(&self, container_dir: PathBuf) -> Option<PathBuf>;
180
181 async fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
182
183 async fn process_completion(&self, _: &mut lsp::CompletionItem) {}
184
185 async fn label_for_completion(
186 &self,
187 _: &lsp::CompletionItem,
188 _: &Arc<Language>,
189 ) -> Option<CodeLabel> {
190 None
191 }
192
193 async fn label_for_symbol(
194 &self,
195 _: &str,
196 _: lsp::SymbolKind,
197 _: &Arc<Language>,
198 ) -> Option<CodeLabel> {
199 None
200 }
201
202 async fn server_args(&self) -> Vec<String> {
203 Vec::new()
204 }
205
206 async fn initialization_options(&self) -> Option<Value> {
207 None
208 }
209
210 async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
211 Default::default()
212 }
213
214 async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
215 None
216 }
217
218 async fn language_ids(&self) -> HashMap<String, String> {
219 Default::default()
220 }
221}
222
223#[derive(Clone, Debug, PartialEq, Eq)]
224pub struct CodeLabel {
225 pub text: String,
226 pub runs: Vec<(Range<usize>, HighlightId)>,
227 pub filter_range: Range<usize>,
228}
229
230#[derive(Deserialize)]
231pub struct LanguageConfig {
232 pub name: Arc<str>,
233 pub path_suffixes: Vec<String>,
234 pub brackets: Vec<BracketPair>,
235 #[serde(default = "auto_indent_using_last_non_empty_line_default")]
236 pub auto_indent_using_last_non_empty_line: bool,
237 #[serde(default, deserialize_with = "deserialize_regex")]
238 pub increase_indent_pattern: Option<Regex>,
239 #[serde(default, deserialize_with = "deserialize_regex")]
240 pub decrease_indent_pattern: Option<Regex>,
241 #[serde(default)]
242 pub autoclose_before: String,
243 #[serde(default)]
244 pub line_comment: Option<Arc<str>>,
245 #[serde(default)]
246 pub block_comment: Option<(Arc<str>, Arc<str>)>,
247 #[serde(default)]
248 pub overrides: HashMap<String, LanguageConfigOverride>,
249}
250
251#[derive(Clone)]
252pub struct LanguageScope {
253 language: Arc<Language>,
254 override_id: Option<u32>,
255}
256
257#[derive(Deserialize, Default, Debug)]
258pub struct LanguageConfigOverride {
259 #[serde(default)]
260 pub line_comment: Override<Arc<str>>,
261 #[serde(default)]
262 pub block_comment: Override<(Arc<str>, Arc<str>)>,
263 #[serde(default)]
264 pub brackets: Override<Vec<BracketPair>>,
265}
266
267#[derive(Deserialize, Debug)]
268#[serde(untagged)]
269pub enum Override<T> {
270 Remove { remove: bool },
271 Set(T),
272}
273
274impl<T> Default for Override<T> {
275 fn default() -> Self {
276 Override::Remove { remove: false }
277 }
278}
279
280impl<T> Override<T> {
281 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
282 match this {
283 Some(Self::Set(value)) => Some(value),
284 Some(Self::Remove { remove: true }) => None,
285 Some(Self::Remove { remove: false }) | None => original,
286 }
287 }
288}
289
290impl Default for LanguageConfig {
291 fn default() -> Self {
292 Self {
293 name: "".into(),
294 path_suffixes: Default::default(),
295 brackets: Default::default(),
296 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
297 increase_indent_pattern: Default::default(),
298 decrease_indent_pattern: Default::default(),
299 autoclose_before: Default::default(),
300 line_comment: Default::default(),
301 block_comment: Default::default(),
302 overrides: Default::default(),
303 }
304 }
305}
306
307fn auto_indent_using_last_non_empty_line_default() -> bool {
308 true
309}
310
311fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
312 let source = Option::<String>::deserialize(d)?;
313 if let Some(source) = source {
314 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
315 } else {
316 Ok(None)
317 }
318}
319
320#[cfg(any(test, feature = "test-support"))]
321pub struct FakeLspAdapter {
322 pub name: &'static str,
323 pub capabilities: lsp::ServerCapabilities,
324 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
325 pub disk_based_diagnostics_progress_token: Option<String>,
326 pub disk_based_diagnostics_sources: Vec<String>,
327}
328
329#[derive(Clone, Debug, Default, Deserialize)]
330pub struct BracketPair {
331 pub start: String,
332 pub end: String,
333 pub close: bool,
334 pub newline: bool,
335}
336
337pub struct Language {
338 pub(crate) config: LanguageConfig,
339 pub(crate) grammar: Option<Arc<Grammar>>,
340 pub(crate) adapter: Option<Arc<CachedLspAdapter>>,
341
342 #[cfg(any(test, feature = "test-support"))]
343 fake_adapter: Option<(
344 mpsc::UnboundedSender<lsp::FakeLanguageServer>,
345 Arc<FakeLspAdapter>,
346 )>,
347}
348
349pub struct Grammar {
350 id: usize,
351 pub(crate) ts_language: tree_sitter::Language,
352 pub(crate) error_query: Query,
353 pub(crate) highlights_query: Option<Query>,
354 pub(crate) brackets_config: Option<BracketConfig>,
355 pub(crate) indents_config: Option<IndentConfig>,
356 pub(crate) outline_config: Option<OutlineConfig>,
357 pub(crate) injection_config: Option<InjectionConfig>,
358 pub(crate) override_config: Option<OverrideConfig>,
359 pub(crate) highlight_map: Mutex<HighlightMap>,
360}
361
362struct IndentConfig {
363 query: Query,
364 indent_capture_ix: u32,
365 start_capture_ix: Option<u32>,
366 end_capture_ix: Option<u32>,
367 outdent_capture_ix: Option<u32>,
368}
369
370struct OutlineConfig {
371 query: Query,
372 item_capture_ix: u32,
373 name_capture_ix: u32,
374 context_capture_ix: Option<u32>,
375}
376
377struct InjectionConfig {
378 query: Query,
379 content_capture_ix: u32,
380 language_capture_ix: Option<u32>,
381 patterns: Vec<InjectionPatternConfig>,
382}
383
384struct OverrideConfig {
385 query: Query,
386 values: HashMap<u32, LanguageConfigOverride>,
387}
388
389#[derive(Default, Clone)]
390struct InjectionPatternConfig {
391 language: Option<Box<str>>,
392 combined: bool,
393}
394
395struct BracketConfig {
396 query: Query,
397 open_capture_ix: u32,
398 close_capture_ix: u32,
399}
400
401#[derive(Clone)]
402pub enum LanguageServerBinaryStatus {
403 CheckingForUpdate,
404 Downloading,
405 Downloaded,
406 Cached,
407 Failed { error: String },
408}
409
410pub struct LanguageRegistry {
411 languages: RwLock<Vec<Arc<Language>>>,
412 language_server_download_dir: Option<Arc<Path>>,
413 lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
414 lsp_binary_statuses_rx: async_broadcast::Receiver<(Arc<Language>, LanguageServerBinaryStatus)>,
415 login_shell_env_loaded: Shared<Task<()>>,
416 #[allow(clippy::type_complexity)]
417 lsp_binary_paths: Mutex<
418 HashMap<
419 LanguageServerName,
420 Shared<BoxFuture<'static, Result<PathBuf, Arc<anyhow::Error>>>>,
421 >,
422 >,
423 subscription: RwLock<(watch::Sender<()>, watch::Receiver<()>)>,
424 theme: RwLock<Option<Arc<Theme>>>,
425}
426
427impl LanguageRegistry {
428 pub fn new(login_shell_env_loaded: Task<()>) -> Self {
429 let (lsp_binary_statuses_tx, lsp_binary_statuses_rx) = async_broadcast::broadcast(16);
430 Self {
431 language_server_download_dir: None,
432 languages: Default::default(),
433 lsp_binary_statuses_tx,
434 lsp_binary_statuses_rx,
435 login_shell_env_loaded: login_shell_env_loaded.shared(),
436 lsp_binary_paths: Default::default(),
437 subscription: RwLock::new(watch::channel()),
438 theme: Default::default(),
439 }
440 }
441
442 #[cfg(any(test, feature = "test-support"))]
443 pub fn test() -> Self {
444 Self::new(Task::ready(()))
445 }
446
447 pub fn add(&self, language: Arc<Language>) {
448 if let Some(theme) = self.theme.read().clone() {
449 language.set_theme(&theme.editor.syntax);
450 }
451 self.languages.write().push(language);
452 *self.subscription.write().0.borrow_mut() = ();
453 }
454
455 pub fn subscribe(&self) -> watch::Receiver<()> {
456 self.subscription.read().1.clone()
457 }
458
459 pub fn set_theme(&self, theme: Arc<Theme>) {
460 *self.theme.write() = Some(theme.clone());
461 for language in self.languages.read().iter() {
462 language.set_theme(&theme.editor.syntax);
463 }
464 }
465
466 pub fn set_language_server_download_dir(&mut self, path: impl Into<Arc<Path>>) {
467 self.language_server_download_dir = Some(path.into());
468 }
469
470 pub fn language_for_name(&self, name: &str) -> Option<Arc<Language>> {
471 let name = UniCase::new(name);
472 self.languages
473 .read()
474 .iter()
475 .find(|language| UniCase::new(language.name()) == name)
476 .cloned()
477 }
478
479 pub fn language_for_extension(&self, extension: &str) -> Option<Arc<Language>> {
480 let extension = UniCase::new(extension);
481 self.languages
482 .read()
483 .iter()
484 .find(|language| {
485 language
486 .config
487 .path_suffixes
488 .iter()
489 .any(|suffix| UniCase::new(suffix) == extension)
490 })
491 .cloned()
492 }
493
494 pub fn to_vec(&self) -> Vec<Arc<Language>> {
495 self.languages.read().iter().cloned().collect()
496 }
497
498 pub fn language_names(&self) -> Vec<String> {
499 self.languages
500 .read()
501 .iter()
502 .map(|language| language.name().to_string())
503 .collect()
504 }
505
506 pub fn select_language(&self, path: impl AsRef<Path>) -> Option<Arc<Language>> {
507 let path = path.as_ref();
508 let filename = path.file_name().and_then(|name| name.to_str());
509 let extension = path.extension().and_then(|name| name.to_str());
510 let path_suffixes = [extension, filename];
511 self.languages
512 .read()
513 .iter()
514 .find(|language| {
515 language
516 .config
517 .path_suffixes
518 .iter()
519 .any(|suffix| path_suffixes.contains(&Some(suffix.as_str())))
520 })
521 .cloned()
522 }
523
524 pub fn start_language_server(
525 self: &Arc<Self>,
526 server_id: usize,
527 language: Arc<Language>,
528 root_path: Arc<Path>,
529 http_client: Arc<dyn HttpClient>,
530 cx: &mut MutableAppContext,
531 ) -> Option<Task<Result<lsp::LanguageServer>>> {
532 #[cfg(any(test, feature = "test-support"))]
533 if language.fake_adapter.is_some() {
534 let language = language;
535 return Some(cx.spawn(|cx| async move {
536 let (servers_tx, fake_adapter) = language.fake_adapter.as_ref().unwrap();
537 let (server, mut fake_server) = lsp::LanguageServer::fake(
538 fake_adapter.name.to_string(),
539 fake_adapter.capabilities.clone(),
540 cx.clone(),
541 );
542
543 if let Some(initializer) = &fake_adapter.initializer {
544 initializer(&mut fake_server);
545 }
546
547 let servers_tx = servers_tx.clone();
548 cx.background()
549 .spawn(async move {
550 if fake_server
551 .try_receive_notification::<lsp::notification::Initialized>()
552 .await
553 .is_some()
554 {
555 servers_tx.unbounded_send(fake_server).ok();
556 }
557 })
558 .detach();
559 Ok(server)
560 }));
561 }
562
563 let download_dir = self
564 .language_server_download_dir
565 .clone()
566 .ok_or_else(|| anyhow!("language server download directory has not been assigned"))
567 .log_err()?;
568
569 let this = self.clone();
570 let adapter = language.adapter.clone()?;
571 let lsp_binary_statuses = self.lsp_binary_statuses_tx.clone();
572 let login_shell_env_loaded = self.login_shell_env_loaded.clone();
573 Some(cx.spawn(|cx| async move {
574 login_shell_env_loaded.await;
575 let server_binary_path = this
576 .lsp_binary_paths
577 .lock()
578 .entry(adapter.name.clone())
579 .or_insert_with(|| {
580 get_server_binary_path(
581 adapter.clone(),
582 language.clone(),
583 http_client,
584 download_dir,
585 lsp_binary_statuses,
586 )
587 .map_err(Arc::new)
588 .boxed()
589 .shared()
590 })
591 .clone()
592 .map_err(|e| anyhow!(e));
593
594 let server_binary_path = server_binary_path.await?;
595 let server_args = &adapter.server_args;
596 let server = lsp::LanguageServer::new(
597 server_id,
598 &server_binary_path,
599 server_args,
600 &root_path,
601 cx,
602 )?;
603 Ok(server)
604 }))
605 }
606
607 pub fn language_server_binary_statuses(
608 &self,
609 ) -> async_broadcast::Receiver<(Arc<Language>, LanguageServerBinaryStatus)> {
610 self.lsp_binary_statuses_rx.clone()
611 }
612}
613
614#[cfg(any(test, feature = "test-support"))]
615impl Default for LanguageRegistry {
616 fn default() -> Self {
617 Self::test()
618 }
619}
620
621async fn get_server_binary_path(
622 adapter: Arc<CachedLspAdapter>,
623 language: Arc<Language>,
624 http_client: Arc<dyn HttpClient>,
625 download_dir: Arc<Path>,
626 statuses: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
627) -> Result<PathBuf> {
628 let container_dir = download_dir.join(adapter.name.0.as_ref());
629 if !container_dir.exists() {
630 smol::fs::create_dir_all(&container_dir)
631 .await
632 .context("failed to create container directory")?;
633 }
634
635 let path = fetch_latest_server_binary_path(
636 adapter.clone(),
637 language.clone(),
638 http_client,
639 &container_dir,
640 statuses.clone(),
641 )
642 .await;
643 if let Err(error) = path.as_ref() {
644 if let Some(cached_path) = adapter.cached_server_binary(container_dir).await {
645 statuses
646 .broadcast((language.clone(), LanguageServerBinaryStatus::Cached))
647 .await?;
648 return Ok(cached_path);
649 } else {
650 statuses
651 .broadcast((
652 language.clone(),
653 LanguageServerBinaryStatus::Failed {
654 error: format!("{:?}", error),
655 },
656 ))
657 .await?;
658 }
659 }
660 path
661}
662
663async fn fetch_latest_server_binary_path(
664 adapter: Arc<CachedLspAdapter>,
665 language: Arc<Language>,
666 http_client: Arc<dyn HttpClient>,
667 container_dir: &Path,
668 lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
669) -> Result<PathBuf> {
670 let container_dir: Arc<Path> = container_dir.into();
671 lsp_binary_statuses_tx
672 .broadcast((
673 language.clone(),
674 LanguageServerBinaryStatus::CheckingForUpdate,
675 ))
676 .await?;
677 let version_info = adapter
678 .fetch_latest_server_version(http_client.clone())
679 .await?;
680 lsp_binary_statuses_tx
681 .broadcast((language.clone(), LanguageServerBinaryStatus::Downloading))
682 .await?;
683 let path = adapter
684 .fetch_server_binary(version_info, http_client, container_dir.to_path_buf())
685 .await?;
686 lsp_binary_statuses_tx
687 .broadcast((language.clone(), LanguageServerBinaryStatus::Downloaded))
688 .await?;
689 Ok(path)
690}
691
692impl Language {
693 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
694 Self {
695 config,
696 grammar: ts_language.map(|ts_language| {
697 Arc::new(Grammar {
698 id: NEXT_GRAMMAR_ID.fetch_add(1, SeqCst),
699 highlights_query: None,
700 brackets_config: None,
701 outline_config: None,
702 indents_config: None,
703 injection_config: None,
704 override_config: None,
705 error_query: Query::new(ts_language, "(ERROR) @error").unwrap(),
706 ts_language,
707 highlight_map: Default::default(),
708 })
709 }),
710 adapter: None,
711
712 #[cfg(any(test, feature = "test-support"))]
713 fake_adapter: None,
714 }
715 }
716
717 pub fn lsp_adapter(&self) -> Option<Arc<CachedLspAdapter>> {
718 self.adapter.clone()
719 }
720
721 pub fn id(&self) -> Option<usize> {
722 self.grammar.as_ref().map(|g| g.id)
723 }
724
725 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
726 let grammar = self.grammar_mut();
727 grammar.highlights_query = Some(Query::new(grammar.ts_language, source)?);
728 Ok(self)
729 }
730
731 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
732 let grammar = self.grammar_mut();
733 let query = Query::new(grammar.ts_language, source)?;
734 let mut open_capture_ix = None;
735 let mut close_capture_ix = None;
736 get_capture_indices(
737 &query,
738 &mut [
739 ("open", &mut open_capture_ix),
740 ("close", &mut close_capture_ix),
741 ],
742 );
743 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
744 grammar.brackets_config = Some(BracketConfig {
745 query,
746 open_capture_ix,
747 close_capture_ix,
748 });
749 }
750 Ok(self)
751 }
752
753 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
754 let grammar = self.grammar_mut();
755 let query = Query::new(grammar.ts_language, source)?;
756 let mut indent_capture_ix = None;
757 let mut start_capture_ix = None;
758 let mut end_capture_ix = None;
759 let mut outdent_capture_ix = None;
760 get_capture_indices(
761 &query,
762 &mut [
763 ("indent", &mut indent_capture_ix),
764 ("start", &mut start_capture_ix),
765 ("end", &mut end_capture_ix),
766 ("outdent", &mut outdent_capture_ix),
767 ],
768 );
769 if let Some(indent_capture_ix) = indent_capture_ix {
770 grammar.indents_config = Some(IndentConfig {
771 query,
772 indent_capture_ix,
773 start_capture_ix,
774 end_capture_ix,
775 outdent_capture_ix,
776 });
777 }
778 Ok(self)
779 }
780
781 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
782 let grammar = self.grammar_mut();
783 let query = Query::new(grammar.ts_language, source)?;
784 let mut item_capture_ix = None;
785 let mut name_capture_ix = None;
786 let mut context_capture_ix = None;
787 get_capture_indices(
788 &query,
789 &mut [
790 ("item", &mut item_capture_ix),
791 ("name", &mut name_capture_ix),
792 ("context", &mut context_capture_ix),
793 ],
794 );
795 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
796 grammar.outline_config = Some(OutlineConfig {
797 query,
798 item_capture_ix,
799 name_capture_ix,
800 context_capture_ix,
801 });
802 }
803 Ok(self)
804 }
805
806 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
807 let grammar = self.grammar_mut();
808 let query = Query::new(grammar.ts_language, source)?;
809 let mut language_capture_ix = None;
810 let mut content_capture_ix = None;
811 get_capture_indices(
812 &query,
813 &mut [
814 ("language", &mut language_capture_ix),
815 ("content", &mut content_capture_ix),
816 ],
817 );
818 let patterns = (0..query.pattern_count())
819 .map(|ix| {
820 let mut config = InjectionPatternConfig::default();
821 for setting in query.property_settings(ix) {
822 match setting.key.as_ref() {
823 "language" => {
824 config.language = setting.value.clone();
825 }
826 "combined" => {
827 config.combined = true;
828 }
829 _ => {}
830 }
831 }
832 config
833 })
834 .collect();
835 if let Some(content_capture_ix) = content_capture_ix {
836 grammar.injection_config = Some(InjectionConfig {
837 query,
838 language_capture_ix,
839 content_capture_ix,
840 patterns,
841 });
842 }
843 Ok(self)
844 }
845
846 pub fn with_override_query(mut self, source: &str) -> Result<Self> {
847 let query = Query::new(self.grammar_mut().ts_language, source)?;
848
849 let mut values = HashMap::default();
850 for (ix, name) in query.capture_names().iter().enumerate() {
851 if !name.starts_with('_') {
852 let value = self.config.overrides.remove(name).ok_or_else(|| {
853 anyhow!(
854 "language {:?} has override in query but not in config: {name:?}",
855 self.config.name
856 )
857 })?;
858 values.insert(ix as u32, value);
859 }
860 }
861
862 if !self.config.overrides.is_empty() {
863 let keys = self.config.overrides.keys().collect::<Vec<_>>();
864 Err(anyhow!(
865 "language {:?} has overrides in config not in query: {keys:?}",
866 self.config.name
867 ))?;
868 }
869
870 self.grammar_mut().override_config = Some(OverrideConfig { query, values });
871 Ok(self)
872 }
873
874 fn grammar_mut(&mut self) -> &mut Grammar {
875 Arc::get_mut(self.grammar.as_mut().unwrap()).unwrap()
876 }
877
878 pub fn with_lsp_adapter(mut self, lsp_adapter: Arc<CachedLspAdapter>) -> Self {
879 self.adapter = Some(lsp_adapter);
880 self
881 }
882
883 #[cfg(any(test, feature = "test-support"))]
884 pub async fn set_fake_lsp_adapter(
885 &mut self,
886 fake_lsp_adapter: Arc<FakeLspAdapter>,
887 ) -> mpsc::UnboundedReceiver<lsp::FakeLanguageServer> {
888 let (servers_tx, servers_rx) = mpsc::unbounded();
889 self.fake_adapter = Some((servers_tx, fake_lsp_adapter.clone()));
890 let adapter = CachedLspAdapter::new(fake_lsp_adapter).await;
891 self.adapter = Some(adapter);
892 servers_rx
893 }
894
895 pub fn name(&self) -> Arc<str> {
896 self.config.name.clone()
897 }
898
899 pub async fn disk_based_diagnostic_sources(&self) -> &[String] {
900 match self.adapter.as_ref() {
901 Some(adapter) => &adapter.disk_based_diagnostic_sources,
902 None => &[],
903 }
904 }
905
906 pub async fn disk_based_diagnostics_progress_token(&self) -> Option<&str> {
907 if let Some(adapter) = self.adapter.as_ref() {
908 adapter.disk_based_diagnostics_progress_token.as_deref()
909 } else {
910 None
911 }
912 }
913
914 pub async fn process_diagnostics(&self, diagnostics: &mut lsp::PublishDiagnosticsParams) {
915 if let Some(processor) = self.adapter.as_ref() {
916 processor.process_diagnostics(diagnostics).await;
917 }
918 }
919
920 pub async fn process_completion(self: &Arc<Self>, completion: &mut lsp::CompletionItem) {
921 if let Some(adapter) = self.adapter.as_ref() {
922 adapter.process_completion(completion).await;
923 }
924 }
925
926 pub async fn label_for_completion(
927 self: &Arc<Self>,
928 completion: &lsp::CompletionItem,
929 ) -> Option<CodeLabel> {
930 self.adapter
931 .as_ref()?
932 .label_for_completion(completion, self)
933 .await
934 }
935
936 pub async fn label_for_symbol(
937 self: &Arc<Self>,
938 name: &str,
939 kind: lsp::SymbolKind,
940 ) -> Option<CodeLabel> {
941 self.adapter
942 .as_ref()?
943 .label_for_symbol(name, kind, self)
944 .await
945 }
946
947 pub fn highlight_text<'a>(
948 self: &'a Arc<Self>,
949 text: &'a Rope,
950 range: Range<usize>,
951 ) -> Vec<(Range<usize>, HighlightId)> {
952 let mut result = Vec::new();
953 if let Some(grammar) = &self.grammar {
954 let tree = grammar.parse_text(text, None);
955 let captures =
956 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
957 grammar.highlights_query.as_ref()
958 });
959 let highlight_maps = vec![grammar.highlight_map()];
960 let mut offset = 0;
961 for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
962 let end_offset = offset + chunk.text.len();
963 if let Some(highlight_id) = chunk.syntax_highlight_id {
964 if !highlight_id.is_default() {
965 result.push((offset..end_offset, highlight_id));
966 }
967 }
968 offset = end_offset;
969 }
970 }
971 result
972 }
973
974 pub fn path_suffixes(&self) -> &[String] {
975 &self.config.path_suffixes
976 }
977
978 pub fn should_autoclose_before(&self, c: char) -> bool {
979 c.is_whitespace() || self.config.autoclose_before.contains(c)
980 }
981
982 pub fn set_theme(&self, theme: &SyntaxTheme) {
983 if let Some(grammar) = self.grammar.as_ref() {
984 if let Some(highlights_query) = &grammar.highlights_query {
985 *grammar.highlight_map.lock() =
986 HighlightMap::new(highlights_query.capture_names(), theme);
987 }
988 }
989 }
990
991 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
992 self.grammar.as_ref()
993 }
994}
995
996impl LanguageScope {
997 pub fn line_comment_prefix(&self) -> Option<&Arc<str>> {
998 Override::as_option(
999 self.config_override().map(|o| &o.line_comment),
1000 self.language.config.line_comment.as_ref(),
1001 )
1002 }
1003
1004 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1005 Override::as_option(
1006 self.config_override().map(|o| &o.block_comment),
1007 self.language.config.block_comment.as_ref(),
1008 )
1009 .map(|e| (&e.0, &e.1))
1010 }
1011
1012 pub fn brackets(&self) -> &[BracketPair] {
1013 Override::as_option(
1014 self.config_override().map(|o| &o.brackets),
1015 Some(&self.language.config.brackets),
1016 )
1017 .map_or(&[], Vec::as_slice)
1018 }
1019
1020 pub fn should_autoclose_before(&self, c: char) -> bool {
1021 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1022 }
1023
1024 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1025 let id = self.override_id?;
1026 let grammar = self.language.grammar.as_ref()?;
1027 let override_config = grammar.override_config.as_ref()?;
1028 override_config.values.get(&id)
1029 }
1030}
1031
1032impl Hash for Language {
1033 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1034 self.id().hash(state)
1035 }
1036}
1037
1038impl PartialEq for Language {
1039 fn eq(&self, other: &Self) -> bool {
1040 self.id().eq(&other.id())
1041 }
1042}
1043
1044impl Eq for Language {}
1045
1046impl Debug for Language {
1047 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1048 f.debug_struct("Language")
1049 .field("name", &self.config.name)
1050 .finish()
1051 }
1052}
1053
1054impl Grammar {
1055 pub fn id(&self) -> usize {
1056 self.id
1057 }
1058
1059 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1060 PARSER.with(|parser| {
1061 let mut parser = parser.borrow_mut();
1062 parser
1063 .set_language(self.ts_language)
1064 .expect("incompatible grammar");
1065 let mut chunks = text.chunks_in_range(0..text.len());
1066 parser
1067 .parse_with(
1068 &mut move |offset, _| {
1069 chunks.seek(offset);
1070 chunks.next().unwrap_or("").as_bytes()
1071 },
1072 old_tree.as_ref(),
1073 )
1074 .unwrap()
1075 })
1076 }
1077
1078 pub fn highlight_map(&self) -> HighlightMap {
1079 self.highlight_map.lock().clone()
1080 }
1081
1082 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1083 let capture_id = self
1084 .highlights_query
1085 .as_ref()?
1086 .capture_index_for_name(name)?;
1087 Some(self.highlight_map.lock().get(capture_id))
1088 }
1089}
1090
1091impl CodeLabel {
1092 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1093 let mut result = Self {
1094 runs: Vec::new(),
1095 filter_range: 0..text.len(),
1096 text,
1097 };
1098 if let Some(filter_text) = filter_text {
1099 if let Some(ix) = result.text.find(filter_text) {
1100 result.filter_range = ix..ix + filter_text.len();
1101 }
1102 }
1103 result
1104 }
1105}
1106
1107#[cfg(any(test, feature = "test-support"))]
1108impl Default for FakeLspAdapter {
1109 fn default() -> Self {
1110 Self {
1111 name: "the-fake-language-server",
1112 capabilities: lsp::LanguageServer::full_capabilities(),
1113 initializer: None,
1114 disk_based_diagnostics_progress_token: None,
1115 disk_based_diagnostics_sources: Vec::new(),
1116 }
1117 }
1118}
1119
1120#[cfg(any(test, feature = "test-support"))]
1121#[async_trait]
1122impl LspAdapter for Arc<FakeLspAdapter> {
1123 async fn name(&self) -> LanguageServerName {
1124 LanguageServerName(self.name.into())
1125 }
1126
1127 async fn fetch_latest_server_version(
1128 &self,
1129 _: Arc<dyn HttpClient>,
1130 ) -> Result<Box<dyn 'static + Send + Any>> {
1131 unreachable!();
1132 }
1133
1134 async fn fetch_server_binary(
1135 &self,
1136 _: Box<dyn 'static + Send + Any>,
1137 _: Arc<dyn HttpClient>,
1138 _: PathBuf,
1139 ) -> Result<PathBuf> {
1140 unreachable!();
1141 }
1142
1143 async fn cached_server_binary(&self, _: PathBuf) -> Option<PathBuf> {
1144 unreachable!();
1145 }
1146
1147 async fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1148
1149 async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1150 self.disk_based_diagnostics_sources.clone()
1151 }
1152
1153 async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1154 self.disk_based_diagnostics_progress_token.clone()
1155 }
1156}
1157
1158fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1159 for (ix, name) in query.capture_names().iter().enumerate() {
1160 for (capture_name, index) in captures.iter_mut() {
1161 if capture_name == name {
1162 **index = Some(ix as u32);
1163 break;
1164 }
1165 }
1166 }
1167}
1168
1169pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1170 lsp::Position::new(point.row, point.column)
1171}
1172
1173pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1174 Unclipped(PointUtf16::new(point.line, point.character))
1175}
1176
1177pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1178 lsp::Range {
1179 start: point_to_lsp(range.start),
1180 end: point_to_lsp(range.end),
1181 }
1182}
1183
1184pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1185 let mut start = point_from_lsp(range.start);
1186 let mut end = point_from_lsp(range.end);
1187 if start > end {
1188 mem::swap(&mut start, &mut end);
1189 }
1190 start..end
1191}