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