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