language.rs

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