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