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