1//! The `language` crate provides... ???
2
3#![warn(missing_docs)]
4
5mod buffer;
6mod diagnostic_set;
7mod highlight_map;
8pub mod language_settings;
9mod outline;
10pub mod proto;
11mod syntax_map;
12
13#[cfg(test)]
14mod buffer_tests;
15pub mod markdown;
16
17use anyhow::{anyhow, Context, Result};
18use async_trait::async_trait;
19use collections::{HashMap, HashSet};
20use futures::{
21 channel::{mpsc, oneshot},
22 future::{BoxFuture, Shared},
23 FutureExt, TryFutureExt as _,
24};
25use gpui::{AppContext, AsyncAppContext, BackgroundExecutor, Task};
26pub use highlight_map::HighlightMap;
27use lazy_static::lazy_static;
28use lsp::{CodeActionKind, LanguageServerBinary};
29use parking_lot::{Mutex, RwLock};
30use postage::watch;
31use regex::Regex;
32use serde::{de, Deserialize, Deserializer};
33use serde_json::Value;
34use std::{
35 any::Any,
36 borrow::Cow,
37 cell::RefCell,
38 fmt::Debug,
39 hash::Hash,
40 mem,
41 ops::{Not, Range},
42 path::{Path, PathBuf},
43 str,
44 sync::{
45 atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
46 Arc,
47 },
48};
49use syntax_map::SyntaxSnapshot;
50use theme::{SyntaxTheme, Theme};
51use tree_sitter::{self, Query};
52use unicase::UniCase;
53use util::{http::HttpClient, paths::PathExt};
54use util::{post_inc, ResultExt, TryFutureExt as _, UnwrapFuture};
55
56pub use buffer::Operation;
57pub use buffer::*;
58pub use diagnostic_set::DiagnosticEntry;
59pub use lsp::LanguageServerId;
60pub use outline::{Outline, OutlineItem};
61pub use syntax_map::{OwnedSyntaxLayer, SyntaxLayer};
62pub use text::LineEnding;
63pub use tree_sitter::{Parser, Tree};
64
65/// Initializes the `language` crate.
66///
67/// This should be called before making use of items from the create.
68pub fn init(cx: &mut AppContext) {
69 language_settings::init(cx);
70}
71
72#[derive(Clone, Default)]
73struct LspBinaryStatusSender {
74 txs: Arc<Mutex<Vec<mpsc::UnboundedSender<(Arc<Language>, LanguageServerBinaryStatus)>>>>,
75}
76
77impl LspBinaryStatusSender {
78 fn subscribe(&self) -> mpsc::UnboundedReceiver<(Arc<Language>, LanguageServerBinaryStatus)> {
79 let (tx, rx) = mpsc::unbounded();
80 self.txs.lock().push(tx);
81 rx
82 }
83
84 fn send(&self, language: Arc<Language>, status: LanguageServerBinaryStatus) {
85 let mut txs = self.txs.lock();
86 txs.retain(|tx| {
87 tx.unbounded_send((language.clone(), status.clone()))
88 .is_ok()
89 });
90 }
91}
92
93thread_local! {
94 static PARSER: RefCell<Parser> = {
95 RefCell::new(Parser::new())
96 };
97}
98
99lazy_static! {
100 pub(crate) static ref NEXT_GRAMMAR_ID: AtomicUsize = Default::default();
101 /// A shared grammar for plain text, exposed for reuse by downstream crates.
102 #[doc(hidden)]
103 pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(
104 LanguageConfig {
105 name: "Plain Text".into(),
106 ..Default::default()
107 },
108 None,
109 ));
110}
111
112pub trait ToLspPosition {
113 fn to_lsp_position(self) -> lsp::Position;
114}
115
116#[derive(Clone, Debug, PartialEq, Eq, Hash)]
117pub struct LanguageServerName(pub Arc<str>);
118
119/// Represents a Language Server, with certain cached sync properties.
120/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
121/// once at startup, and caches the results.
122pub struct CachedLspAdapter {
123 pub name: LanguageServerName,
124 pub short_name: &'static str,
125 pub disk_based_diagnostic_sources: Vec<String>,
126 pub disk_based_diagnostics_progress_token: Option<String>,
127 pub language_ids: HashMap<String, String>,
128 pub adapter: Arc<dyn LspAdapter>,
129 pub reinstall_attempt_count: AtomicU64,
130}
131
132impl CachedLspAdapter {
133 pub async fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
134 let name = adapter.name().await;
135 let short_name = adapter.short_name();
136 let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources().await;
137 let disk_based_diagnostics_progress_token =
138 adapter.disk_based_diagnostics_progress_token().await;
139 let language_ids = adapter.language_ids().await;
140
141 Arc::new(CachedLspAdapter {
142 name,
143 short_name,
144 disk_based_diagnostic_sources,
145 disk_based_diagnostics_progress_token,
146 language_ids,
147 adapter,
148 reinstall_attempt_count: AtomicU64::new(0),
149 })
150 }
151
152 pub async fn fetch_latest_server_version(
153 &self,
154 delegate: &dyn LspAdapterDelegate,
155 ) -> Result<Box<dyn 'static + Send + Any>> {
156 self.adapter.fetch_latest_server_version(delegate).await
157 }
158
159 pub fn will_fetch_server(
160 &self,
161 delegate: &Arc<dyn LspAdapterDelegate>,
162 cx: &mut AsyncAppContext,
163 ) -> Option<Task<Result<()>>> {
164 self.adapter.will_fetch_server(delegate, cx)
165 }
166
167 pub fn will_start_server(
168 &self,
169 delegate: &Arc<dyn LspAdapterDelegate>,
170 cx: &mut AsyncAppContext,
171 ) -> Option<Task<Result<()>>> {
172 self.adapter.will_start_server(delegate, cx)
173 }
174
175 pub async fn fetch_server_binary(
176 &self,
177 version: Box<dyn 'static + Send + Any>,
178 container_dir: PathBuf,
179 delegate: &dyn LspAdapterDelegate,
180 ) -> Result<LanguageServerBinary> {
181 self.adapter
182 .fetch_server_binary(version, container_dir, delegate)
183 .await
184 }
185
186 pub async fn cached_server_binary(
187 &self,
188 container_dir: PathBuf,
189 delegate: &dyn LspAdapterDelegate,
190 ) -> Option<LanguageServerBinary> {
191 self.adapter
192 .cached_server_binary(container_dir, delegate)
193 .await
194 }
195
196 pub fn can_be_reinstalled(&self) -> bool {
197 self.adapter.can_be_reinstalled()
198 }
199
200 pub async fn installation_test_binary(
201 &self,
202 container_dir: PathBuf,
203 ) -> Option<LanguageServerBinary> {
204 self.adapter.installation_test_binary(container_dir).await
205 }
206
207 pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
208 self.adapter.code_action_kinds()
209 }
210
211 pub fn workspace_configuration(
212 &self,
213 workspace_root: &Path,
214 cx: &mut AppContext,
215 ) -> BoxFuture<'static, Value> {
216 self.adapter.workspace_configuration(workspace_root, cx)
217 }
218
219 pub fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
220 self.adapter.process_diagnostics(params)
221 }
222
223 pub async fn process_completion(&self, completion_item: &mut lsp::CompletionItem) {
224 self.adapter.process_completion(completion_item).await
225 }
226
227 pub async fn label_for_completion(
228 &self,
229 completion_item: &lsp::CompletionItem,
230 language: &Arc<Language>,
231 ) -> Option<CodeLabel> {
232 self.adapter
233 .label_for_completion(completion_item, language)
234 .await
235 }
236
237 pub async fn label_for_symbol(
238 &self,
239 name: &str,
240 kind: lsp::SymbolKind,
241 language: &Arc<Language>,
242 ) -> Option<CodeLabel> {
243 self.adapter.label_for_symbol(name, kind, language).await
244 }
245
246 pub fn prettier_plugins(&self) -> &[&'static str] {
247 self.adapter.prettier_plugins()
248 }
249}
250
251/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
252// e.g. to display a notification or fetch data from the web.
253pub trait LspAdapterDelegate: Send + Sync {
254 fn show_notification(&self, message: &str, cx: &mut AppContext);
255 fn http_client(&self) -> Arc<dyn HttpClient>;
256}
257
258#[async_trait]
259pub trait LspAdapter: 'static + Send + Sync {
260 async fn name(&self) -> LanguageServerName;
261
262 fn short_name(&self) -> &'static str;
263
264 async fn fetch_latest_server_version(
265 &self,
266 delegate: &dyn LspAdapterDelegate,
267 ) -> Result<Box<dyn 'static + Send + Any>>;
268
269 fn will_fetch_server(
270 &self,
271 _: &Arc<dyn LspAdapterDelegate>,
272 _: &mut AsyncAppContext,
273 ) -> Option<Task<Result<()>>> {
274 None
275 }
276
277 fn will_start_server(
278 &self,
279 _: &Arc<dyn LspAdapterDelegate>,
280 _: &mut AsyncAppContext,
281 ) -> Option<Task<Result<()>>> {
282 None
283 }
284
285 async fn fetch_server_binary(
286 &self,
287 version: Box<dyn 'static + Send + Any>,
288 container_dir: PathBuf,
289 delegate: &dyn LspAdapterDelegate,
290 ) -> Result<LanguageServerBinary>;
291
292 async fn cached_server_binary(
293 &self,
294 container_dir: PathBuf,
295 delegate: &dyn LspAdapterDelegate,
296 ) -> Option<LanguageServerBinary>;
297
298 /// Returns true if a language server can be reinstalled.
299 /// If language server initialization fails, a reinstallation will be attempted unless the value returned from this method is false.
300 /// Implementations that rely on software already installed on user's system
301 /// should have [`can_be_reinstalled`] return false.
302 fn can_be_reinstalled(&self) -> bool {
303 true
304 }
305
306 async fn installation_test_binary(
307 &self,
308 container_dir: PathBuf,
309 ) -> Option<LanguageServerBinary>;
310
311 fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
312
313 /// A callback called for each [`lsp_types::CompletionItem`] obtained from LSP server.
314 /// Some LspAdapter implementations might want to modify the obtained item to
315 /// change how it's displayed.
316 async fn process_completion(&self, _: &mut lsp::CompletionItem) {}
317
318 async fn label_for_completion(
319 &self,
320 _: &lsp::CompletionItem,
321 _: &Arc<Language>,
322 ) -> Option<CodeLabel> {
323 None
324 }
325
326 async fn label_for_symbol(
327 &self,
328 _: &str,
329 _: lsp::SymbolKind,
330 _: &Arc<Language>,
331 ) -> Option<CodeLabel> {
332 None
333 }
334
335 /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp_types::InitializeParams`]
336 async fn initialization_options(&self) -> Option<Value> {
337 None
338 }
339
340 fn workspace_configuration(&self, _: &Path, _: &mut AppContext) -> BoxFuture<'static, Value> {
341 futures::future::ready(serde_json::json!({})).boxed()
342 }
343
344 /// Returns a list of code actions supported by a given LspAdapter
345 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
346 Some(vec![
347 CodeActionKind::EMPTY,
348 CodeActionKind::QUICKFIX,
349 CodeActionKind::REFACTOR,
350 CodeActionKind::REFACTOR_EXTRACT,
351 CodeActionKind::SOURCE,
352 ])
353 }
354
355 async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
356 Default::default()
357 }
358
359 async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
360 None
361 }
362
363 async fn language_ids(&self) -> HashMap<String, String> {
364 Default::default()
365 }
366
367 fn prettier_plugins(&self) -> &[&'static str] {
368 &[]
369 }
370}
371
372#[derive(Clone, Debug, PartialEq, Eq)]
373pub struct CodeLabel {
374 pub text: String,
375 pub runs: Vec<(Range<usize>, HighlightId)>,
376 pub filter_range: Range<usize>,
377}
378
379#[derive(Clone, Deserialize)]
380pub struct LanguageConfig {
381 /// Human-readable name of the language.
382 pub name: Arc<str>,
383 // The name of the grammar in a WASM bundle.
384 pub grammar_name: Option<Arc<str>>,
385 /// Given a list of `LanguageConfig`'s, the language of a file can be determined based on the path extension matching any of the `path_suffixes`.
386 pub path_suffixes: Vec<String>,
387 /// List of bracket types in a language.
388 pub brackets: BracketPairConfig,
389 /// A regex pattern that determines whether the language should be assigned to a file or not.
390 #[serde(default, deserialize_with = "deserialize_regex")]
391 pub first_line_pattern: Option<Regex>,
392 /// If set to true, auto indentation uses last non empty line to determine
393 /// the indentation level for a new line.
394 #[serde(default = "auto_indent_using_last_non_empty_line_default")]
395 pub auto_indent_using_last_non_empty_line: bool,
396 /// A regex that is used to determine whether the indentation level should be
397 /// increased in the following line.
398 #[serde(default, deserialize_with = "deserialize_regex")]
399 pub increase_indent_pattern: Option<Regex>,
400 /// A regex that is used to determine whether the indentation level should be
401 /// decreased in the following line.
402 #[serde(default, deserialize_with = "deserialize_regex")]
403 pub decrease_indent_pattern: Option<Regex>,
404 /// A list of characters that trigger the automatic insertion of a closing
405 /// bracket when they immediately precede the point where an opening
406 /// bracket is inserted.
407 #[serde(default)]
408 pub autoclose_before: String,
409 /// A placeholder used internally by Semantic Index.
410 #[serde(default)]
411 pub collapsed_placeholder: String,
412 /// A line comment string that is inserted in e.g. `toggle comments` action.
413 #[serde(default)]
414 pub line_comment: Option<Arc<str>>,
415 /// Starting and closing characters of a block comment.
416 #[serde(default)]
417 pub block_comment: Option<(Arc<str>, Arc<str>)>,
418 /// A list of language servers that are allowed to run on subranges of a given language.
419 #[serde(default)]
420 pub scope_opt_in_language_servers: Vec<String>,
421 #[serde(default)]
422 pub overrides: HashMap<String, LanguageConfigOverride>,
423 /// A list of characters that Zed should treat as word characters for the
424 /// purpose of features that operate on word boundaries, like 'move to next word end'
425 /// or a whole-word search in buffer search.
426 #[serde(default)]
427 pub word_characters: HashSet<char>,
428 /// The name of a Prettier parser that should be used for this language.
429 #[serde(default)]
430 pub prettier_parser_name: Option<String>,
431}
432
433/// Tree-sitter language queries for a given language.
434#[derive(Debug, Default)]
435pub struct LanguageQueries {
436 pub highlights: Option<Cow<'static, str>>,
437 pub brackets: Option<Cow<'static, str>>,
438 pub indents: Option<Cow<'static, str>>,
439 pub outline: Option<Cow<'static, str>>,
440 pub embedding: Option<Cow<'static, str>>,
441 pub injections: Option<Cow<'static, str>>,
442 pub overrides: Option<Cow<'static, str>>,
443}
444
445/// Represents a language for the given range. Some languages (e.g. HTML)
446/// interleave several languages together, thus a single buffer might actually contain
447/// several nested scopes.
448#[derive(Clone, Debug)]
449pub struct LanguageScope {
450 language: Arc<Language>,
451 override_id: Option<u32>,
452}
453
454#[derive(Clone, Deserialize, Default, Debug)]
455pub struct LanguageConfigOverride {
456 #[serde(default)]
457 pub line_comment: Override<Arc<str>>,
458 #[serde(default)]
459 pub block_comment: Override<(Arc<str>, Arc<str>)>,
460 #[serde(skip_deserializing)]
461 pub disabled_bracket_ixs: Vec<u16>,
462 #[serde(default)]
463 pub word_characters: Override<HashSet<char>>,
464 #[serde(default)]
465 pub opt_into_language_servers: Vec<String>,
466}
467
468#[derive(Clone, Deserialize, Debug)]
469#[serde(untagged)]
470pub enum Override<T> {
471 Remove { remove: bool },
472 Set(T),
473}
474
475impl<T> Default for Override<T> {
476 fn default() -> Self {
477 Override::Remove { remove: false }
478 }
479}
480
481impl<T> Override<T> {
482 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
483 match this {
484 Some(Self::Set(value)) => Some(value),
485 Some(Self::Remove { remove: true }) => None,
486 Some(Self::Remove { remove: false }) | None => original,
487 }
488 }
489}
490
491impl Default for LanguageConfig {
492 fn default() -> Self {
493 Self {
494 name: "".into(),
495 grammar_name: None,
496 path_suffixes: Default::default(),
497 brackets: Default::default(),
498 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
499 first_line_pattern: Default::default(),
500 increase_indent_pattern: Default::default(),
501 decrease_indent_pattern: Default::default(),
502 autoclose_before: Default::default(),
503 line_comment: Default::default(),
504 block_comment: Default::default(),
505 scope_opt_in_language_servers: Default::default(),
506 overrides: Default::default(),
507 word_characters: Default::default(),
508 prettier_parser_name: None,
509 collapsed_placeholder: Default::default(),
510 }
511 }
512}
513
514fn auto_indent_using_last_non_empty_line_default() -> bool {
515 true
516}
517
518fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
519 let source = Option::<String>::deserialize(d)?;
520 if let Some(source) = source {
521 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
522 } else {
523 Ok(None)
524 }
525}
526
527#[doc(hidden)]
528#[cfg(any(test, feature = "test-support"))]
529pub struct FakeLspAdapter {
530 pub name: &'static str,
531 pub initialization_options: Option<Value>,
532 pub capabilities: lsp::ServerCapabilities,
533 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
534 pub disk_based_diagnostics_progress_token: Option<String>,
535 pub disk_based_diagnostics_sources: Vec<String>,
536 pub prettier_plugins: Vec<&'static str>,
537}
538
539/// Configuration of handling bracket pairs for a given language.
540///
541/// This struct includes settings for defining which pairs of characters are considered brackets and
542/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
543#[derive(Clone, Debug, Default)]
544pub struct BracketPairConfig {
545 /// A list of character pairs that should be treated as brackets in the context of a given language.
546 pub pairs: Vec<BracketPair>,
547 /// A list of tree-sitter scopes for which a given bracket should not be active.
548 /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
549 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
550}
551
552impl<'de> Deserialize<'de> for BracketPairConfig {
553 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
554 where
555 D: Deserializer<'de>,
556 {
557 #[derive(Deserialize)]
558 pub struct Entry {
559 #[serde(flatten)]
560 pub bracket_pair: BracketPair,
561 #[serde(default)]
562 pub not_in: Vec<String>,
563 }
564
565 let result = Vec::<Entry>::deserialize(deserializer)?;
566 let mut brackets = Vec::with_capacity(result.len());
567 let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
568 for entry in result {
569 brackets.push(entry.bracket_pair);
570 disabled_scopes_by_bracket_ix.push(entry.not_in);
571 }
572
573 Ok(BracketPairConfig {
574 pairs: brackets,
575 disabled_scopes_by_bracket_ix,
576 })
577 }
578}
579
580/// Describes a single bracket pair and how an editor should react to e.g. inserting
581/// an opening bracket or to a newline character insertion inbetween `start` and `end` characters.
582#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
583pub struct BracketPair {
584 /// Starting substring for a bracket.
585 pub start: String,
586 /// Ending substring for a bracket.
587 pub end: String,
588 /// True if `end` should be automatically inserted right after `start` characters.
589 pub close: bool,
590 /// True if an extra newline should be inserted while the cursor is in the middle
591 /// of that bracket pair.
592 pub newline: bool,
593}
594
595pub struct Language {
596 pub(crate) config: LanguageConfig,
597 pub(crate) grammar: Option<Arc<Grammar>>,
598 pub(crate) adapters: Vec<Arc<CachedLspAdapter>>,
599
600 #[cfg(any(test, feature = "test-support"))]
601 fake_adapter: Option<(
602 mpsc::UnboundedSender<lsp::FakeLanguageServer>,
603 Arc<FakeLspAdapter>,
604 )>,
605}
606
607pub struct Grammar {
608 id: usize,
609 pub ts_language: tree_sitter::Language,
610 pub(crate) error_query: Query,
611 pub(crate) highlights_query: Option<Query>,
612 pub(crate) brackets_config: Option<BracketConfig>,
613 pub(crate) indents_config: Option<IndentConfig>,
614 pub outline_config: Option<OutlineConfig>,
615 pub embedding_config: Option<EmbeddingConfig>,
616 pub(crate) injection_config: Option<InjectionConfig>,
617 pub(crate) override_config: Option<OverrideConfig>,
618 pub(crate) highlight_map: Mutex<HighlightMap>,
619}
620
621struct IndentConfig {
622 query: Query,
623 indent_capture_ix: u32,
624 start_capture_ix: Option<u32>,
625 end_capture_ix: Option<u32>,
626 outdent_capture_ix: Option<u32>,
627}
628
629pub struct OutlineConfig {
630 pub query: Query,
631 pub item_capture_ix: u32,
632 pub name_capture_ix: u32,
633 pub context_capture_ix: Option<u32>,
634 pub extra_context_capture_ix: Option<u32>,
635}
636
637#[derive(Debug)]
638pub struct EmbeddingConfig {
639 pub query: Query,
640 pub item_capture_ix: u32,
641 pub name_capture_ix: Option<u32>,
642 pub context_capture_ix: Option<u32>,
643 pub collapse_capture_ix: Option<u32>,
644 pub keep_capture_ix: Option<u32>,
645}
646
647struct InjectionConfig {
648 query: Query,
649 content_capture_ix: u32,
650 language_capture_ix: Option<u32>,
651 patterns: Vec<InjectionPatternConfig>,
652}
653
654struct OverrideConfig {
655 query: Query,
656 values: HashMap<u32, (String, LanguageConfigOverride)>,
657}
658
659#[derive(Default, Clone)]
660struct InjectionPatternConfig {
661 language: Option<Box<str>>,
662 combined: bool,
663}
664
665struct BracketConfig {
666 query: Query,
667 open_capture_ix: u32,
668 close_capture_ix: u32,
669}
670
671#[derive(Clone)]
672pub enum LanguageServerBinaryStatus {
673 CheckingForUpdate,
674 Downloading,
675 Downloaded,
676 Cached,
677 Failed { error: String },
678}
679
680type AvailableLanguageId = usize;
681
682#[derive(Clone)]
683struct AvailableLanguage {
684 id: AvailableLanguageId,
685 config: LanguageConfig,
686 grammar: AvailableGrammar,
687 lsp_adapters: Vec<Arc<dyn LspAdapter>>,
688 loaded: bool,
689}
690
691#[derive(Clone)]
692enum AvailableGrammar {
693 Native {
694 grammar: tree_sitter::Language,
695 asset_dir: &'static str,
696 get_queries: fn(&str) -> LanguageQueries,
697 },
698 Wasm {
699 _grammar_name: Arc<str>,
700 _path: Arc<Path>,
701 },
702}
703
704pub struct LanguageRegistry {
705 state: RwLock<LanguageRegistryState>,
706 language_server_download_dir: Option<Arc<Path>>,
707 login_shell_env_loaded: Shared<Task<()>>,
708 #[allow(clippy::type_complexity)]
709 lsp_binary_paths: Mutex<
710 HashMap<LanguageServerName, Shared<Task<Result<LanguageServerBinary, Arc<anyhow::Error>>>>>,
711 >,
712 executor: Option<BackgroundExecutor>,
713 lsp_binary_status_tx: LspBinaryStatusSender,
714}
715
716struct LanguageRegistryState {
717 next_language_server_id: usize,
718 languages: Vec<Arc<Language>>,
719 available_languages: Vec<AvailableLanguage>,
720 next_available_language_id: AvailableLanguageId,
721 loading_languages: HashMap<AvailableLanguageId, Vec<oneshot::Sender<Result<Arc<Language>>>>>,
722 subscription: (watch::Sender<()>, watch::Receiver<()>),
723 theme: Option<Arc<Theme>>,
724 version: usize,
725 reload_count: usize,
726}
727
728pub struct PendingLanguageServer {
729 pub server_id: LanguageServerId,
730 pub task: Task<Result<lsp::LanguageServer>>,
731 pub container_dir: Option<Arc<Path>>,
732}
733
734impl LanguageRegistry {
735 pub fn new(login_shell_env_loaded: Task<()>) -> Self {
736 Self {
737 state: RwLock::new(LanguageRegistryState {
738 next_language_server_id: 0,
739 languages: vec![PLAIN_TEXT.clone()],
740 available_languages: Default::default(),
741 next_available_language_id: 0,
742 loading_languages: Default::default(),
743 subscription: watch::channel(),
744 theme: Default::default(),
745 version: 0,
746 reload_count: 0,
747 }),
748 language_server_download_dir: None,
749 login_shell_env_loaded: login_shell_env_loaded.shared(),
750 lsp_binary_paths: Default::default(),
751 executor: None,
752 lsp_binary_status_tx: Default::default(),
753 }
754 }
755
756 #[cfg(any(test, feature = "test-support"))]
757 pub fn test() -> Self {
758 Self::new(Task::ready(()))
759 }
760
761 pub fn set_executor(&mut self, executor: BackgroundExecutor) {
762 self.executor = Some(executor);
763 }
764
765 /// Clear out all of the loaded languages and reload them from scratch.
766 ///
767 /// This is useful in development, when queries have changed.
768 #[cfg(debug_assertions)]
769 pub fn reload(&self) {
770 self.state.write().reload();
771 }
772
773 pub fn register(
774 &self,
775 asset_dir: &'static str,
776 config: LanguageConfig,
777 grammar: tree_sitter::Language,
778 lsp_adapters: Vec<Arc<dyn LspAdapter>>,
779 get_queries: fn(&str) -> LanguageQueries,
780 ) {
781 let state = &mut *self.state.write();
782 state.available_languages.push(AvailableLanguage {
783 id: post_inc(&mut state.next_available_language_id),
784 config,
785 grammar: AvailableGrammar::Native {
786 grammar,
787 get_queries,
788 asset_dir,
789 },
790 lsp_adapters,
791 loaded: false,
792 });
793 }
794
795 pub fn register_wasm(&self, path: Arc<Path>, grammar_name: Arc<str>, config: LanguageConfig) {
796 let state = &mut *self.state.write();
797 state.available_languages.push(AvailableLanguage {
798 id: post_inc(&mut state.next_available_language_id),
799 config,
800 grammar: AvailableGrammar::Wasm {
801 _grammar_name: grammar_name,
802 _path: path,
803 },
804 lsp_adapters: Vec::new(),
805 loaded: false,
806 });
807 }
808
809 pub fn language_names(&self) -> Vec<String> {
810 let state = self.state.read();
811 let mut result = state
812 .available_languages
813 .iter()
814 .filter_map(|l| l.loaded.not().then_some(l.config.name.to_string()))
815 .chain(state.languages.iter().map(|l| l.config.name.to_string()))
816 .collect::<Vec<_>>();
817 result.sort_unstable_by_key(|language_name| language_name.to_lowercase());
818 result
819 }
820
821 pub fn add(&self, language: Arc<Language>) {
822 self.state.write().add(language);
823 }
824
825 pub fn subscribe(&self) -> watch::Receiver<()> {
826 self.state.read().subscription.1.clone()
827 }
828
829 /// The number of times that the registry has been changed,
830 /// by adding languages or reloading.
831 pub fn version(&self) -> usize {
832 self.state.read().version
833 }
834
835 /// The number of times that the registry has been reloaded.
836 pub fn reload_count(&self) -> usize {
837 self.state.read().reload_count
838 }
839
840 pub fn set_theme(&self, theme: Arc<Theme>) {
841 let mut state = self.state.write();
842 state.theme = Some(theme.clone());
843 for language in &state.languages {
844 language.set_theme(&theme.syntax());
845 }
846 }
847
848 pub fn set_language_server_download_dir(&mut self, path: impl Into<Arc<Path>>) {
849 self.language_server_download_dir = Some(path.into());
850 }
851
852 pub fn language_for_name(
853 self: &Arc<Self>,
854 name: &str,
855 ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
856 let name = UniCase::new(name);
857 self.get_or_load_language(|config| UniCase::new(config.name.as_ref()) == name)
858 }
859
860 pub fn language_for_name_or_extension(
861 self: &Arc<Self>,
862 string: &str,
863 ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
864 let string = UniCase::new(string);
865 self.get_or_load_language(|config| {
866 UniCase::new(config.name.as_ref()) == string
867 || config
868 .path_suffixes
869 .iter()
870 .any(|suffix| UniCase::new(suffix) == string)
871 })
872 }
873
874 pub fn language_for_file(
875 self: &Arc<Self>,
876 path: impl AsRef<Path>,
877 content: Option<&Rope>,
878 ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
879 let path = path.as_ref();
880 let filename = path.file_name().and_then(|name| name.to_str());
881 let extension = path.extension_or_hidden_file_name();
882 let path_suffixes = [extension, filename];
883 self.get_or_load_language(|config| {
884 let path_matches = config
885 .path_suffixes
886 .iter()
887 .any(|suffix| path_suffixes.contains(&Some(suffix.as_str())));
888 let content_matches = content.zip(config.first_line_pattern.as_ref()).map_or(
889 false,
890 |(content, pattern)| {
891 let end = content.clip_point(Point::new(0, 256), Bias::Left);
892 let end = content.point_to_offset(end);
893 let text = content.chunks_in_range(0..end).collect::<String>();
894 pattern.is_match(&text)
895 },
896 );
897 path_matches || content_matches
898 })
899 }
900
901 fn get_or_load_language(
902 self: &Arc<Self>,
903 callback: impl Fn(&LanguageConfig) -> bool,
904 ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
905 let (tx, rx) = oneshot::channel();
906
907 let mut state = self.state.write();
908 if let Some(language) = state
909 .languages
910 .iter()
911 .find(|language| callback(&language.config))
912 {
913 let _ = tx.send(Ok(language.clone()));
914 } else if let Some(executor) = self.executor.clone() {
915 if let Some(language) = state
916 .available_languages
917 .iter()
918 .find(|l| !l.loaded && callback(&l.config))
919 .cloned()
920 {
921 let txs = state
922 .loading_languages
923 .entry(language.id)
924 .or_insert_with(|| {
925 let this = self.clone();
926 executor
927 .spawn(async move {
928 let id = language.id;
929 let name = language.config.name.clone();
930 let language = async {
931 let (grammar, queries) = match language.grammar {
932 AvailableGrammar::Native {
933 grammar,
934 asset_dir,
935 get_queries,
936 } => (grammar, (get_queries)(asset_dir)),
937 AvailableGrammar::Wasm { .. } => {
938 Err(anyhow!("not supported"))?
939 }
940 };
941 Language::new(language.config, Some(grammar))
942 .with_lsp_adapters(language.lsp_adapters)
943 .await
944 .with_queries(queries)
945 }
946 .await;
947
948 match language {
949 Ok(language) => {
950 let language = Arc::new(language);
951 let mut state = this.state.write();
952
953 state.add(language.clone());
954 state.mark_language_loaded(id);
955 if let Some(mut txs) = state.loading_languages.remove(&id) {
956 for tx in txs.drain(..) {
957 let _ = tx.send(Ok(language.clone()));
958 }
959 }
960 }
961 Err(e) => {
962 log::error!("failed to load language {name}:\n{:?}", e);
963 let mut state = this.state.write();
964 state.mark_language_loaded(id);
965 if let Some(mut txs) = state.loading_languages.remove(&id) {
966 for tx in txs.drain(..) {
967 let _ = tx.send(Err(anyhow!(
968 "failed to load language {}: {}",
969 name,
970 e
971 )));
972 }
973 }
974 }
975 };
976 })
977 .detach();
978
979 Vec::new()
980 });
981 txs.push(tx);
982 } else {
983 let _ = tx.send(Err(anyhow!("language not found")));
984 }
985 } else {
986 let _ = tx.send(Err(anyhow!("executor does not exist")));
987 }
988
989 rx.unwrap()
990 }
991
992 pub fn to_vec(&self) -> Vec<Arc<Language>> {
993 self.state.read().languages.iter().cloned().collect()
994 }
995
996 pub fn create_pending_language_server(
997 self: &Arc<Self>,
998 stderr_capture: Arc<Mutex<Option<String>>>,
999 language: Arc<Language>,
1000 adapter: Arc<CachedLspAdapter>,
1001 root_path: Arc<Path>,
1002 delegate: Arc<dyn LspAdapterDelegate>,
1003 cx: &mut AppContext,
1004 ) -> Option<PendingLanguageServer> {
1005 let server_id = self.state.write().next_language_server_id();
1006 log::info!(
1007 "starting language server {:?}, path: {root_path:?}, id: {server_id}",
1008 adapter.name.0
1009 );
1010
1011 #[cfg(any(test, feature = "test-support"))]
1012 if language.fake_adapter.is_some() {
1013 let task = cx.spawn(|cx| async move {
1014 let (servers_tx, fake_adapter) = language.fake_adapter.as_ref().unwrap();
1015 let (server, mut fake_server) = lsp::LanguageServer::fake(
1016 fake_adapter.name.to_string(),
1017 fake_adapter.capabilities.clone(),
1018 cx.clone(),
1019 );
1020
1021 if let Some(initializer) = &fake_adapter.initializer {
1022 initializer(&mut fake_server);
1023 }
1024
1025 let servers_tx = servers_tx.clone();
1026 cx.background_executor()
1027 .spawn(async move {
1028 if fake_server
1029 .try_receive_notification::<lsp::notification::Initialized>()
1030 .await
1031 .is_some()
1032 {
1033 servers_tx.unbounded_send(fake_server).ok();
1034 }
1035 })
1036 .detach();
1037
1038 Ok(server)
1039 });
1040
1041 return Some(PendingLanguageServer {
1042 server_id,
1043 task,
1044 container_dir: None,
1045 });
1046 }
1047
1048 let download_dir = self
1049 .language_server_download_dir
1050 .clone()
1051 .ok_or_else(|| anyhow!("language server download directory has not been assigned before starting server"))
1052 .log_err()?;
1053 let this = self.clone();
1054 let language = language.clone();
1055 let container_dir: Arc<Path> = Arc::from(download_dir.join(adapter.name.0.as_ref()));
1056 let root_path = root_path.clone();
1057 let adapter = adapter.clone();
1058 let login_shell_env_loaded = self.login_shell_env_loaded.clone();
1059 let lsp_binary_statuses = self.lsp_binary_status_tx.clone();
1060
1061 let task = {
1062 let container_dir = container_dir.clone();
1063 cx.spawn(move |mut cx| async move {
1064 login_shell_env_loaded.await;
1065
1066 let entry = this
1067 .lsp_binary_paths
1068 .lock()
1069 .entry(adapter.name.clone())
1070 .or_insert_with(|| {
1071 let adapter = adapter.clone();
1072 let language = language.clone();
1073 let delegate = delegate.clone();
1074 cx.spawn(|cx| {
1075 get_binary(
1076 adapter,
1077 language,
1078 delegate,
1079 container_dir,
1080 lsp_binary_statuses,
1081 cx,
1082 )
1083 .map_err(Arc::new)
1084 })
1085 .shared()
1086 })
1087 .clone();
1088
1089 let binary = match entry.await {
1090 Ok(binary) => binary,
1091 Err(err) => anyhow::bail!("{err}"),
1092 };
1093
1094 if let Some(task) = adapter.will_start_server(&delegate, &mut cx) {
1095 task.await?;
1096 }
1097
1098 lsp::LanguageServer::new(
1099 stderr_capture,
1100 server_id,
1101 binary,
1102 &root_path,
1103 adapter.code_action_kinds(),
1104 cx,
1105 )
1106 })
1107 };
1108
1109 Some(PendingLanguageServer {
1110 server_id,
1111 task,
1112 container_dir: Some(container_dir),
1113 })
1114 }
1115
1116 pub fn language_server_binary_statuses(
1117 &self,
1118 ) -> mpsc::UnboundedReceiver<(Arc<Language>, LanguageServerBinaryStatus)> {
1119 self.lsp_binary_status_tx.subscribe()
1120 }
1121
1122 pub fn delete_server_container(
1123 &self,
1124 adapter: Arc<CachedLspAdapter>,
1125 cx: &mut AppContext,
1126 ) -> Task<()> {
1127 log::info!("deleting server container");
1128
1129 let mut lock = self.lsp_binary_paths.lock();
1130 lock.remove(&adapter.name);
1131
1132 let download_dir = self
1133 .language_server_download_dir
1134 .clone()
1135 .expect("language server download directory has not been assigned before deleting server container");
1136
1137 cx.spawn(|_| async move {
1138 let container_dir = download_dir.join(adapter.name.0.as_ref());
1139 smol::fs::remove_dir_all(container_dir)
1140 .await
1141 .context("server container removal")
1142 .log_err();
1143 })
1144 }
1145
1146 pub fn next_language_server_id(&self) -> LanguageServerId {
1147 self.state.write().next_language_server_id()
1148 }
1149}
1150
1151impl LanguageRegistryState {
1152 fn next_language_server_id(&mut self) -> LanguageServerId {
1153 LanguageServerId(post_inc(&mut self.next_language_server_id))
1154 }
1155
1156 fn add(&mut self, language: Arc<Language>) {
1157 if let Some(theme) = self.theme.as_ref() {
1158 language.set_theme(&theme.syntax());
1159 }
1160 self.languages.push(language);
1161 self.version += 1;
1162 *self.subscription.0.borrow_mut() = ();
1163 }
1164
1165 #[cfg(debug_assertions)]
1166 fn reload(&mut self) {
1167 self.languages.clear();
1168 self.version += 1;
1169 self.reload_count += 1;
1170 for language in &mut self.available_languages {
1171 language.loaded = false;
1172 }
1173 *self.subscription.0.borrow_mut() = ();
1174 }
1175
1176 /// Mark the given language a having been loaded, so that the
1177 /// language registry won't try to load it again.
1178 fn mark_language_loaded(&mut self, id: AvailableLanguageId) {
1179 for language in &mut self.available_languages {
1180 if language.id == id {
1181 language.loaded = true;
1182 break;
1183 }
1184 }
1185 }
1186}
1187
1188#[cfg(any(test, feature = "test-support"))]
1189impl Default for LanguageRegistry {
1190 fn default() -> Self {
1191 Self::test()
1192 }
1193}
1194
1195async fn get_binary(
1196 adapter: Arc<CachedLspAdapter>,
1197 language: Arc<Language>,
1198 delegate: Arc<dyn LspAdapterDelegate>,
1199 container_dir: Arc<Path>,
1200 statuses: LspBinaryStatusSender,
1201 mut cx: AsyncAppContext,
1202) -> Result<LanguageServerBinary> {
1203 if !container_dir.exists() {
1204 smol::fs::create_dir_all(&container_dir)
1205 .await
1206 .context("failed to create container directory")?;
1207 }
1208
1209 if let Some(task) = adapter.will_fetch_server(&delegate, &mut cx) {
1210 task.await?;
1211 }
1212
1213 let binary = fetch_latest_binary(
1214 adapter.clone(),
1215 language.clone(),
1216 delegate.as_ref(),
1217 &container_dir,
1218 statuses.clone(),
1219 )
1220 .await;
1221
1222 if let Err(error) = binary.as_ref() {
1223 if let Some(binary) = adapter
1224 .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
1225 .await
1226 {
1227 statuses.send(language.clone(), LanguageServerBinaryStatus::Cached);
1228 return Ok(binary);
1229 } else {
1230 statuses.send(
1231 language.clone(),
1232 LanguageServerBinaryStatus::Failed {
1233 error: format!("{:?}", error),
1234 },
1235 );
1236 }
1237 }
1238
1239 binary
1240}
1241
1242async fn fetch_latest_binary(
1243 adapter: Arc<CachedLspAdapter>,
1244 language: Arc<Language>,
1245 delegate: &dyn LspAdapterDelegate,
1246 container_dir: &Path,
1247 lsp_binary_statuses_tx: LspBinaryStatusSender,
1248) -> Result<LanguageServerBinary> {
1249 let container_dir: Arc<Path> = container_dir.into();
1250 lsp_binary_statuses_tx.send(
1251 language.clone(),
1252 LanguageServerBinaryStatus::CheckingForUpdate,
1253 );
1254
1255 let version_info = adapter.fetch_latest_server_version(delegate).await?;
1256 lsp_binary_statuses_tx.send(language.clone(), LanguageServerBinaryStatus::Downloading);
1257
1258 let binary = adapter
1259 .fetch_server_binary(version_info, container_dir.to_path_buf(), delegate)
1260 .await?;
1261 lsp_binary_statuses_tx.send(language.clone(), LanguageServerBinaryStatus::Downloaded);
1262
1263 Ok(binary)
1264}
1265
1266impl Language {
1267 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1268 Self {
1269 config,
1270 grammar: ts_language.map(|ts_language| {
1271 Arc::new(Grammar {
1272 id: NEXT_GRAMMAR_ID.fetch_add(1, SeqCst),
1273 highlights_query: None,
1274 brackets_config: None,
1275 outline_config: None,
1276 embedding_config: None,
1277 indents_config: None,
1278 injection_config: None,
1279 override_config: None,
1280 error_query: Query::new(&ts_language, "(ERROR) @error").unwrap(),
1281 ts_language,
1282 highlight_map: Default::default(),
1283 })
1284 }),
1285 adapters: Vec::new(),
1286
1287 #[cfg(any(test, feature = "test-support"))]
1288 fake_adapter: None,
1289 }
1290 }
1291
1292 pub fn lsp_adapters(&self) -> &[Arc<CachedLspAdapter>] {
1293 &self.adapters
1294 }
1295
1296 pub fn id(&self) -> Option<usize> {
1297 self.grammar.as_ref().map(|g| g.id)
1298 }
1299
1300 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1301 if let Some(query) = queries.highlights {
1302 self = self
1303 .with_highlights_query(query.as_ref())
1304 .context("Error loading highlights query")?;
1305 }
1306 if let Some(query) = queries.brackets {
1307 self = self
1308 .with_brackets_query(query.as_ref())
1309 .context("Error loading brackets query")?;
1310 }
1311 if let Some(query) = queries.indents {
1312 self = self
1313 .with_indents_query(query.as_ref())
1314 .context("Error loading indents query")?;
1315 }
1316 if let Some(query) = queries.outline {
1317 self = self
1318 .with_outline_query(query.as_ref())
1319 .context("Error loading outline query")?;
1320 }
1321 if let Some(query) = queries.embedding {
1322 self = self
1323 .with_embedding_query(query.as_ref())
1324 .context("Error loading embedding query")?;
1325 }
1326 if let Some(query) = queries.injections {
1327 self = self
1328 .with_injection_query(query.as_ref())
1329 .context("Error loading injection query")?;
1330 }
1331 if let Some(query) = queries.overrides {
1332 self = self
1333 .with_override_query(query.as_ref())
1334 .context("Error loading override query")?;
1335 }
1336 Ok(self)
1337 }
1338
1339 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1340 let grammar = self.grammar_mut();
1341 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1342 Ok(self)
1343 }
1344
1345 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1346 let grammar = self.grammar_mut();
1347 let query = Query::new(&grammar.ts_language, source)?;
1348 let mut item_capture_ix = None;
1349 let mut name_capture_ix = None;
1350 let mut context_capture_ix = None;
1351 let mut extra_context_capture_ix = None;
1352 get_capture_indices(
1353 &query,
1354 &mut [
1355 ("item", &mut item_capture_ix),
1356 ("name", &mut name_capture_ix),
1357 ("context", &mut context_capture_ix),
1358 ("context.extra", &mut extra_context_capture_ix),
1359 ],
1360 );
1361 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1362 grammar.outline_config = Some(OutlineConfig {
1363 query,
1364 item_capture_ix,
1365 name_capture_ix,
1366 context_capture_ix,
1367 extra_context_capture_ix,
1368 });
1369 }
1370 Ok(self)
1371 }
1372
1373 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1374 let grammar = self.grammar_mut();
1375 let query = Query::new(&grammar.ts_language, source)?;
1376 let mut item_capture_ix = None;
1377 let mut name_capture_ix = None;
1378 let mut context_capture_ix = None;
1379 let mut collapse_capture_ix = None;
1380 let mut keep_capture_ix = None;
1381 get_capture_indices(
1382 &query,
1383 &mut [
1384 ("item", &mut item_capture_ix),
1385 ("name", &mut name_capture_ix),
1386 ("context", &mut context_capture_ix),
1387 ("keep", &mut keep_capture_ix),
1388 ("collapse", &mut collapse_capture_ix),
1389 ],
1390 );
1391 if let Some(item_capture_ix) = item_capture_ix {
1392 grammar.embedding_config = Some(EmbeddingConfig {
1393 query,
1394 item_capture_ix,
1395 name_capture_ix,
1396 context_capture_ix,
1397 collapse_capture_ix,
1398 keep_capture_ix,
1399 });
1400 }
1401 Ok(self)
1402 }
1403
1404 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1405 let grammar = self.grammar_mut();
1406 let query = Query::new(&grammar.ts_language, source)?;
1407 let mut open_capture_ix = None;
1408 let mut close_capture_ix = None;
1409 get_capture_indices(
1410 &query,
1411 &mut [
1412 ("open", &mut open_capture_ix),
1413 ("close", &mut close_capture_ix),
1414 ],
1415 );
1416 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1417 grammar.brackets_config = Some(BracketConfig {
1418 query,
1419 open_capture_ix,
1420 close_capture_ix,
1421 });
1422 }
1423 Ok(self)
1424 }
1425
1426 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1427 let grammar = self.grammar_mut();
1428 let query = Query::new(&grammar.ts_language, source)?;
1429 let mut indent_capture_ix = None;
1430 let mut start_capture_ix = None;
1431 let mut end_capture_ix = None;
1432 let mut outdent_capture_ix = None;
1433 get_capture_indices(
1434 &query,
1435 &mut [
1436 ("indent", &mut indent_capture_ix),
1437 ("start", &mut start_capture_ix),
1438 ("end", &mut end_capture_ix),
1439 ("outdent", &mut outdent_capture_ix),
1440 ],
1441 );
1442 if let Some(indent_capture_ix) = indent_capture_ix {
1443 grammar.indents_config = Some(IndentConfig {
1444 query,
1445 indent_capture_ix,
1446 start_capture_ix,
1447 end_capture_ix,
1448 outdent_capture_ix,
1449 });
1450 }
1451 Ok(self)
1452 }
1453
1454 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1455 let grammar = self.grammar_mut();
1456 let query = Query::new(&grammar.ts_language, source)?;
1457 let mut language_capture_ix = None;
1458 let mut content_capture_ix = None;
1459 get_capture_indices(
1460 &query,
1461 &mut [
1462 ("language", &mut language_capture_ix),
1463 ("content", &mut content_capture_ix),
1464 ],
1465 );
1466 let patterns = (0..query.pattern_count())
1467 .map(|ix| {
1468 let mut config = InjectionPatternConfig::default();
1469 for setting in query.property_settings(ix) {
1470 match setting.key.as_ref() {
1471 "language" => {
1472 config.language = setting.value.clone();
1473 }
1474 "combined" => {
1475 config.combined = true;
1476 }
1477 _ => {}
1478 }
1479 }
1480 config
1481 })
1482 .collect();
1483 if let Some(content_capture_ix) = content_capture_ix {
1484 grammar.injection_config = Some(InjectionConfig {
1485 query,
1486 language_capture_ix,
1487 content_capture_ix,
1488 patterns,
1489 });
1490 }
1491 Ok(self)
1492 }
1493
1494 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1495 let query = Query::new(&self.grammar_mut().ts_language, source)?;
1496
1497 let mut override_configs_by_id = HashMap::default();
1498 for (ix, name) in query.capture_names().iter().enumerate() {
1499 if !name.starts_with('_') {
1500 let value = self.config.overrides.remove(*name).unwrap_or_default();
1501 for server_name in &value.opt_into_language_servers {
1502 if !self
1503 .config
1504 .scope_opt_in_language_servers
1505 .contains(server_name)
1506 {
1507 util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1508 }
1509 }
1510
1511 override_configs_by_id.insert(ix as u32, (name.to_string(), value));
1512 }
1513 }
1514
1515 if !self.config.overrides.is_empty() {
1516 let keys = self.config.overrides.keys().collect::<Vec<_>>();
1517 Err(anyhow!(
1518 "language {:?} has overrides in config not in query: {keys:?}",
1519 self.config.name
1520 ))?;
1521 }
1522
1523 for disabled_scope_name in self
1524 .config
1525 .brackets
1526 .disabled_scopes_by_bracket_ix
1527 .iter()
1528 .flatten()
1529 {
1530 if !override_configs_by_id
1531 .values()
1532 .any(|(scope_name, _)| scope_name == disabled_scope_name)
1533 {
1534 Err(anyhow!(
1535 "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1536 self.config.name
1537 ))?;
1538 }
1539 }
1540
1541 for (name, override_config) in override_configs_by_id.values_mut() {
1542 override_config.disabled_bracket_ixs = self
1543 .config
1544 .brackets
1545 .disabled_scopes_by_bracket_ix
1546 .iter()
1547 .enumerate()
1548 .filter_map(|(ix, disabled_scope_names)| {
1549 if disabled_scope_names.contains(name) {
1550 Some(ix as u16)
1551 } else {
1552 None
1553 }
1554 })
1555 .collect();
1556 }
1557
1558 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1559 self.grammar_mut().override_config = Some(OverrideConfig {
1560 query,
1561 values: override_configs_by_id,
1562 });
1563 Ok(self)
1564 }
1565
1566 fn grammar_mut(&mut self) -> &mut Grammar {
1567 Arc::get_mut(self.grammar.as_mut().unwrap()).unwrap()
1568 }
1569
1570 pub async fn with_lsp_adapters(mut self, lsp_adapters: Vec<Arc<dyn LspAdapter>>) -> Self {
1571 for adapter in lsp_adapters {
1572 self.adapters.push(CachedLspAdapter::new(adapter).await);
1573 }
1574 self
1575 }
1576
1577 #[cfg(any(test, feature = "test-support"))]
1578 pub async fn set_fake_lsp_adapter(
1579 &mut self,
1580 fake_lsp_adapter: Arc<FakeLspAdapter>,
1581 ) -> mpsc::UnboundedReceiver<lsp::FakeLanguageServer> {
1582 let (servers_tx, servers_rx) = mpsc::unbounded();
1583 self.fake_adapter = Some((servers_tx, fake_lsp_adapter.clone()));
1584 let adapter = CachedLspAdapter::new(Arc::new(fake_lsp_adapter)).await;
1585 self.adapters = vec![adapter];
1586 servers_rx
1587 }
1588
1589 pub fn name(&self) -> Arc<str> {
1590 self.config.name.clone()
1591 }
1592
1593 pub async fn disk_based_diagnostic_sources(&self) -> &[String] {
1594 match self.adapters.first().as_ref() {
1595 Some(adapter) => &adapter.disk_based_diagnostic_sources,
1596 None => &[],
1597 }
1598 }
1599
1600 pub async fn disk_based_diagnostics_progress_token(&self) -> Option<&str> {
1601 for adapter in &self.adapters {
1602 let token = adapter.disk_based_diagnostics_progress_token.as_deref();
1603 if token.is_some() {
1604 return token;
1605 }
1606 }
1607
1608 None
1609 }
1610
1611 pub async fn process_completion(self: &Arc<Self>, completion: &mut lsp::CompletionItem) {
1612 for adapter in &self.adapters {
1613 adapter.process_completion(completion).await;
1614 }
1615 }
1616
1617 pub async fn label_for_completion(
1618 self: &Arc<Self>,
1619 completion: &lsp::CompletionItem,
1620 ) -> Option<CodeLabel> {
1621 self.adapters
1622 .first()
1623 .as_ref()?
1624 .label_for_completion(completion, self)
1625 .await
1626 }
1627
1628 pub async fn label_for_symbol(
1629 self: &Arc<Self>,
1630 name: &str,
1631 kind: lsp::SymbolKind,
1632 ) -> Option<CodeLabel> {
1633 self.adapters
1634 .first()
1635 .as_ref()?
1636 .label_for_symbol(name, kind, self)
1637 .await
1638 }
1639
1640 pub fn highlight_text<'a>(
1641 self: &'a Arc<Self>,
1642 text: &'a Rope,
1643 range: Range<usize>,
1644 ) -> Vec<(Range<usize>, HighlightId)> {
1645 let mut result = Vec::new();
1646 if let Some(grammar) = &self.grammar {
1647 let tree = grammar.parse_text(text, None);
1648 let captures =
1649 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1650 grammar.highlights_query.as_ref()
1651 });
1652 let highlight_maps = vec![grammar.highlight_map()];
1653 let mut offset = 0;
1654 for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1655 let end_offset = offset + chunk.text.len();
1656 if let Some(highlight_id) = chunk.syntax_highlight_id {
1657 if !highlight_id.is_default() {
1658 result.push((offset..end_offset, highlight_id));
1659 }
1660 }
1661 offset = end_offset;
1662 }
1663 }
1664 result
1665 }
1666
1667 pub fn path_suffixes(&self) -> &[String] {
1668 &self.config.path_suffixes
1669 }
1670
1671 pub fn should_autoclose_before(&self, c: char) -> bool {
1672 c.is_whitespace() || self.config.autoclose_before.contains(c)
1673 }
1674
1675 pub fn set_theme(&self, theme: &SyntaxTheme) {
1676 if let Some(grammar) = self.grammar.as_ref() {
1677 if let Some(highlights_query) = &grammar.highlights_query {
1678 *grammar.highlight_map.lock() =
1679 HighlightMap::new(highlights_query.capture_names(), theme);
1680 }
1681 }
1682 }
1683
1684 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1685 self.grammar.as_ref()
1686 }
1687
1688 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1689 LanguageScope {
1690 language: self.clone(),
1691 override_id: None,
1692 }
1693 }
1694
1695 pub fn prettier_parser_name(&self) -> Option<&str> {
1696 self.config.prettier_parser_name.as_deref()
1697 }
1698}
1699
1700impl LanguageScope {
1701 pub fn collapsed_placeholder(&self) -> &str {
1702 self.language.config.collapsed_placeholder.as_ref()
1703 }
1704
1705 /// Returns line prefix that is inserted in e.g. line continuations or
1706 /// in `toggle comments` action.
1707 pub fn line_comment_prefix(&self) -> Option<&Arc<str>> {
1708 Override::as_option(
1709 self.config_override().map(|o| &o.line_comment),
1710 self.language.config.line_comment.as_ref(),
1711 )
1712 }
1713
1714 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1715 Override::as_option(
1716 self.config_override().map(|o| &o.block_comment),
1717 self.language.config.block_comment.as_ref(),
1718 )
1719 .map(|e| (&e.0, &e.1))
1720 }
1721
1722 /// Returns a list of language-specific word characters.
1723 ///
1724 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1725 /// the purpose of actions like 'move to next word end` or whole-word search.
1726 /// It additionally accounts for language's additional word characters.
1727 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1728 Override::as_option(
1729 self.config_override().map(|o| &o.word_characters),
1730 Some(&self.language.config.word_characters),
1731 )
1732 }
1733
1734 /// Returns a list of bracket pairs for a given language with an additional
1735 /// piece of information about whether the particular bracket pair is currently active for a given language.
1736 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1737 let mut disabled_ids = self
1738 .config_override()
1739 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1740 self.language
1741 .config
1742 .brackets
1743 .pairs
1744 .iter()
1745 .enumerate()
1746 .map(move |(ix, bracket)| {
1747 let mut is_enabled = true;
1748 if let Some(next_disabled_ix) = disabled_ids.first() {
1749 if ix == *next_disabled_ix as usize {
1750 disabled_ids = &disabled_ids[1..];
1751 is_enabled = false;
1752 }
1753 }
1754 (bracket, is_enabled)
1755 })
1756 }
1757
1758 pub fn should_autoclose_before(&self, c: char) -> bool {
1759 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1760 }
1761
1762 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1763 let config = &self.language.config;
1764 let opt_in_servers = &config.scope_opt_in_language_servers;
1765 if opt_in_servers.iter().any(|o| *o == *name.0) {
1766 if let Some(over) = self.config_override() {
1767 over.opt_into_language_servers.iter().any(|o| *o == *name.0)
1768 } else {
1769 false
1770 }
1771 } else {
1772 true
1773 }
1774 }
1775
1776 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1777 let id = self.override_id?;
1778 let grammar = self.language.grammar.as_ref()?;
1779 let override_config = grammar.override_config.as_ref()?;
1780 override_config.values.get(&id).map(|e| &e.1)
1781 }
1782}
1783
1784impl Hash for Language {
1785 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1786 self.id().hash(state)
1787 }
1788}
1789
1790impl PartialEq for Language {
1791 fn eq(&self, other: &Self) -> bool {
1792 self.id().eq(&other.id())
1793 }
1794}
1795
1796impl Eq for Language {}
1797
1798impl Debug for Language {
1799 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1800 f.debug_struct("Language")
1801 .field("name", &self.config.name)
1802 .finish()
1803 }
1804}
1805
1806impl Grammar {
1807 pub fn id(&self) -> usize {
1808 self.id
1809 }
1810
1811 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1812 PARSER.with(|parser| {
1813 let mut parser = parser.borrow_mut();
1814 parser
1815 .set_language(&self.ts_language)
1816 .expect("incompatible grammar");
1817 let mut chunks = text.chunks_in_range(0..text.len());
1818 parser
1819 .parse_with(
1820 &mut move |offset, _| {
1821 chunks.seek(offset);
1822 chunks.next().unwrap_or("").as_bytes()
1823 },
1824 old_tree.as_ref(),
1825 )
1826 .unwrap()
1827 })
1828 }
1829
1830 pub fn highlight_map(&self) -> HighlightMap {
1831 self.highlight_map.lock().clone()
1832 }
1833
1834 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1835 let capture_id = self
1836 .highlights_query
1837 .as_ref()?
1838 .capture_index_for_name(name)?;
1839 Some(self.highlight_map.lock().get(capture_id))
1840 }
1841}
1842
1843impl CodeLabel {
1844 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1845 let mut result = Self {
1846 runs: Vec::new(),
1847 filter_range: 0..text.len(),
1848 text,
1849 };
1850 if let Some(filter_text) = filter_text {
1851 if let Some(ix) = result.text.find(filter_text) {
1852 result.filter_range = ix..ix + filter_text.len();
1853 }
1854 }
1855 result
1856 }
1857}
1858
1859#[cfg(any(test, feature = "test-support"))]
1860impl Default for FakeLspAdapter {
1861 fn default() -> Self {
1862 Self {
1863 name: "the-fake-language-server",
1864 capabilities: lsp::LanguageServer::full_capabilities(),
1865 initializer: None,
1866 disk_based_diagnostics_progress_token: None,
1867 initialization_options: None,
1868 disk_based_diagnostics_sources: Vec::new(),
1869 prettier_plugins: Vec::new(),
1870 }
1871 }
1872}
1873
1874#[cfg(any(test, feature = "test-support"))]
1875#[async_trait]
1876impl LspAdapter for Arc<FakeLspAdapter> {
1877 async fn name(&self) -> LanguageServerName {
1878 LanguageServerName(self.name.into())
1879 }
1880
1881 fn short_name(&self) -> &'static str {
1882 "FakeLspAdapter"
1883 }
1884
1885 async fn fetch_latest_server_version(
1886 &self,
1887 _: &dyn LspAdapterDelegate,
1888 ) -> Result<Box<dyn 'static + Send + Any>> {
1889 unreachable!();
1890 }
1891
1892 async fn fetch_server_binary(
1893 &self,
1894 _: Box<dyn 'static + Send + Any>,
1895 _: PathBuf,
1896 _: &dyn LspAdapterDelegate,
1897 ) -> Result<LanguageServerBinary> {
1898 unreachable!();
1899 }
1900
1901 async fn cached_server_binary(
1902 &self,
1903 _: PathBuf,
1904 _: &dyn LspAdapterDelegate,
1905 ) -> Option<LanguageServerBinary> {
1906 unreachable!();
1907 }
1908
1909 async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1910 unreachable!();
1911 }
1912
1913 fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1914
1915 async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1916 self.disk_based_diagnostics_sources.clone()
1917 }
1918
1919 async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1920 self.disk_based_diagnostics_progress_token.clone()
1921 }
1922
1923 async fn initialization_options(&self) -> Option<Value> {
1924 self.initialization_options.clone()
1925 }
1926
1927 fn prettier_plugins(&self) -> &[&'static str] {
1928 &self.prettier_plugins
1929 }
1930}
1931
1932fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1933 for (ix, name) in query.capture_names().iter().enumerate() {
1934 for (capture_name, index) in captures.iter_mut() {
1935 if capture_name == name {
1936 **index = Some(ix as u32);
1937 break;
1938 }
1939 }
1940 }
1941}
1942
1943pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1944 lsp::Position::new(point.row, point.column)
1945}
1946
1947pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1948 Unclipped(PointUtf16::new(point.line, point.character))
1949}
1950
1951pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1952 lsp::Range {
1953 start: point_to_lsp(range.start),
1954 end: point_to_lsp(range.end),
1955 }
1956}
1957
1958pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1959 let mut start = point_from_lsp(range.start);
1960 let mut end = point_from_lsp(range.end);
1961 if start > end {
1962 mem::swap(&mut start, &mut end);
1963 }
1964 start..end
1965}
1966
1967#[cfg(test)]
1968mod tests {
1969 use super::*;
1970 use gpui::TestAppContext;
1971
1972 #[gpui::test(iterations = 10)]
1973 async fn test_first_line_pattern(cx: &mut TestAppContext) {
1974 let mut languages = LanguageRegistry::test();
1975
1976 languages.set_executor(cx.executor());
1977 let languages = Arc::new(languages);
1978 languages.register(
1979 "/javascript",
1980 LanguageConfig {
1981 name: "JavaScript".into(),
1982 path_suffixes: vec!["js".into()],
1983 first_line_pattern: Some(Regex::new(r"\bnode\b").unwrap()),
1984 ..Default::default()
1985 },
1986 tree_sitter_typescript::language_tsx(),
1987 vec![],
1988 |_| Default::default(),
1989 );
1990
1991 languages
1992 .language_for_file("the/script", None)
1993 .await
1994 .unwrap_err();
1995 languages
1996 .language_for_file("the/script", Some(&"nothing".into()))
1997 .await
1998 .unwrap_err();
1999 assert_eq!(
2000 languages
2001 .language_for_file("the/script", Some(&"#!/bin/env node".into()))
2002 .await
2003 .unwrap()
2004 .name()
2005 .as_ref(),
2006 "JavaScript"
2007 );
2008 }
2009
2010 #[gpui::test(iterations = 10)]
2011 async fn test_language_loading(cx: &mut TestAppContext) {
2012 let mut languages = LanguageRegistry::test();
2013 languages.set_executor(cx.executor());
2014 let languages = Arc::new(languages);
2015 languages.register(
2016 "/JSON",
2017 LanguageConfig {
2018 name: "JSON".into(),
2019 path_suffixes: vec!["json".into()],
2020 ..Default::default()
2021 },
2022 tree_sitter_json::language(),
2023 vec![],
2024 |_| Default::default(),
2025 );
2026 languages.register(
2027 "/rust",
2028 LanguageConfig {
2029 name: "Rust".into(),
2030 path_suffixes: vec!["rs".into()],
2031 ..Default::default()
2032 },
2033 tree_sitter_rust::language(),
2034 vec![],
2035 |_| Default::default(),
2036 );
2037 assert_eq!(
2038 languages.language_names(),
2039 &[
2040 "JSON".to_string(),
2041 "Plain Text".to_string(),
2042 "Rust".to_string(),
2043 ]
2044 );
2045
2046 let rust1 = languages.language_for_name("Rust");
2047 let rust2 = languages.language_for_name("Rust");
2048
2049 // Ensure language is still listed even if it's being loaded.
2050 assert_eq!(
2051 languages.language_names(),
2052 &[
2053 "JSON".to_string(),
2054 "Plain Text".to_string(),
2055 "Rust".to_string(),
2056 ]
2057 );
2058
2059 let (rust1, rust2) = futures::join!(rust1, rust2);
2060 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2061
2062 // Ensure language is still listed even after loading it.
2063 assert_eq!(
2064 languages.language_names(),
2065 &[
2066 "JSON".to_string(),
2067 "Plain Text".to_string(),
2068 "Rust".to_string(),
2069 ]
2070 );
2071
2072 // Loading an unknown language returns an error.
2073 assert!(languages.language_for_name("Unknown").await.is_err());
2074 }
2075}