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