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