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        None
 554    }
 555
 556    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
 557        Default::default()
 558    }
 559
 560    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
 561        None
 562    }
 563
 564    fn language_ids(&self) -> HashMap<String, String> {
 565        Default::default()
 566    }
 567
 568    /// Support custom initialize params.
 569    fn prepare_initialize_params(
 570        &self,
 571        original: InitializeParams,
 572        _: &App,
 573    ) -> Result<InitializeParams> {
 574        Ok(original)
 575    }
 576
 577    fn attach_kind(&self) -> Attach {
 578        Attach::Shared
 579    }
 580
 581    fn manifest_name(&self) -> Option<ManifestName> {
 582        None
 583    }
 584
 585    /// Method only implemented by the default JSON language server adapter.
 586    /// Used to provide dynamic reloading of the JSON schemas used to
 587    /// provide autocompletion and diagnostics in Zed setting and keybind
 588    /// files
 589    fn is_primary_zed_json_schema_adapter(&self) -> bool {
 590        false
 591    }
 592
 593    /// Method only implemented by the default JSON language server adapter.
 594    /// Used to clear the cache of JSON schemas that are used to provide
 595    /// autocompletion and diagnostics in Zed settings and keybinds files.
 596    /// Should not be called unless the callee is sure that
 597    /// `Self::is_primary_zed_json_schema_adapter` returns `true`
 598    async fn clear_zed_json_schema_cache(&self) {
 599        unreachable!(
 600            "Not implemented for this adapter. This method should only be called on the default JSON language server adapter"
 601        );
 602    }
 603}
 604
 605async fn try_fetch_server_binary<L: LspAdapter + 'static + Send + Sync + ?Sized>(
 606    adapter: &L,
 607    delegate: &Arc<dyn LspAdapterDelegate>,
 608    container_dir: PathBuf,
 609    cx: &mut AsyncApp,
 610) -> Result<LanguageServerBinary> {
 611    if let Some(task) = adapter.will_fetch_server(delegate, cx) {
 612        task.await?;
 613    }
 614
 615    let name = adapter.name();
 616    log::info!("fetching latest version of language server {:?}", name.0);
 617    delegate.update_status(name.clone(), BinaryStatus::CheckingForUpdate);
 618
 619    let latest_version = adapter
 620        .fetch_latest_server_version(delegate.as_ref())
 621        .await?;
 622
 623    if let Some(binary) = adapter
 624        .check_if_version_installed(latest_version.as_ref(), &container_dir, delegate.as_ref())
 625        .await
 626    {
 627        log::info!("language server {:?} is already installed", name.0);
 628        delegate.update_status(name.clone(), BinaryStatus::None);
 629        Ok(binary)
 630    } else {
 631        log::info!("downloading language server {:?}", name.0);
 632        delegate.update_status(adapter.name(), BinaryStatus::Downloading);
 633        let binary = adapter
 634            .fetch_server_binary(latest_version, container_dir, delegate.as_ref())
 635            .await;
 636
 637        delegate.update_status(name.clone(), BinaryStatus::None);
 638        binary
 639    }
 640}
 641
 642#[derive(Clone, Debug, Default, PartialEq, Eq)]
 643pub struct CodeLabel {
 644    /// The text to display.
 645    pub text: String,
 646    /// Syntax highlighting runs.
 647    pub runs: Vec<(Range<usize>, HighlightId)>,
 648    /// The portion of the text that should be used in fuzzy filtering.
 649    pub filter_range: Range<usize>,
 650}
 651
 652#[derive(Clone, Deserialize, JsonSchema)]
 653pub struct LanguageConfig {
 654    /// Human-readable name of the language.
 655    pub name: LanguageName,
 656    /// The name of this language for a Markdown code fence block
 657    pub code_fence_block_name: Option<Arc<str>>,
 658    // The name of the grammar in a WASM bundle (experimental).
 659    pub grammar: Option<Arc<str>>,
 660    /// The criteria for matching this language to a given file.
 661    #[serde(flatten)]
 662    pub matcher: LanguageMatcher,
 663    /// List of bracket types in a language.
 664    #[serde(default)]
 665    #[schemars(schema_with = "bracket_pair_config_json_schema")]
 666    pub brackets: BracketPairConfig,
 667    /// If set to true, auto indentation uses last non empty line to determine
 668    /// the indentation level for a new line.
 669    #[serde(default = "auto_indent_using_last_non_empty_line_default")]
 670    pub auto_indent_using_last_non_empty_line: bool,
 671    // Whether indentation of pasted content should be adjusted based on the context.
 672    #[serde(default)]
 673    pub auto_indent_on_paste: Option<bool>,
 674    /// A regex that is used to determine whether the indentation level should be
 675    /// increased in the following line.
 676    #[serde(default, deserialize_with = "deserialize_regex")]
 677    #[schemars(schema_with = "regex_json_schema")]
 678    pub increase_indent_pattern: Option<Regex>,
 679    /// A regex that is used to determine whether the indentation level should be
 680    /// decreased in the following line.
 681    #[serde(default, deserialize_with = "deserialize_regex")]
 682    #[schemars(schema_with = "regex_json_schema")]
 683    pub decrease_indent_pattern: Option<Regex>,
 684    /// A list of characters that trigger the automatic insertion of a closing
 685    /// bracket when they immediately precede the point where an opening
 686    /// bracket is inserted.
 687    #[serde(default)]
 688    pub autoclose_before: String,
 689    /// A placeholder used internally by Semantic Index.
 690    #[serde(default)]
 691    pub collapsed_placeholder: String,
 692    /// A line comment string that is inserted in e.g. `toggle comments` action.
 693    /// A language can have multiple flavours of line comments. All of the provided line comments are
 694    /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
 695    #[serde(default)]
 696    pub line_comments: Vec<Arc<str>>,
 697    /// Starting and closing characters of a block comment.
 698    #[serde(default)]
 699    pub block_comment: Option<(Arc<str>, Arc<str>)>,
 700    /// A list of language servers that are allowed to run on subranges of a given language.
 701    #[serde(default)]
 702    pub scope_opt_in_language_servers: Vec<LanguageServerName>,
 703    #[serde(default)]
 704    pub overrides: HashMap<String, LanguageConfigOverride>,
 705    /// A list of characters that Zed should treat as word characters for the
 706    /// purpose of features that operate on word boundaries, like 'move to next word end'
 707    /// or a whole-word search in buffer search.
 708    #[serde(default)]
 709    pub word_characters: HashSet<char>,
 710    /// Whether to indent lines using tab characters, as opposed to multiple
 711    /// spaces.
 712    #[serde(default)]
 713    pub hard_tabs: Option<bool>,
 714    /// How many columns a tab should occupy.
 715    #[serde(default)]
 716    pub tab_size: Option<NonZeroU32>,
 717    /// How to soft-wrap long lines of text.
 718    #[serde(default)]
 719    pub soft_wrap: Option<SoftWrap>,
 720    /// The name of a Prettier parser that will be used for this language when no file path is available.
 721    /// If there's a parser name in the language settings, that will be used instead.
 722    #[serde(default)]
 723    pub prettier_parser_name: Option<String>,
 724    /// If true, this language is only for syntax highlighting via an injection into other
 725    /// languages, but should not appear to the user as a distinct language.
 726    #[serde(default)]
 727    pub hidden: bool,
 728    /// If configured, this language contains JSX style tags, and should support auto-closing of those tags.
 729    #[serde(default)]
 730    pub jsx_tag_auto_close: Option<JsxTagAutoCloseConfig>,
 731    /// A list of characters that Zed should treat as word characters for completion queries.
 732    #[serde(default)]
 733    pub completion_query_characters: HashSet<char>,
 734}
 735
 736#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
 737pub struct LanguageMatcher {
 738    /// 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`.
 739    #[serde(default)]
 740    pub path_suffixes: Vec<String>,
 741    /// A regex pattern that determines whether the language should be assigned to a file or not.
 742    #[serde(
 743        default,
 744        serialize_with = "serialize_regex",
 745        deserialize_with = "deserialize_regex"
 746    )]
 747    #[schemars(schema_with = "regex_json_schema")]
 748    pub first_line_pattern: Option<Regex>,
 749}
 750
 751/// The configuration for JSX tag auto-closing.
 752#[derive(Clone, Deserialize, JsonSchema)]
 753pub struct JsxTagAutoCloseConfig {
 754    /// The name of the node for a opening tag
 755    pub open_tag_node_name: String,
 756    /// The name of the node for an closing tag
 757    pub close_tag_node_name: String,
 758    /// The name of the node for a complete element with children for open and close tags
 759    pub jsx_element_node_name: String,
 760    /// The name of the node found within both opening and closing
 761    /// tags that describes the tag name
 762    pub tag_name_node_name: String,
 763    /// Alternate Node names for tag names.
 764    /// Specifically needed as TSX represents the name in `<Foo.Bar>`
 765    /// as `member_expression` rather than `identifier` as usual
 766    #[serde(default)]
 767    pub tag_name_node_name_alternates: Vec<String>,
 768    /// Some grammars are smart enough to detect a closing tag
 769    /// that is not valid i.e. doesn't match it's corresponding
 770    /// opening tag or does not have a corresponding opening tag
 771    /// This should be set to the name of the node for invalid
 772    /// closing tags if the grammar contains such a node, otherwise
 773    /// detecting already closed tags will not work properly
 774    #[serde(default)]
 775    pub erroneous_close_tag_node_name: Option<String>,
 776    /// See above for erroneous_close_tag_node_name for details
 777    /// This should be set if the node used for the tag name
 778    /// within erroneous closing tags is different from the
 779    /// normal tag name node name
 780    #[serde(default)]
 781    pub erroneous_close_tag_name_node_name: Option<String>,
 782}
 783
 784/// Represents a language for the given range. Some languages (e.g. HTML)
 785/// interleave several languages together, thus a single buffer might actually contain
 786/// several nested scopes.
 787#[derive(Clone, Debug)]
 788pub struct LanguageScope {
 789    language: Arc<Language>,
 790    override_id: Option<u32>,
 791}
 792
 793#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
 794pub struct LanguageConfigOverride {
 795    #[serde(default)]
 796    pub line_comments: Override<Vec<Arc<str>>>,
 797    #[serde(default)]
 798    pub block_comment: Override<(Arc<str>, Arc<str>)>,
 799    #[serde(skip)]
 800    pub disabled_bracket_ixs: Vec<u16>,
 801    #[serde(default)]
 802    pub word_characters: Override<HashSet<char>>,
 803    #[serde(default)]
 804    pub completion_query_characters: Override<HashSet<char>>,
 805    #[serde(default)]
 806    pub opt_into_language_servers: Vec<LanguageServerName>,
 807}
 808
 809#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
 810#[serde(untagged)]
 811pub enum Override<T> {
 812    Remove { remove: bool },
 813    Set(T),
 814}
 815
 816impl<T> Default for Override<T> {
 817    fn default() -> Self {
 818        Override::Remove { remove: false }
 819    }
 820}
 821
 822impl<T> Override<T> {
 823    fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
 824        match this {
 825            Some(Self::Set(value)) => Some(value),
 826            Some(Self::Remove { remove: true }) => None,
 827            Some(Self::Remove { remove: false }) | None => original,
 828        }
 829    }
 830}
 831
 832impl Default for LanguageConfig {
 833    fn default() -> Self {
 834        Self {
 835            name: LanguageName::new(""),
 836            code_fence_block_name: None,
 837            grammar: None,
 838            matcher: LanguageMatcher::default(),
 839            brackets: Default::default(),
 840            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
 841            auto_indent_on_paste: None,
 842            increase_indent_pattern: Default::default(),
 843            decrease_indent_pattern: Default::default(),
 844            autoclose_before: Default::default(),
 845            line_comments: Default::default(),
 846            block_comment: Default::default(),
 847            scope_opt_in_language_servers: Default::default(),
 848            overrides: Default::default(),
 849            word_characters: Default::default(),
 850            collapsed_placeholder: Default::default(),
 851            hard_tabs: None,
 852            tab_size: None,
 853            soft_wrap: None,
 854            prettier_parser_name: None,
 855            hidden: false,
 856            jsx_tag_auto_close: None,
 857            completion_query_characters: Default::default(),
 858        }
 859    }
 860}
 861
 862fn auto_indent_using_last_non_empty_line_default() -> bool {
 863    true
 864}
 865
 866fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
 867    let source = Option::<String>::deserialize(d)?;
 868    if let Some(source) = source {
 869        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
 870    } else {
 871        Ok(None)
 872    }
 873}
 874
 875fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
 876    Schema::Object(SchemaObject {
 877        instance_type: Some(InstanceType::String.into()),
 878        ..Default::default()
 879    })
 880}
 881
 882fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
 883where
 884    S: Serializer,
 885{
 886    match regex {
 887        Some(regex) => serializer.serialize_str(regex.as_str()),
 888        None => serializer.serialize_none(),
 889    }
 890}
 891
 892#[doc(hidden)]
 893#[cfg(any(test, feature = "test-support"))]
 894pub struct FakeLspAdapter {
 895    pub name: &'static str,
 896    pub initialization_options: Option<Value>,
 897    pub prettier_plugins: Vec<&'static str>,
 898    pub disk_based_diagnostics_progress_token: Option<String>,
 899    pub disk_based_diagnostics_sources: Vec<String>,
 900    pub language_server_binary: LanguageServerBinary,
 901
 902    pub capabilities: lsp::ServerCapabilities,
 903    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
 904    pub label_for_completion: Option<
 905        Box<
 906            dyn 'static
 907                + Send
 908                + Sync
 909                + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
 910        >,
 911    >,
 912}
 913
 914/// Configuration of handling bracket pairs for a given language.
 915///
 916/// This struct includes settings for defining which pairs of characters are considered brackets and
 917/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
 918#[derive(Clone, Debug, Default, JsonSchema)]
 919pub struct BracketPairConfig {
 920    /// A list of character pairs that should be treated as brackets in the context of a given language.
 921    pub pairs: Vec<BracketPair>,
 922    /// A list of tree-sitter scopes for which a given bracket should not be active.
 923    /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
 924    #[serde(skip)]
 925    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
 926}
 927
 928impl BracketPairConfig {
 929    pub fn is_closing_brace(&self, c: char) -> bool {
 930        self.pairs.iter().any(|pair| pair.end.starts_with(c))
 931    }
 932}
 933
 934fn bracket_pair_config_json_schema(r#gen: &mut SchemaGenerator) -> Schema {
 935    Option::<Vec<BracketPairContent>>::json_schema(r#gen)
 936}
 937
 938#[derive(Deserialize, JsonSchema)]
 939pub struct BracketPairContent {
 940    #[serde(flatten)]
 941    pub bracket_pair: BracketPair,
 942    #[serde(default)]
 943    pub not_in: Vec<String>,
 944}
 945
 946impl<'de> Deserialize<'de> for BracketPairConfig {
 947    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 948    where
 949        D: Deserializer<'de>,
 950    {
 951        let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
 952        let mut brackets = Vec::with_capacity(result.len());
 953        let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
 954        for entry in result {
 955            brackets.push(entry.bracket_pair);
 956            disabled_scopes_by_bracket_ix.push(entry.not_in);
 957        }
 958
 959        Ok(BracketPairConfig {
 960            pairs: brackets,
 961            disabled_scopes_by_bracket_ix,
 962        })
 963    }
 964}
 965
 966/// Describes a single bracket pair and how an editor should react to e.g. inserting
 967/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
 968#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
 969pub struct BracketPair {
 970    /// Starting substring for a bracket.
 971    pub start: String,
 972    /// Ending substring for a bracket.
 973    pub end: String,
 974    /// True if `end` should be automatically inserted right after `start` characters.
 975    pub close: bool,
 976    /// True if selected text should be surrounded by `start` and `end` characters.
 977    #[serde(default = "default_true")]
 978    pub surround: bool,
 979    /// True if an extra newline should be inserted while the cursor is in the middle
 980    /// of that bracket pair.
 981    pub newline: bool,
 982}
 983
 984#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 985pub struct LanguageId(usize);
 986
 987impl LanguageId {
 988    pub(crate) fn new() -> Self {
 989        Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
 990    }
 991}
 992
 993pub struct Language {
 994    pub(crate) id: LanguageId,
 995    pub(crate) config: LanguageConfig,
 996    pub(crate) grammar: Option<Arc<Grammar>>,
 997    pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
 998    pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
 999}
1000
1001#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1002pub struct GrammarId(pub usize);
1003
1004impl GrammarId {
1005    pub(crate) fn new() -> Self {
1006        Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
1007    }
1008}
1009
1010pub struct Grammar {
1011    id: GrammarId,
1012    pub ts_language: tree_sitter::Language,
1013    pub(crate) error_query: Option<Query>,
1014    pub(crate) highlights_query: Option<Query>,
1015    pub(crate) brackets_config: Option<BracketsConfig>,
1016    pub(crate) redactions_config: Option<RedactionConfig>,
1017    pub(crate) runnable_config: Option<RunnableConfig>,
1018    pub(crate) debug_variables_config: Option<DebugVariablesConfig>,
1019    pub(crate) indents_config: Option<IndentConfig>,
1020    pub outline_config: Option<OutlineConfig>,
1021    pub text_object_config: Option<TextObjectConfig>,
1022    pub embedding_config: Option<EmbeddingConfig>,
1023    pub(crate) injection_config: Option<InjectionConfig>,
1024    pub(crate) override_config: Option<OverrideConfig>,
1025    pub(crate) highlight_map: Mutex<HighlightMap>,
1026}
1027
1028struct IndentConfig {
1029    query: Query,
1030    indent_capture_ix: u32,
1031    start_capture_ix: Option<u32>,
1032    end_capture_ix: Option<u32>,
1033    outdent_capture_ix: Option<u32>,
1034}
1035
1036pub struct OutlineConfig {
1037    pub query: Query,
1038    pub item_capture_ix: u32,
1039    pub name_capture_ix: u32,
1040    pub context_capture_ix: Option<u32>,
1041    pub extra_context_capture_ix: Option<u32>,
1042    pub open_capture_ix: Option<u32>,
1043    pub close_capture_ix: Option<u32>,
1044    pub annotation_capture_ix: Option<u32>,
1045}
1046
1047#[derive(Debug, Clone, Copy, PartialEq)]
1048pub enum TextObject {
1049    InsideFunction,
1050    AroundFunction,
1051    InsideClass,
1052    AroundClass,
1053    InsideComment,
1054    AroundComment,
1055}
1056
1057impl TextObject {
1058    pub fn from_capture_name(name: &str) -> Option<TextObject> {
1059        match name {
1060            "function.inside" => Some(TextObject::InsideFunction),
1061            "function.around" => Some(TextObject::AroundFunction),
1062            "class.inside" => Some(TextObject::InsideClass),
1063            "class.around" => Some(TextObject::AroundClass),
1064            "comment.inside" => Some(TextObject::InsideComment),
1065            "comment.around" => Some(TextObject::AroundComment),
1066            _ => None,
1067        }
1068    }
1069
1070    pub fn around(&self) -> Option<Self> {
1071        match self {
1072            TextObject::InsideFunction => Some(TextObject::AroundFunction),
1073            TextObject::InsideClass => Some(TextObject::AroundClass),
1074            TextObject::InsideComment => Some(TextObject::AroundComment),
1075            _ => None,
1076        }
1077    }
1078}
1079
1080pub struct TextObjectConfig {
1081    pub query: Query,
1082    pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1083}
1084
1085#[derive(Debug)]
1086pub struct EmbeddingConfig {
1087    pub query: Query,
1088    pub item_capture_ix: u32,
1089    pub name_capture_ix: Option<u32>,
1090    pub context_capture_ix: Option<u32>,
1091    pub collapse_capture_ix: Option<u32>,
1092    pub keep_capture_ix: Option<u32>,
1093}
1094
1095struct InjectionConfig {
1096    query: Query,
1097    content_capture_ix: u32,
1098    language_capture_ix: Option<u32>,
1099    patterns: Vec<InjectionPatternConfig>,
1100}
1101
1102struct RedactionConfig {
1103    pub query: Query,
1104    pub redaction_capture_ix: u32,
1105}
1106
1107#[derive(Clone, Debug, PartialEq)]
1108enum RunnableCapture {
1109    Named(SharedString),
1110    Run,
1111}
1112
1113struct RunnableConfig {
1114    pub query: Query,
1115    /// A mapping from capture indice to capture kind
1116    pub extra_captures: Vec<RunnableCapture>,
1117}
1118
1119#[derive(Clone, Debug, PartialEq)]
1120enum DebugVariableCapture {
1121    Named(SharedString),
1122    Variable,
1123}
1124
1125#[derive(Debug)]
1126struct DebugVariablesConfig {
1127    pub query: Query,
1128    pub captures: Vec<DebugVariableCapture>,
1129}
1130
1131struct OverrideConfig {
1132    query: Query,
1133    values: HashMap<u32, OverrideEntry>,
1134}
1135
1136#[derive(Debug)]
1137struct OverrideEntry {
1138    name: String,
1139    range_is_inclusive: bool,
1140    value: LanguageConfigOverride,
1141}
1142
1143#[derive(Default, Clone)]
1144struct InjectionPatternConfig {
1145    language: Option<Box<str>>,
1146    combined: bool,
1147}
1148
1149struct BracketsConfig {
1150    query: Query,
1151    open_capture_ix: u32,
1152    close_capture_ix: u32,
1153    patterns: Vec<BracketsPatternConfig>,
1154}
1155
1156#[derive(Clone, Debug, Default)]
1157struct BracketsPatternConfig {
1158    newline_only: bool,
1159}
1160
1161impl Language {
1162    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1163        Self::new_with_id(LanguageId::new(), config, ts_language)
1164    }
1165
1166    pub fn id(&self) -> LanguageId {
1167        self.id
1168    }
1169
1170    fn new_with_id(
1171        id: LanguageId,
1172        config: LanguageConfig,
1173        ts_language: Option<tree_sitter::Language>,
1174    ) -> Self {
1175        Self {
1176            id,
1177            config,
1178            grammar: ts_language.map(|ts_language| {
1179                Arc::new(Grammar {
1180                    id: GrammarId::new(),
1181                    highlights_query: None,
1182                    brackets_config: None,
1183                    outline_config: None,
1184                    text_object_config: None,
1185                    embedding_config: None,
1186                    indents_config: None,
1187                    injection_config: None,
1188                    override_config: None,
1189                    redactions_config: None,
1190                    runnable_config: None,
1191                    debug_variables_config: None,
1192                    error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1193                    ts_language,
1194                    highlight_map: Default::default(),
1195                })
1196            }),
1197            context_provider: None,
1198            toolchain: None,
1199        }
1200    }
1201
1202    pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1203        self.context_provider = provider;
1204        self
1205    }
1206
1207    pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1208        self.toolchain = provider;
1209        self
1210    }
1211
1212    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1213        if let Some(query) = queries.highlights {
1214            self = self
1215                .with_highlights_query(query.as_ref())
1216                .context("Error loading highlights query")?;
1217        }
1218        if let Some(query) = queries.brackets {
1219            self = self
1220                .with_brackets_query(query.as_ref())
1221                .context("Error loading brackets query")?;
1222        }
1223        if let Some(query) = queries.indents {
1224            self = self
1225                .with_indents_query(query.as_ref())
1226                .context("Error loading indents query")?;
1227        }
1228        if let Some(query) = queries.outline {
1229            self = self
1230                .with_outline_query(query.as_ref())
1231                .context("Error loading outline query")?;
1232        }
1233        if let Some(query) = queries.embedding {
1234            self = self
1235                .with_embedding_query(query.as_ref())
1236                .context("Error loading embedding query")?;
1237        }
1238        if let Some(query) = queries.injections {
1239            self = self
1240                .with_injection_query(query.as_ref())
1241                .context("Error loading injection query")?;
1242        }
1243        if let Some(query) = queries.overrides {
1244            self = self
1245                .with_override_query(query.as_ref())
1246                .context("Error loading override query")?;
1247        }
1248        if let Some(query) = queries.redactions {
1249            self = self
1250                .with_redaction_query(query.as_ref())
1251                .context("Error loading redaction query")?;
1252        }
1253        if let Some(query) = queries.runnables {
1254            self = self
1255                .with_runnable_query(query.as_ref())
1256                .context("Error loading runnables query")?;
1257        }
1258        if let Some(query) = queries.text_objects {
1259            self = self
1260                .with_text_object_query(query.as_ref())
1261                .context("Error loading textobject query")?;
1262        }
1263        if let Some(query) = queries.debug_variables {
1264            self = self
1265                .with_debug_variables_query(query.as_ref())
1266                .context("Error loading debug variable query")?;
1267        }
1268        Ok(self)
1269    }
1270
1271    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1272        let grammar = self
1273            .grammar_mut()
1274            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1275        grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1276        Ok(self)
1277    }
1278
1279    pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1280        let grammar = self
1281            .grammar_mut()
1282            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1283
1284        let query = Query::new(&grammar.ts_language, source)?;
1285        let mut extra_captures = Vec::with_capacity(query.capture_names().len());
1286
1287        for name in query.capture_names().iter() {
1288            let kind = if *name == "run" {
1289                RunnableCapture::Run
1290            } else {
1291                RunnableCapture::Named(name.to_string().into())
1292            };
1293            extra_captures.push(kind);
1294        }
1295
1296        grammar.runnable_config = Some(RunnableConfig {
1297            extra_captures,
1298            query,
1299        });
1300
1301        Ok(self)
1302    }
1303
1304    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1305        let grammar = self
1306            .grammar_mut()
1307            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1308        let query = Query::new(&grammar.ts_language, source)?;
1309        let mut item_capture_ix = None;
1310        let mut name_capture_ix = None;
1311        let mut context_capture_ix = None;
1312        let mut extra_context_capture_ix = None;
1313        let mut open_capture_ix = None;
1314        let mut close_capture_ix = None;
1315        let mut annotation_capture_ix = None;
1316        get_capture_indices(
1317            &query,
1318            &mut [
1319                ("item", &mut item_capture_ix),
1320                ("name", &mut name_capture_ix),
1321                ("context", &mut context_capture_ix),
1322                ("context.extra", &mut extra_context_capture_ix),
1323                ("open", &mut open_capture_ix),
1324                ("close", &mut close_capture_ix),
1325                ("annotation", &mut annotation_capture_ix),
1326            ],
1327        );
1328        if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1329            grammar.outline_config = Some(OutlineConfig {
1330                query,
1331                item_capture_ix,
1332                name_capture_ix,
1333                context_capture_ix,
1334                extra_context_capture_ix,
1335                open_capture_ix,
1336                close_capture_ix,
1337                annotation_capture_ix,
1338            });
1339        }
1340        Ok(self)
1341    }
1342
1343    pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1344        let grammar = self
1345            .grammar_mut()
1346            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1347        let query = Query::new(&grammar.ts_language, source)?;
1348
1349        let mut text_objects_by_capture_ix = Vec::new();
1350        for (ix, name) in query.capture_names().iter().enumerate() {
1351            if let Some(text_object) = TextObject::from_capture_name(name) {
1352                text_objects_by_capture_ix.push((ix as u32, text_object));
1353            }
1354        }
1355
1356        grammar.text_object_config = Some(TextObjectConfig {
1357            query,
1358            text_objects_by_capture_ix,
1359        });
1360        Ok(self)
1361    }
1362
1363    pub fn with_debug_variables_query(mut self, source: &str) -> Result<Self> {
1364        let grammar = self
1365            .grammar_mut()
1366            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1367        let query = Query::new(&grammar.ts_language, source)?;
1368
1369        let mut captures = Vec::new();
1370        for name in query.capture_names() {
1371            captures.push(if *name == "debug_variable" {
1372                DebugVariableCapture::Variable
1373            } else {
1374                DebugVariableCapture::Named(name.to_string().into())
1375            });
1376        }
1377        grammar.debug_variables_config = Some(DebugVariablesConfig { query, captures });
1378
1379        Ok(self)
1380    }
1381
1382    pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1383        let grammar = self
1384            .grammar_mut()
1385            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1386        let query = Query::new(&grammar.ts_language, source)?;
1387        let mut item_capture_ix = None;
1388        let mut name_capture_ix = None;
1389        let mut context_capture_ix = None;
1390        let mut collapse_capture_ix = None;
1391        let mut keep_capture_ix = None;
1392        get_capture_indices(
1393            &query,
1394            &mut [
1395                ("item", &mut item_capture_ix),
1396                ("name", &mut name_capture_ix),
1397                ("context", &mut context_capture_ix),
1398                ("keep", &mut keep_capture_ix),
1399                ("collapse", &mut collapse_capture_ix),
1400            ],
1401        );
1402        if let Some(item_capture_ix) = item_capture_ix {
1403            grammar.embedding_config = Some(EmbeddingConfig {
1404                query,
1405                item_capture_ix,
1406                name_capture_ix,
1407                context_capture_ix,
1408                collapse_capture_ix,
1409                keep_capture_ix,
1410            });
1411        }
1412        Ok(self)
1413    }
1414
1415    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1416        let grammar = self
1417            .grammar_mut()
1418            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1419        let query = Query::new(&grammar.ts_language, source)?;
1420        let mut open_capture_ix = None;
1421        let mut close_capture_ix = None;
1422        get_capture_indices(
1423            &query,
1424            &mut [
1425                ("open", &mut open_capture_ix),
1426                ("close", &mut close_capture_ix),
1427            ],
1428        );
1429        let patterns = (0..query.pattern_count())
1430            .map(|ix| {
1431                let mut config = BracketsPatternConfig::default();
1432                for setting in query.property_settings(ix) {
1433                    match setting.key.as_ref() {
1434                        "newline.only" => config.newline_only = true,
1435                        _ => {}
1436                    }
1437                }
1438                config
1439            })
1440            .collect();
1441        if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1442            grammar.brackets_config = Some(BracketsConfig {
1443                query,
1444                open_capture_ix,
1445                close_capture_ix,
1446                patterns,
1447            });
1448        }
1449        Ok(self)
1450    }
1451
1452    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1453        let grammar = self
1454            .grammar_mut()
1455            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1456        let query = Query::new(&grammar.ts_language, source)?;
1457        let mut indent_capture_ix = None;
1458        let mut start_capture_ix = None;
1459        let mut end_capture_ix = None;
1460        let mut outdent_capture_ix = None;
1461        get_capture_indices(
1462            &query,
1463            &mut [
1464                ("indent", &mut indent_capture_ix),
1465                ("start", &mut start_capture_ix),
1466                ("end", &mut end_capture_ix),
1467                ("outdent", &mut outdent_capture_ix),
1468            ],
1469        );
1470        if let Some(indent_capture_ix) = indent_capture_ix {
1471            grammar.indents_config = Some(IndentConfig {
1472                query,
1473                indent_capture_ix,
1474                start_capture_ix,
1475                end_capture_ix,
1476                outdent_capture_ix,
1477            });
1478        }
1479        Ok(self)
1480    }
1481
1482    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1483        let grammar = self
1484            .grammar_mut()
1485            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1486        let query = Query::new(&grammar.ts_language, source)?;
1487        let mut language_capture_ix = None;
1488        let mut injection_language_capture_ix = None;
1489        let mut content_capture_ix = None;
1490        let mut injection_content_capture_ix = None;
1491        get_capture_indices(
1492            &query,
1493            &mut [
1494                ("language", &mut language_capture_ix),
1495                ("injection.language", &mut injection_language_capture_ix),
1496                ("content", &mut content_capture_ix),
1497                ("injection.content", &mut injection_content_capture_ix),
1498            ],
1499        );
1500        language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1501            (None, Some(ix)) => Some(ix),
1502            (Some(_), Some(_)) => {
1503                return Err(anyhow!(
1504                    "both language and injection.language captures are present"
1505                ));
1506            }
1507            _ => language_capture_ix,
1508        };
1509        content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1510            (None, Some(ix)) => Some(ix),
1511            (Some(_), Some(_)) => {
1512                return Err(anyhow!(
1513                    "both content and injection.content captures are present"
1514                ));
1515            }
1516            _ => content_capture_ix,
1517        };
1518        let patterns = (0..query.pattern_count())
1519            .map(|ix| {
1520                let mut config = InjectionPatternConfig::default();
1521                for setting in query.property_settings(ix) {
1522                    match setting.key.as_ref() {
1523                        "language" | "injection.language" => {
1524                            config.language.clone_from(&setting.value);
1525                        }
1526                        "combined" | "injection.combined" => {
1527                            config.combined = true;
1528                        }
1529                        _ => {}
1530                    }
1531                }
1532                config
1533            })
1534            .collect();
1535        if let Some(content_capture_ix) = content_capture_ix {
1536            grammar.injection_config = Some(InjectionConfig {
1537                query,
1538                language_capture_ix,
1539                content_capture_ix,
1540                patterns,
1541            });
1542        }
1543        Ok(self)
1544    }
1545
1546    pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1547        let query = {
1548            let grammar = self
1549                .grammar
1550                .as_ref()
1551                .ok_or_else(|| anyhow!("no grammar for language"))?;
1552            Query::new(&grammar.ts_language, source)?
1553        };
1554
1555        let mut override_configs_by_id = HashMap::default();
1556        for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1557            let mut range_is_inclusive = false;
1558            if name.starts_with('_') {
1559                continue;
1560            }
1561            if let Some(prefix) = name.strip_suffix(".inclusive") {
1562                name = prefix;
1563                range_is_inclusive = true;
1564            }
1565
1566            let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1567            for server_name in &value.opt_into_language_servers {
1568                if !self
1569                    .config
1570                    .scope_opt_in_language_servers
1571                    .contains(server_name)
1572                {
1573                    util::debug_panic!(
1574                        "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1575                    );
1576                }
1577            }
1578
1579            override_configs_by_id.insert(
1580                ix as u32,
1581                OverrideEntry {
1582                    name: name.to_string(),
1583                    range_is_inclusive,
1584                    value,
1585                },
1586            );
1587        }
1588
1589        let referenced_override_names = self.config.overrides.keys().chain(
1590            self.config
1591                .brackets
1592                .disabled_scopes_by_bracket_ix
1593                .iter()
1594                .flatten(),
1595        );
1596
1597        for referenced_name in referenced_override_names {
1598            if !override_configs_by_id
1599                .values()
1600                .any(|entry| entry.name == *referenced_name)
1601            {
1602                Err(anyhow!(
1603                    "language {:?} has overrides in config not in query: {referenced_name:?}",
1604                    self.config.name
1605                ))?;
1606            }
1607        }
1608
1609        for entry in override_configs_by_id.values_mut() {
1610            entry.value.disabled_bracket_ixs = self
1611                .config
1612                .brackets
1613                .disabled_scopes_by_bracket_ix
1614                .iter()
1615                .enumerate()
1616                .filter_map(|(ix, disabled_scope_names)| {
1617                    if disabled_scope_names.contains(&entry.name) {
1618                        Some(ix as u16)
1619                    } else {
1620                        None
1621                    }
1622                })
1623                .collect();
1624        }
1625
1626        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1627
1628        let grammar = self
1629            .grammar_mut()
1630            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1631        grammar.override_config = Some(OverrideConfig {
1632            query,
1633            values: override_configs_by_id,
1634        });
1635        Ok(self)
1636    }
1637
1638    pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1639        let grammar = self
1640            .grammar_mut()
1641            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1642
1643        let query = Query::new(&grammar.ts_language, source)?;
1644        let mut redaction_capture_ix = None;
1645        get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1646
1647        if let Some(redaction_capture_ix) = redaction_capture_ix {
1648            grammar.redactions_config = Some(RedactionConfig {
1649                query,
1650                redaction_capture_ix,
1651            });
1652        }
1653
1654        Ok(self)
1655    }
1656
1657    fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1658        Arc::get_mut(self.grammar.as_mut()?)
1659    }
1660
1661    pub fn name(&self) -> LanguageName {
1662        self.config.name.clone()
1663    }
1664
1665    pub fn code_fence_block_name(&self) -> Arc<str> {
1666        self.config
1667            .code_fence_block_name
1668            .clone()
1669            .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1670    }
1671
1672    pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1673        self.context_provider.clone()
1674    }
1675
1676    pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1677        self.toolchain.clone()
1678    }
1679
1680    pub fn highlight_text<'a>(
1681        self: &'a Arc<Self>,
1682        text: &'a Rope,
1683        range: Range<usize>,
1684    ) -> Vec<(Range<usize>, HighlightId)> {
1685        let mut result = Vec::new();
1686        if let Some(grammar) = &self.grammar {
1687            let tree = grammar.parse_text(text, None);
1688            let captures =
1689                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1690                    grammar.highlights_query.as_ref()
1691                });
1692            let highlight_maps = vec![grammar.highlight_map()];
1693            let mut offset = 0;
1694            for chunk in
1695                BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1696            {
1697                let end_offset = offset + chunk.text.len();
1698                if let Some(highlight_id) = chunk.syntax_highlight_id {
1699                    if !highlight_id.is_default() {
1700                        result.push((offset..end_offset, highlight_id));
1701                    }
1702                }
1703                offset = end_offset;
1704            }
1705        }
1706        result
1707    }
1708
1709    pub fn path_suffixes(&self) -> &[String] {
1710        &self.config.matcher.path_suffixes
1711    }
1712
1713    pub fn should_autoclose_before(&self, c: char) -> bool {
1714        c.is_whitespace() || self.config.autoclose_before.contains(c)
1715    }
1716
1717    pub fn set_theme(&self, theme: &SyntaxTheme) {
1718        if let Some(grammar) = self.grammar.as_ref() {
1719            if let Some(highlights_query) = &grammar.highlights_query {
1720                *grammar.highlight_map.lock() =
1721                    HighlightMap::new(highlights_query.capture_names(), theme);
1722            }
1723        }
1724    }
1725
1726    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1727        self.grammar.as_ref()
1728    }
1729
1730    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1731        LanguageScope {
1732            language: self.clone(),
1733            override_id: None,
1734        }
1735    }
1736
1737    pub fn lsp_id(&self) -> String {
1738        self.config.name.lsp_id()
1739    }
1740
1741    pub fn prettier_parser_name(&self) -> Option<&str> {
1742        self.config.prettier_parser_name.as_deref()
1743    }
1744
1745    pub fn config(&self) -> &LanguageConfig {
1746        &self.config
1747    }
1748}
1749
1750impl LanguageScope {
1751    pub fn path_suffixes(&self) -> &[String] {
1752        &self.language.path_suffixes()
1753    }
1754
1755    pub fn language_name(&self) -> LanguageName {
1756        self.language.config.name.clone()
1757    }
1758
1759    pub fn collapsed_placeholder(&self) -> &str {
1760        self.language.config.collapsed_placeholder.as_ref()
1761    }
1762
1763    /// Returns line prefix that is inserted in e.g. line continuations or
1764    /// in `toggle comments` action.
1765    pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1766        Override::as_option(
1767            self.config_override().map(|o| &o.line_comments),
1768            Some(&self.language.config.line_comments),
1769        )
1770        .map_or([].as_slice(), |e| e.as_slice())
1771    }
1772
1773    pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1774        Override::as_option(
1775            self.config_override().map(|o| &o.block_comment),
1776            self.language.config.block_comment.as_ref(),
1777        )
1778        .map(|e| (&e.0, &e.1))
1779    }
1780
1781    /// Returns a list of language-specific word characters.
1782    ///
1783    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1784    /// the purpose of actions like 'move to next word end` or whole-word search.
1785    /// It additionally accounts for language's additional word characters.
1786    pub fn word_characters(&self) -> Option<&HashSet<char>> {
1787        Override::as_option(
1788            self.config_override().map(|o| &o.word_characters),
1789            Some(&self.language.config.word_characters),
1790        )
1791    }
1792
1793    /// Returns a list of language-specific characters that are considered part of
1794    /// a completion query.
1795    pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
1796        Override::as_option(
1797            self.config_override()
1798                .map(|o| &o.completion_query_characters),
1799            Some(&self.language.config.completion_query_characters),
1800        )
1801    }
1802
1803    /// Returns a list of bracket pairs for a given language with an additional
1804    /// piece of information about whether the particular bracket pair is currently active for a given language.
1805    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1806        let mut disabled_ids = self
1807            .config_override()
1808            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1809        self.language
1810            .config
1811            .brackets
1812            .pairs
1813            .iter()
1814            .enumerate()
1815            .map(move |(ix, bracket)| {
1816                let mut is_enabled = true;
1817                if let Some(next_disabled_ix) = disabled_ids.first() {
1818                    if ix == *next_disabled_ix as usize {
1819                        disabled_ids = &disabled_ids[1..];
1820                        is_enabled = false;
1821                    }
1822                }
1823                (bracket, is_enabled)
1824            })
1825    }
1826
1827    pub fn should_autoclose_before(&self, c: char) -> bool {
1828        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1829    }
1830
1831    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1832        let config = &self.language.config;
1833        let opt_in_servers = &config.scope_opt_in_language_servers;
1834        if opt_in_servers.iter().any(|o| *o == *name) {
1835            if let Some(over) = self.config_override() {
1836                over.opt_into_language_servers.iter().any(|o| *o == *name)
1837            } else {
1838                false
1839            }
1840        } else {
1841            true
1842        }
1843    }
1844
1845    pub fn override_name(&self) -> Option<&str> {
1846        let id = self.override_id?;
1847        let grammar = self.language.grammar.as_ref()?;
1848        let override_config = grammar.override_config.as_ref()?;
1849        override_config.values.get(&id).map(|e| e.name.as_str())
1850    }
1851
1852    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1853        let id = self.override_id?;
1854        let grammar = self.language.grammar.as_ref()?;
1855        let override_config = grammar.override_config.as_ref()?;
1856        override_config.values.get(&id).map(|e| &e.value)
1857    }
1858}
1859
1860impl Hash for Language {
1861    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1862        self.id.hash(state)
1863    }
1864}
1865
1866impl PartialEq for Language {
1867    fn eq(&self, other: &Self) -> bool {
1868        self.id.eq(&other.id)
1869    }
1870}
1871
1872impl Eq for Language {}
1873
1874impl Debug for Language {
1875    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1876        f.debug_struct("Language")
1877            .field("name", &self.config.name)
1878            .finish()
1879    }
1880}
1881
1882impl Grammar {
1883    pub fn id(&self) -> GrammarId {
1884        self.id
1885    }
1886
1887    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1888        with_parser(|parser| {
1889            parser
1890                .set_language(&self.ts_language)
1891                .expect("incompatible grammar");
1892            let mut chunks = text.chunks_in_range(0..text.len());
1893            parser
1894                .parse_with_options(
1895                    &mut move |offset, _| {
1896                        chunks.seek(offset);
1897                        chunks.next().unwrap_or("").as_bytes()
1898                    },
1899                    old_tree.as_ref(),
1900                    None,
1901                )
1902                .unwrap()
1903        })
1904    }
1905
1906    pub fn highlight_map(&self) -> HighlightMap {
1907        self.highlight_map.lock().clone()
1908    }
1909
1910    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1911        let capture_id = self
1912            .highlights_query
1913            .as_ref()?
1914            .capture_index_for_name(name)?;
1915        Some(self.highlight_map.lock().get(capture_id))
1916    }
1917}
1918
1919impl CodeLabel {
1920    pub fn fallback_for_completion(
1921        item: &lsp::CompletionItem,
1922        language: Option<&Language>,
1923    ) -> Self {
1924        let highlight_id = item.kind.and_then(|kind| {
1925            let grammar = language?.grammar()?;
1926            use lsp::CompletionItemKind as Kind;
1927            match kind {
1928                Kind::CLASS => grammar.highlight_id_for_name("type"),
1929                Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
1930                Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
1931                Kind::ENUM => grammar
1932                    .highlight_id_for_name("enum")
1933                    .or_else(|| grammar.highlight_id_for_name("type")),
1934                Kind::FIELD => grammar.highlight_id_for_name("property"),
1935                Kind::FUNCTION => grammar.highlight_id_for_name("function"),
1936                Kind::INTERFACE => grammar.highlight_id_for_name("type"),
1937                Kind::METHOD => grammar
1938                    .highlight_id_for_name("function.method")
1939                    .or_else(|| grammar.highlight_id_for_name("function")),
1940                Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
1941                Kind::PROPERTY => grammar.highlight_id_for_name("property"),
1942                Kind::STRUCT => grammar.highlight_id_for_name("type"),
1943                Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
1944                Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
1945                _ => None,
1946            }
1947        });
1948
1949        let label = &item.label;
1950        let label_length = label.len();
1951        let runs = highlight_id
1952            .map(|highlight_id| vec![(0..label_length, highlight_id)])
1953            .unwrap_or_default();
1954        let text = if let Some(detail) = item.detail.as_deref().filter(|detail| detail != label) {
1955            format!("{label} {detail}")
1956        } else if let Some(description) = item
1957            .label_details
1958            .as_ref()
1959            .and_then(|label_details| label_details.description.as_deref())
1960            .filter(|description| description != label)
1961        {
1962            format!("{label} {description}")
1963        } else {
1964            label.clone()
1965        };
1966        Self {
1967            text,
1968            runs,
1969            filter_range: 0..label_length,
1970        }
1971    }
1972
1973    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1974        let mut result = Self {
1975            runs: Vec::new(),
1976            filter_range: 0..text.len(),
1977            text,
1978        };
1979        if let Some(filter_text) = filter_text {
1980            if let Some(ix) = result.text.find(filter_text) {
1981                result.filter_range = ix..ix + filter_text.len();
1982            }
1983        }
1984        result
1985    }
1986
1987    pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
1988        let start_ix = self.text.len();
1989        self.text.push_str(text);
1990        let end_ix = self.text.len();
1991        if let Some(highlight) = highlight {
1992            self.runs.push((start_ix..end_ix, highlight));
1993        }
1994    }
1995
1996    pub fn text(&self) -> &str {
1997        self.text.as_str()
1998    }
1999
2000    pub fn filter_text(&self) -> &str {
2001        &self.text[self.filter_range.clone()]
2002    }
2003}
2004
2005impl From<String> for CodeLabel {
2006    fn from(value: String) -> Self {
2007        Self::plain(value, None)
2008    }
2009}
2010
2011impl From<&str> for CodeLabel {
2012    fn from(value: &str) -> Self {
2013        Self::plain(value.to_string(), None)
2014    }
2015}
2016
2017impl Ord for LanguageMatcher {
2018    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2019        self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
2020            self.first_line_pattern
2021                .as_ref()
2022                .map(Regex::as_str)
2023                .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
2024        })
2025    }
2026}
2027
2028impl PartialOrd for LanguageMatcher {
2029    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2030        Some(self.cmp(other))
2031    }
2032}
2033
2034impl Eq for LanguageMatcher {}
2035
2036impl PartialEq for LanguageMatcher {
2037    fn eq(&self, other: &Self) -> bool {
2038        self.path_suffixes == other.path_suffixes
2039            && self.first_line_pattern.as_ref().map(Regex::as_str)
2040                == other.first_line_pattern.as_ref().map(Regex::as_str)
2041    }
2042}
2043
2044#[cfg(any(test, feature = "test-support"))]
2045impl Default for FakeLspAdapter {
2046    fn default() -> Self {
2047        Self {
2048            name: "the-fake-language-server",
2049            capabilities: lsp::LanguageServer::full_capabilities(),
2050            initializer: None,
2051            disk_based_diagnostics_progress_token: None,
2052            initialization_options: None,
2053            disk_based_diagnostics_sources: Vec::new(),
2054            prettier_plugins: Vec::new(),
2055            language_server_binary: LanguageServerBinary {
2056                path: "/the/fake/lsp/path".into(),
2057                arguments: vec![],
2058                env: Default::default(),
2059            },
2060            label_for_completion: None,
2061        }
2062    }
2063}
2064
2065#[cfg(any(test, feature = "test-support"))]
2066#[async_trait(?Send)]
2067impl LspAdapter for FakeLspAdapter {
2068    fn name(&self) -> LanguageServerName {
2069        LanguageServerName(self.name.into())
2070    }
2071
2072    async fn check_if_user_installed(
2073        &self,
2074        _: &dyn LspAdapterDelegate,
2075        _: Arc<dyn LanguageToolchainStore>,
2076        _: &AsyncApp,
2077    ) -> Option<LanguageServerBinary> {
2078        Some(self.language_server_binary.clone())
2079    }
2080
2081    fn get_language_server_command<'a>(
2082        self: Arc<Self>,
2083        _: Arc<dyn LspAdapterDelegate>,
2084        _: Arc<dyn LanguageToolchainStore>,
2085        _: LanguageServerBinaryOptions,
2086        _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
2087        _: &'a mut AsyncApp,
2088    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
2089        async move { Ok(self.language_server_binary.clone()) }.boxed_local()
2090    }
2091
2092    async fn fetch_latest_server_version(
2093        &self,
2094        _: &dyn LspAdapterDelegate,
2095    ) -> Result<Box<dyn 'static + Send + Any>> {
2096        unreachable!();
2097    }
2098
2099    async fn fetch_server_binary(
2100        &self,
2101        _: Box<dyn 'static + Send + Any>,
2102        _: PathBuf,
2103        _: &dyn LspAdapterDelegate,
2104    ) -> Result<LanguageServerBinary> {
2105        unreachable!();
2106    }
2107
2108    async fn cached_server_binary(
2109        &self,
2110        _: PathBuf,
2111        _: &dyn LspAdapterDelegate,
2112    ) -> Option<LanguageServerBinary> {
2113        unreachable!();
2114    }
2115
2116    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2117        self.disk_based_diagnostics_sources.clone()
2118    }
2119
2120    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2121        self.disk_based_diagnostics_progress_token.clone()
2122    }
2123
2124    async fn initialization_options(
2125        self: Arc<Self>,
2126        _: &dyn Fs,
2127        _: &Arc<dyn LspAdapterDelegate>,
2128    ) -> Result<Option<Value>> {
2129        Ok(self.initialization_options.clone())
2130    }
2131
2132    async fn label_for_completion(
2133        &self,
2134        item: &lsp::CompletionItem,
2135        language: &Arc<Language>,
2136    ) -> Option<CodeLabel> {
2137        let label_for_completion = self.label_for_completion.as_ref()?;
2138        label_for_completion(item, language)
2139    }
2140}
2141
2142fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
2143    for (ix, name) in query.capture_names().iter().enumerate() {
2144        for (capture_name, index) in captures.iter_mut() {
2145            if capture_name == name {
2146                **index = Some(ix as u32);
2147                break;
2148            }
2149        }
2150    }
2151}
2152
2153pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2154    lsp::Position::new(point.row, point.column)
2155}
2156
2157pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2158    Unclipped(PointUtf16::new(point.line, point.character))
2159}
2160
2161pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2162    if range.start > range.end {
2163        Err(anyhow!(
2164            "Inverted range provided to an LSP request: {:?}-{:?}",
2165            range.start,
2166            range.end
2167        ))
2168    } else {
2169        Ok(lsp::Range {
2170            start: point_to_lsp(range.start),
2171            end: point_to_lsp(range.end),
2172        })
2173    }
2174}
2175
2176pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2177    let mut start = point_from_lsp(range.start);
2178    let mut end = point_from_lsp(range.end);
2179    if start > end {
2180        log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2181        mem::swap(&mut start, &mut end);
2182    }
2183    start..end
2184}
2185
2186#[cfg(test)]
2187mod tests {
2188    use super::*;
2189    use gpui::TestAppContext;
2190
2191    #[gpui::test(iterations = 10)]
2192    async fn test_language_loading(cx: &mut TestAppContext) {
2193        let languages = LanguageRegistry::test(cx.executor());
2194        let languages = Arc::new(languages);
2195        languages.register_native_grammars([
2196            ("json", tree_sitter_json::LANGUAGE),
2197            ("rust", tree_sitter_rust::LANGUAGE),
2198        ]);
2199        languages.register_test_language(LanguageConfig {
2200            name: "JSON".into(),
2201            grammar: Some("json".into()),
2202            matcher: LanguageMatcher {
2203                path_suffixes: vec!["json".into()],
2204                ..Default::default()
2205            },
2206            ..Default::default()
2207        });
2208        languages.register_test_language(LanguageConfig {
2209            name: "Rust".into(),
2210            grammar: Some("rust".into()),
2211            matcher: LanguageMatcher {
2212                path_suffixes: vec!["rs".into()],
2213                ..Default::default()
2214            },
2215            ..Default::default()
2216        });
2217        assert_eq!(
2218            languages.language_names(),
2219            &[
2220                "JSON".to_string(),
2221                "Plain Text".to_string(),
2222                "Rust".to_string(),
2223            ]
2224        );
2225
2226        let rust1 = languages.language_for_name("Rust");
2227        let rust2 = languages.language_for_name("Rust");
2228
2229        // Ensure language is still listed even if it's being loaded.
2230        assert_eq!(
2231            languages.language_names(),
2232            &[
2233                "JSON".to_string(),
2234                "Plain Text".to_string(),
2235                "Rust".to_string(),
2236            ]
2237        );
2238
2239        let (rust1, rust2) = futures::join!(rust1, rust2);
2240        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2241
2242        // Ensure language is still listed even after loading it.
2243        assert_eq!(
2244            languages.language_names(),
2245            &[
2246                "JSON".to_string(),
2247                "Plain Text".to_string(),
2248                "Rust".to_string(),
2249            ]
2250        );
2251
2252        // Loading an unknown language returns an error.
2253        assert!(languages.language_for_name("Unknown").await.is_err());
2254    }
2255
2256    #[gpui::test]
2257    async fn test_completion_label_omits_duplicate_data() {
2258        let regular_completion_item_1 = lsp::CompletionItem {
2259            label: "regular1".to_string(),
2260            detail: Some("detail1".to_string()),
2261            label_details: Some(lsp::CompletionItemLabelDetails {
2262                detail: None,
2263                description: Some("description 1".to_string()),
2264            }),
2265            ..lsp::CompletionItem::default()
2266        };
2267
2268        let regular_completion_item_2 = lsp::CompletionItem {
2269            label: "regular2".to_string(),
2270            label_details: Some(lsp::CompletionItemLabelDetails {
2271                detail: None,
2272                description: Some("description 2".to_string()),
2273            }),
2274            ..lsp::CompletionItem::default()
2275        };
2276
2277        let completion_item_with_duplicate_detail_and_proper_description = lsp::CompletionItem {
2278            detail: Some(regular_completion_item_1.label.clone()),
2279            ..regular_completion_item_1.clone()
2280        };
2281
2282        let completion_item_with_duplicate_detail = lsp::CompletionItem {
2283            detail: Some(regular_completion_item_1.label.clone()),
2284            label_details: None,
2285            ..regular_completion_item_1.clone()
2286        };
2287
2288        let completion_item_with_duplicate_description = lsp::CompletionItem {
2289            label_details: Some(lsp::CompletionItemLabelDetails {
2290                detail: None,
2291                description: Some(regular_completion_item_2.label.clone()),
2292            }),
2293            ..regular_completion_item_2.clone()
2294        };
2295
2296        assert_eq!(
2297            CodeLabel::fallback_for_completion(&regular_completion_item_1, None).text,
2298            format!(
2299                "{} {}",
2300                regular_completion_item_1.label,
2301                regular_completion_item_1.detail.unwrap()
2302            ),
2303            "LSP completion items with both detail and label_details.description should prefer detail"
2304        );
2305        assert_eq!(
2306            CodeLabel::fallback_for_completion(&regular_completion_item_2, None).text,
2307            format!(
2308                "{} {}",
2309                regular_completion_item_2.label,
2310                regular_completion_item_2
2311                    .label_details
2312                    .as_ref()
2313                    .unwrap()
2314                    .description
2315                    .as_ref()
2316                    .unwrap()
2317            ),
2318            "LSP completion items without detail but with label_details.description should use that"
2319        );
2320        assert_eq!(
2321            CodeLabel::fallback_for_completion(
2322                &completion_item_with_duplicate_detail_and_proper_description,
2323                None
2324            )
2325            .text,
2326            format!(
2327                "{} {}",
2328                regular_completion_item_1.label,
2329                regular_completion_item_1
2330                    .label_details
2331                    .as_ref()
2332                    .unwrap()
2333                    .description
2334                    .as_ref()
2335                    .unwrap()
2336            ),
2337            "LSP completion items with both detail and label_details.description should prefer description only if the detail duplicates the completion label"
2338        );
2339        assert_eq!(
2340            CodeLabel::fallback_for_completion(&completion_item_with_duplicate_detail, None).text,
2341            regular_completion_item_1.label,
2342            "LSP completion items with duplicate label and detail, should omit the detail"
2343        );
2344        assert_eq!(
2345            CodeLabel::fallback_for_completion(&completion_item_with_duplicate_description, None)
2346                .text,
2347            regular_completion_item_2.label,
2348            "LSP completion items with duplicate label and detail, should omit the detail"
2349        );
2350    }
2351}