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 to_vec(&self) -> Vec<Arc<Language>> {
480 self.languages.read().iter().cloned().collect()
481 }
482
483 pub fn language_names(&self) -> Vec<String> {
484 self.languages
485 .read()
486 .iter()
487 .map(|language| language.name().to_string())
488 .collect()
489 }
490
491 pub fn select_language(&self, path: impl AsRef<Path>) -> Option<Arc<Language>> {
492 let path = path.as_ref();
493 let filename = path.file_name().and_then(|name| name.to_str());
494 let extension = path.extension().and_then(|name| name.to_str());
495 let path_suffixes = [extension, filename];
496 self.languages
497 .read()
498 .iter()
499 .find(|language| {
500 language
501 .config
502 .path_suffixes
503 .iter()
504 .any(|suffix| path_suffixes.contains(&Some(suffix.as_str())))
505 })
506 .cloned()
507 }
508
509 pub fn start_language_server(
510 self: &Arc<Self>,
511 server_id: usize,
512 language: Arc<Language>,
513 root_path: Arc<Path>,
514 http_client: Arc<dyn HttpClient>,
515 cx: &mut MutableAppContext,
516 ) -> Option<Task<Result<lsp::LanguageServer>>> {
517 #[cfg(any(test, feature = "test-support"))]
518 if language.fake_adapter.is_some() {
519 let language = language;
520 return Some(cx.spawn(|cx| async move {
521 let (servers_tx, fake_adapter) = language.fake_adapter.as_ref().unwrap();
522 let (server, mut fake_server) = lsp::LanguageServer::fake(
523 fake_adapter.name.to_string(),
524 fake_adapter.capabilities.clone(),
525 cx.clone(),
526 );
527
528 if let Some(initializer) = &fake_adapter.initializer {
529 initializer(&mut fake_server);
530 }
531
532 let servers_tx = servers_tx.clone();
533 cx.background()
534 .spawn(async move {
535 if fake_server
536 .try_receive_notification::<lsp::notification::Initialized>()
537 .await
538 .is_some()
539 {
540 servers_tx.unbounded_send(fake_server).ok();
541 }
542 })
543 .detach();
544 Ok(server)
545 }));
546 }
547
548 let download_dir = self
549 .language_server_download_dir
550 .clone()
551 .ok_or_else(|| anyhow!("language server download directory has not been assigned"))
552 .log_err()?;
553
554 let this = self.clone();
555 let adapter = language.adapter.clone()?;
556 let lsp_binary_statuses = self.lsp_binary_statuses_tx.clone();
557 let login_shell_env_loaded = self.login_shell_env_loaded.clone();
558 Some(cx.spawn(|cx| async move {
559 login_shell_env_loaded.await;
560 let server_binary_path = this
561 .lsp_binary_paths
562 .lock()
563 .entry(adapter.name.clone())
564 .or_insert_with(|| {
565 get_server_binary_path(
566 adapter.clone(),
567 language.clone(),
568 http_client,
569 download_dir,
570 lsp_binary_statuses,
571 )
572 .map_err(Arc::new)
573 .boxed()
574 .shared()
575 })
576 .clone()
577 .map_err(|e| anyhow!(e));
578
579 let server_binary_path = server_binary_path.await?;
580 let server_args = &adapter.server_args;
581 let server = lsp::LanguageServer::new(
582 server_id,
583 &server_binary_path,
584 server_args,
585 &root_path,
586 cx,
587 )?;
588 Ok(server)
589 }))
590 }
591
592 pub fn language_server_binary_statuses(
593 &self,
594 ) -> async_broadcast::Receiver<(Arc<Language>, LanguageServerBinaryStatus)> {
595 self.lsp_binary_statuses_rx.clone()
596 }
597}
598
599#[cfg(any(test, feature = "test-support"))]
600impl Default for LanguageRegistry {
601 fn default() -> Self {
602 Self::test()
603 }
604}
605
606async fn get_server_binary_path(
607 adapter: Arc<CachedLspAdapter>,
608 language: Arc<Language>,
609 http_client: Arc<dyn HttpClient>,
610 download_dir: Arc<Path>,
611 statuses: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
612) -> Result<PathBuf> {
613 let container_dir = download_dir.join(adapter.name.0.as_ref());
614 if !container_dir.exists() {
615 smol::fs::create_dir_all(&container_dir)
616 .await
617 .context("failed to create container directory")?;
618 }
619
620 let path = fetch_latest_server_binary_path(
621 adapter.clone(),
622 language.clone(),
623 http_client,
624 &container_dir,
625 statuses.clone(),
626 )
627 .await;
628 if let Err(error) = path.as_ref() {
629 if let Some(cached_path) = adapter.cached_server_binary(container_dir).await {
630 statuses
631 .broadcast((language.clone(), LanguageServerBinaryStatus::Cached))
632 .await?;
633 return Ok(cached_path);
634 } else {
635 statuses
636 .broadcast((
637 language.clone(),
638 LanguageServerBinaryStatus::Failed {
639 error: format!("{:?}", error),
640 },
641 ))
642 .await?;
643 }
644 }
645 path
646}
647
648async fn fetch_latest_server_binary_path(
649 adapter: Arc<CachedLspAdapter>,
650 language: Arc<Language>,
651 http_client: Arc<dyn HttpClient>,
652 container_dir: &Path,
653 lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
654) -> Result<PathBuf> {
655 let container_dir: Arc<Path> = container_dir.into();
656 lsp_binary_statuses_tx
657 .broadcast((
658 language.clone(),
659 LanguageServerBinaryStatus::CheckingForUpdate,
660 ))
661 .await?;
662 let version_info = adapter
663 .fetch_latest_server_version(http_client.clone())
664 .await?;
665 lsp_binary_statuses_tx
666 .broadcast((language.clone(), LanguageServerBinaryStatus::Downloading))
667 .await?;
668 let path = adapter
669 .fetch_server_binary(version_info, http_client, container_dir.to_path_buf())
670 .await?;
671 lsp_binary_statuses_tx
672 .broadcast((language.clone(), LanguageServerBinaryStatus::Downloaded))
673 .await?;
674 Ok(path)
675}
676
677impl Language {
678 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
679 Self {
680 config,
681 grammar: ts_language.map(|ts_language| {
682 Arc::new(Grammar {
683 id: NEXT_GRAMMAR_ID.fetch_add(1, SeqCst),
684 highlights_query: None,
685 brackets_config: None,
686 outline_config: None,
687 indents_config: None,
688 injection_config: None,
689 override_config: None,
690 error_query: Query::new(ts_language, "(ERROR) @error").unwrap(),
691 ts_language,
692 highlight_map: Default::default(),
693 })
694 }),
695 adapter: None,
696
697 #[cfg(any(test, feature = "test-support"))]
698 fake_adapter: None,
699 }
700 }
701
702 pub fn lsp_adapter(&self) -> Option<Arc<CachedLspAdapter>> {
703 self.adapter.clone()
704 }
705
706 pub fn id(&self) -> Option<usize> {
707 self.grammar.as_ref().map(|g| g.id)
708 }
709
710 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
711 let grammar = self.grammar_mut();
712 grammar.highlights_query = Some(Query::new(grammar.ts_language, source)?);
713 Ok(self)
714 }
715
716 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
717 let grammar = self.grammar_mut();
718 let query = Query::new(grammar.ts_language, source)?;
719 let mut open_capture_ix = None;
720 let mut close_capture_ix = None;
721 get_capture_indices(
722 &query,
723 &mut [
724 ("open", &mut open_capture_ix),
725 ("close", &mut close_capture_ix),
726 ],
727 );
728 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
729 grammar.brackets_config = Some(BracketConfig {
730 query,
731 open_capture_ix,
732 close_capture_ix,
733 });
734 }
735 Ok(self)
736 }
737
738 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
739 let grammar = self.grammar_mut();
740 let query = Query::new(grammar.ts_language, source)?;
741 let mut indent_capture_ix = None;
742 let mut start_capture_ix = None;
743 let mut end_capture_ix = None;
744 let mut outdent_capture_ix = None;
745 get_capture_indices(
746 &query,
747 &mut [
748 ("indent", &mut indent_capture_ix),
749 ("start", &mut start_capture_ix),
750 ("end", &mut end_capture_ix),
751 ("outdent", &mut outdent_capture_ix),
752 ],
753 );
754 if let Some(indent_capture_ix) = indent_capture_ix {
755 grammar.indents_config = Some(IndentConfig {
756 query,
757 indent_capture_ix,
758 start_capture_ix,
759 end_capture_ix,
760 outdent_capture_ix,
761 });
762 }
763 Ok(self)
764 }
765
766 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
767 let grammar = self.grammar_mut();
768 let query = Query::new(grammar.ts_language, source)?;
769 let mut item_capture_ix = None;
770 let mut name_capture_ix = None;
771 let mut context_capture_ix = None;
772 get_capture_indices(
773 &query,
774 &mut [
775 ("item", &mut item_capture_ix),
776 ("name", &mut name_capture_ix),
777 ("context", &mut context_capture_ix),
778 ],
779 );
780 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
781 grammar.outline_config = Some(OutlineConfig {
782 query,
783 item_capture_ix,
784 name_capture_ix,
785 context_capture_ix,
786 });
787 }
788 Ok(self)
789 }
790
791 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
792 let grammar = self.grammar_mut();
793 let query = Query::new(grammar.ts_language, source)?;
794 let mut language_capture_ix = None;
795 let mut content_capture_ix = None;
796 get_capture_indices(
797 &query,
798 &mut [
799 ("language", &mut language_capture_ix),
800 ("content", &mut content_capture_ix),
801 ],
802 );
803 let patterns = (0..query.pattern_count())
804 .map(|ix| {
805 let mut config = InjectionPatternConfig::default();
806 for setting in query.property_settings(ix) {
807 match setting.key.as_ref() {
808 "language" => {
809 config.language = setting.value.clone();
810 }
811 "combined" => {
812 config.combined = true;
813 }
814 _ => {}
815 }
816 }
817 config
818 })
819 .collect();
820 if let Some(content_capture_ix) = content_capture_ix {
821 grammar.injection_config = Some(InjectionConfig {
822 query,
823 language_capture_ix,
824 content_capture_ix,
825 patterns,
826 });
827 }
828 Ok(self)
829 }
830
831 pub fn with_override_query(mut self, source: &str) -> Result<Self> {
832 let query = Query::new(self.grammar_mut().ts_language, source)?;
833
834 let mut values = HashMap::default();
835 for (ix, name) in query.capture_names().iter().enumerate() {
836 if !name.starts_with('_') {
837 let value = self.config.overrides.remove(name).ok_or_else(|| {
838 anyhow!(
839 "language {:?} has override in query but not in config: {name:?}",
840 self.config.name
841 )
842 })?;
843 values.insert(ix as u32, value);
844 }
845 }
846
847 if !self.config.overrides.is_empty() {
848 let keys = self.config.overrides.keys().collect::<Vec<_>>();
849 Err(anyhow!(
850 "language {:?} has overrides in config not in query: {keys:?}",
851 self.config.name
852 ))?;
853 }
854
855 self.grammar_mut().override_config = Some(OverrideConfig { query, values });
856 Ok(self)
857 }
858
859 fn grammar_mut(&mut self) -> &mut Grammar {
860 Arc::get_mut(self.grammar.as_mut().unwrap()).unwrap()
861 }
862
863 pub fn with_lsp_adapter(mut self, lsp_adapter: Arc<CachedLspAdapter>) -> Self {
864 self.adapter = Some(lsp_adapter);
865 self
866 }
867
868 #[cfg(any(test, feature = "test-support"))]
869 pub async fn set_fake_lsp_adapter(
870 &mut self,
871 fake_lsp_adapter: Arc<FakeLspAdapter>,
872 ) -> mpsc::UnboundedReceiver<lsp::FakeLanguageServer> {
873 let (servers_tx, servers_rx) = mpsc::unbounded();
874 self.fake_adapter = Some((servers_tx, fake_lsp_adapter.clone()));
875 let adapter = CachedLspAdapter::new(fake_lsp_adapter).await;
876 self.adapter = Some(adapter);
877 servers_rx
878 }
879
880 pub fn name(&self) -> Arc<str> {
881 self.config.name.clone()
882 }
883
884 pub async fn disk_based_diagnostic_sources(&self) -> &[String] {
885 match self.adapter.as_ref() {
886 Some(adapter) => &adapter.disk_based_diagnostic_sources,
887 None => &[],
888 }
889 }
890
891 pub async fn disk_based_diagnostics_progress_token(&self) -> Option<&str> {
892 if let Some(adapter) = self.adapter.as_ref() {
893 adapter.disk_based_diagnostics_progress_token.as_deref()
894 } else {
895 None
896 }
897 }
898
899 pub async fn process_diagnostics(&self, diagnostics: &mut lsp::PublishDiagnosticsParams) {
900 if let Some(processor) = self.adapter.as_ref() {
901 processor.process_diagnostics(diagnostics).await;
902 }
903 }
904
905 pub async fn process_completion(self: &Arc<Self>, completion: &mut lsp::CompletionItem) {
906 if let Some(adapter) = self.adapter.as_ref() {
907 adapter.process_completion(completion).await;
908 }
909 }
910
911 pub async fn label_for_completion(
912 self: &Arc<Self>,
913 completion: &lsp::CompletionItem,
914 ) -> Option<CodeLabel> {
915 self.adapter
916 .as_ref()?
917 .label_for_completion(completion, self)
918 .await
919 }
920
921 pub async fn label_for_symbol(
922 self: &Arc<Self>,
923 name: &str,
924 kind: lsp::SymbolKind,
925 ) -> Option<CodeLabel> {
926 self.adapter
927 .as_ref()?
928 .label_for_symbol(name, kind, self)
929 .await
930 }
931
932 pub fn highlight_text<'a>(
933 self: &'a Arc<Self>,
934 text: &'a Rope,
935 range: Range<usize>,
936 ) -> Vec<(Range<usize>, HighlightId)> {
937 let mut result = Vec::new();
938 if let Some(grammar) = &self.grammar {
939 let tree = grammar.parse_text(text, None);
940 let captures =
941 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
942 grammar.highlights_query.as_ref()
943 });
944 let highlight_maps = vec![grammar.highlight_map()];
945 let mut offset = 0;
946 for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
947 let end_offset = offset + chunk.text.len();
948 if let Some(highlight_id) = chunk.syntax_highlight_id {
949 if !highlight_id.is_default() {
950 result.push((offset..end_offset, highlight_id));
951 }
952 }
953 offset = end_offset;
954 }
955 }
956 result
957 }
958
959 pub fn path_suffixes(&self) -> &[String] {
960 &self.config.path_suffixes
961 }
962
963 pub fn should_autoclose_before(&self, c: char) -> bool {
964 c.is_whitespace() || self.config.autoclose_before.contains(c)
965 }
966
967 pub fn set_theme(&self, theme: &SyntaxTheme) {
968 if let Some(grammar) = self.grammar.as_ref() {
969 if let Some(highlights_query) = &grammar.highlights_query {
970 *grammar.highlight_map.lock() =
971 HighlightMap::new(highlights_query.capture_names(), theme);
972 }
973 }
974 }
975
976 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
977 self.grammar.as_ref()
978 }
979}
980
981impl LanguageScope {
982 pub fn line_comment_prefix(&self) -> Option<&Arc<str>> {
983 Override::as_option(
984 self.config_override().map(|o| &o.line_comment),
985 self.language.config.line_comment.as_ref(),
986 )
987 }
988
989 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
990 Override::as_option(
991 self.config_override().map(|o| &o.block_comment),
992 self.language.config.block_comment.as_ref(),
993 )
994 .map(|e| (&e.0, &e.1))
995 }
996
997 pub fn brackets(&self) -> &[BracketPair] {
998 Override::as_option(
999 self.config_override().map(|o| &o.brackets),
1000 Some(&self.language.config.brackets),
1001 )
1002 .map_or(&[], Vec::as_slice)
1003 }
1004
1005 pub fn should_autoclose_before(&self, c: char) -> bool {
1006 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1007 }
1008
1009 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1010 let id = self.override_id?;
1011 let grammar = self.language.grammar.as_ref()?;
1012 let override_config = grammar.override_config.as_ref()?;
1013 override_config.values.get(&id)
1014 }
1015}
1016
1017impl Hash for Language {
1018 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1019 self.id().hash(state)
1020 }
1021}
1022
1023impl PartialEq for Language {
1024 fn eq(&self, other: &Self) -> bool {
1025 self.id().eq(&other.id())
1026 }
1027}
1028
1029impl Eq for Language {}
1030
1031impl Debug for Language {
1032 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1033 f.debug_struct("Language")
1034 .field("name", &self.config.name)
1035 .finish()
1036 }
1037}
1038
1039impl Grammar {
1040 pub fn id(&self) -> usize {
1041 self.id
1042 }
1043
1044 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1045 PARSER.with(|parser| {
1046 let mut parser = parser.borrow_mut();
1047 parser
1048 .set_language(self.ts_language)
1049 .expect("incompatible grammar");
1050 let mut chunks = text.chunks_in_range(0..text.len());
1051 parser
1052 .parse_with(
1053 &mut move |offset, _| {
1054 chunks.seek(offset);
1055 chunks.next().unwrap_or("").as_bytes()
1056 },
1057 old_tree.as_ref(),
1058 )
1059 .unwrap()
1060 })
1061 }
1062
1063 pub fn highlight_map(&self) -> HighlightMap {
1064 self.highlight_map.lock().clone()
1065 }
1066
1067 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1068 let capture_id = self
1069 .highlights_query
1070 .as_ref()?
1071 .capture_index_for_name(name)?;
1072 Some(self.highlight_map.lock().get(capture_id))
1073 }
1074}
1075
1076impl CodeLabel {
1077 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1078 let mut result = Self {
1079 runs: Vec::new(),
1080 filter_range: 0..text.len(),
1081 text,
1082 };
1083 if let Some(filter_text) = filter_text {
1084 if let Some(ix) = result.text.find(filter_text) {
1085 result.filter_range = ix..ix + filter_text.len();
1086 }
1087 }
1088 result
1089 }
1090}
1091
1092#[cfg(any(test, feature = "test-support"))]
1093impl Default for FakeLspAdapter {
1094 fn default() -> Self {
1095 Self {
1096 name: "the-fake-language-server",
1097 capabilities: lsp::LanguageServer::full_capabilities(),
1098 initializer: None,
1099 disk_based_diagnostics_progress_token: None,
1100 disk_based_diagnostics_sources: Vec::new(),
1101 }
1102 }
1103}
1104
1105#[cfg(any(test, feature = "test-support"))]
1106#[async_trait]
1107impl LspAdapter for Arc<FakeLspAdapter> {
1108 async fn name(&self) -> LanguageServerName {
1109 LanguageServerName(self.name.into())
1110 }
1111
1112 async fn fetch_latest_server_version(
1113 &self,
1114 _: Arc<dyn HttpClient>,
1115 ) -> Result<Box<dyn 'static + Send + Any>> {
1116 unreachable!();
1117 }
1118
1119 async fn fetch_server_binary(
1120 &self,
1121 _: Box<dyn 'static + Send + Any>,
1122 _: Arc<dyn HttpClient>,
1123 _: PathBuf,
1124 ) -> Result<PathBuf> {
1125 unreachable!();
1126 }
1127
1128 async fn cached_server_binary(&self, _: PathBuf) -> Option<PathBuf> {
1129 unreachable!();
1130 }
1131
1132 async fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1133
1134 async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1135 self.disk_based_diagnostics_sources.clone()
1136 }
1137
1138 async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1139 self.disk_based_diagnostics_progress_token.clone()
1140 }
1141}
1142
1143fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1144 for (ix, name) in query.capture_names().iter().enumerate() {
1145 for (capture_name, index) in captures.iter_mut() {
1146 if capture_name == name {
1147 **index = Some(ix as u32);
1148 break;
1149 }
1150 }
1151 }
1152}
1153
1154pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1155 lsp::Position::new(point.row, point.column)
1156}
1157
1158pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1159 Unclipped(PointUtf16::new(point.line, point.character))
1160}
1161
1162pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1163 lsp::Range {
1164 start: point_to_lsp(range.start),
1165 end: point_to_lsp(range.end),
1166 }
1167}
1168
1169pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1170 let mut start = point_from_lsp(range.start);
1171 let mut end = point_from_lsp(range.end);
1172 if start > end {
1173 mem::swap(&mut start, &mut end);
1174 }
1175 start..end
1176}