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::{anyhow, Context as _, Result};
  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    gen::SchemaGenerator,
  42    schema::{InstanceType, Schema, SchemaObject},
  43    JsonSchema,
  44};
  45use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
  46use serde_json::Value;
  47use settings::WorktreeId;
  48use smol::future::FutureExt as _;
  49use std::{
  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        atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
  61        Arc, LazyLock,
  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::{line_diff, text_diff, text_diff_with_options, unified_diff, DiffOptions};
  69use theme::SyntaxTheme;
  70pub use toolchain::{LanguageToolchainStore, Toolchain, ToolchainList, ToolchainLister};
  71use tree_sitter::{self, wasmtime, Query, QueryCursor, WasmStore};
  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(&self, original: InitializeParams) -> Result<InitializeParams> {
 576        Ok(original)
 577    }
 578
 579    fn attach_kind(&self) -> Attach {
 580        Attach::Shared
 581    }
 582
 583    fn manifest_name(&self) -> Option<ManifestName> {
 584        None
 585    }
 586
 587    /// Method only implemented by the default JSON language server adapter.
 588    /// Used to provide dynamic reloading of the JSON schemas used to
 589    /// provide autocompletion and diagnostics in Zed setting and keybind
 590    /// files
 591    fn is_primary_zed_json_schema_adapter(&self) -> bool {
 592        false
 593    }
 594
 595    /// Method only implemented by the default JSON language server adapter.
 596    /// Used to clear the cache of JSON schemas that are used to provide
 597    /// autocompletion and diagnostics in Zed settings and keybinds files.
 598    /// Should not be called unless the callee is sure that
 599    /// `Self::is_primary_zed_json_schema_adapter` returns `true`
 600    async fn clear_zed_json_schema_cache(&self) {
 601        unreachable!("Not implemented for this adapter. This method should only be called on the default JSON language server adapter");
 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(gen: &mut SchemaGenerator) -> Schema {
 935    Option::<Vec<BracketPairContent>>::json_schema(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) indents_config: Option<IndentConfig>,
1019    pub outline_config: Option<OutlineConfig>,
1020    pub text_object_config: Option<TextObjectConfig>,
1021    pub embedding_config: Option<EmbeddingConfig>,
1022    pub(crate) injection_config: Option<InjectionConfig>,
1023    pub(crate) override_config: Option<OverrideConfig>,
1024    pub(crate) highlight_map: Mutex<HighlightMap>,
1025}
1026
1027struct IndentConfig {
1028    query: Query,
1029    indent_capture_ix: u32,
1030    start_capture_ix: Option<u32>,
1031    end_capture_ix: Option<u32>,
1032    outdent_capture_ix: Option<u32>,
1033}
1034
1035pub struct OutlineConfig {
1036    pub query: Query,
1037    pub item_capture_ix: u32,
1038    pub name_capture_ix: u32,
1039    pub context_capture_ix: Option<u32>,
1040    pub extra_context_capture_ix: Option<u32>,
1041    pub open_capture_ix: Option<u32>,
1042    pub close_capture_ix: Option<u32>,
1043    pub annotation_capture_ix: Option<u32>,
1044}
1045
1046#[derive(Debug, Clone, Copy, PartialEq)]
1047pub enum TextObject {
1048    InsideFunction,
1049    AroundFunction,
1050    InsideClass,
1051    AroundClass,
1052    InsideComment,
1053    AroundComment,
1054}
1055
1056impl TextObject {
1057    pub fn from_capture_name(name: &str) -> Option<TextObject> {
1058        match name {
1059            "function.inside" => Some(TextObject::InsideFunction),
1060            "function.around" => Some(TextObject::AroundFunction),
1061            "class.inside" => Some(TextObject::InsideClass),
1062            "class.around" => Some(TextObject::AroundClass),
1063            "comment.inside" => Some(TextObject::InsideComment),
1064            "comment.around" => Some(TextObject::AroundComment),
1065            _ => None,
1066        }
1067    }
1068
1069    pub fn around(&self) -> Option<Self> {
1070        match self {
1071            TextObject::InsideFunction => Some(TextObject::AroundFunction),
1072            TextObject::InsideClass => Some(TextObject::AroundClass),
1073            TextObject::InsideComment => Some(TextObject::AroundComment),
1074            _ => None,
1075        }
1076    }
1077}
1078
1079pub struct TextObjectConfig {
1080    pub query: Query,
1081    pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1082}
1083
1084#[derive(Debug)]
1085pub struct EmbeddingConfig {
1086    pub query: Query,
1087    pub item_capture_ix: u32,
1088    pub name_capture_ix: Option<u32>,
1089    pub context_capture_ix: Option<u32>,
1090    pub collapse_capture_ix: Option<u32>,
1091    pub keep_capture_ix: Option<u32>,
1092}
1093
1094struct InjectionConfig {
1095    query: Query,
1096    content_capture_ix: u32,
1097    language_capture_ix: Option<u32>,
1098    patterns: Vec<InjectionPatternConfig>,
1099}
1100
1101struct RedactionConfig {
1102    pub query: Query,
1103    pub redaction_capture_ix: u32,
1104}
1105
1106#[derive(Clone, Debug, PartialEq)]
1107enum RunnableCapture {
1108    Named(SharedString),
1109    Run,
1110}
1111
1112struct RunnableConfig {
1113    pub query: Query,
1114    /// A mapping from capture indice to capture kind
1115    pub extra_captures: Vec<RunnableCapture>,
1116}
1117
1118struct OverrideConfig {
1119    query: Query,
1120    values: HashMap<u32, OverrideEntry>,
1121}
1122
1123#[derive(Debug)]
1124struct OverrideEntry {
1125    name: String,
1126    range_is_inclusive: bool,
1127    value: LanguageConfigOverride,
1128}
1129
1130#[derive(Default, Clone)]
1131struct InjectionPatternConfig {
1132    language: Option<Box<str>>,
1133    combined: bool,
1134}
1135
1136struct BracketsConfig {
1137    query: Query,
1138    open_capture_ix: u32,
1139    close_capture_ix: u32,
1140    patterns: Vec<BracketsPatternConfig>,
1141}
1142
1143#[derive(Clone, Debug, Default)]
1144struct BracketsPatternConfig {
1145    newline_only: bool,
1146}
1147
1148impl Language {
1149    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1150        Self::new_with_id(LanguageId::new(), config, ts_language)
1151    }
1152
1153    pub fn id(&self) -> LanguageId {
1154        self.id
1155    }
1156
1157    fn new_with_id(
1158        id: LanguageId,
1159        config: LanguageConfig,
1160        ts_language: Option<tree_sitter::Language>,
1161    ) -> Self {
1162        Self {
1163            id,
1164            config,
1165            grammar: ts_language.map(|ts_language| {
1166                Arc::new(Grammar {
1167                    id: GrammarId::new(),
1168                    highlights_query: None,
1169                    brackets_config: None,
1170                    outline_config: None,
1171                    text_object_config: None,
1172                    embedding_config: None,
1173                    indents_config: None,
1174                    injection_config: None,
1175                    override_config: None,
1176                    redactions_config: None,
1177                    runnable_config: None,
1178                    error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1179                    ts_language,
1180                    highlight_map: Default::default(),
1181                })
1182            }),
1183            context_provider: None,
1184            toolchain: None,
1185        }
1186    }
1187
1188    pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1189        self.context_provider = provider;
1190        self
1191    }
1192
1193    pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1194        self.toolchain = provider;
1195        self
1196    }
1197
1198    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1199        if let Some(query) = queries.highlights {
1200            self = self
1201                .with_highlights_query(query.as_ref())
1202                .context("Error loading highlights query")?;
1203        }
1204        if let Some(query) = queries.brackets {
1205            self = self
1206                .with_brackets_query(query.as_ref())
1207                .context("Error loading brackets query")?;
1208        }
1209        if let Some(query) = queries.indents {
1210            self = self
1211                .with_indents_query(query.as_ref())
1212                .context("Error loading indents query")?;
1213        }
1214        if let Some(query) = queries.outline {
1215            self = self
1216                .with_outline_query(query.as_ref())
1217                .context("Error loading outline query")?;
1218        }
1219        if let Some(query) = queries.embedding {
1220            self = self
1221                .with_embedding_query(query.as_ref())
1222                .context("Error loading embedding query")?;
1223        }
1224        if let Some(query) = queries.injections {
1225            self = self
1226                .with_injection_query(query.as_ref())
1227                .context("Error loading injection query")?;
1228        }
1229        if let Some(query) = queries.overrides {
1230            self = self
1231                .with_override_query(query.as_ref())
1232                .context("Error loading override query")?;
1233        }
1234        if let Some(query) = queries.redactions {
1235            self = self
1236                .with_redaction_query(query.as_ref())
1237                .context("Error loading redaction query")?;
1238        }
1239        if let Some(query) = queries.runnables {
1240            self = self
1241                .with_runnable_query(query.as_ref())
1242                .context("Error loading runnables query")?;
1243        }
1244        if let Some(query) = queries.text_objects {
1245            self = self
1246                .with_text_object_query(query.as_ref())
1247                .context("Error loading textobject query")?;
1248        }
1249        Ok(self)
1250    }
1251
1252    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1253        let grammar = self
1254            .grammar_mut()
1255            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1256        grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1257        Ok(self)
1258    }
1259
1260    pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1261        let grammar = self
1262            .grammar_mut()
1263            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1264
1265        let query = Query::new(&grammar.ts_language, source)?;
1266        let mut extra_captures = Vec::with_capacity(query.capture_names().len());
1267
1268        for name in query.capture_names().iter() {
1269            let kind = if *name == "run" {
1270                RunnableCapture::Run
1271            } else {
1272                RunnableCapture::Named(name.to_string().into())
1273            };
1274            extra_captures.push(kind);
1275        }
1276
1277        grammar.runnable_config = Some(RunnableConfig {
1278            extra_captures,
1279            query,
1280        });
1281
1282        Ok(self)
1283    }
1284
1285    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1286        let grammar = self
1287            .grammar_mut()
1288            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1289        let query = Query::new(&grammar.ts_language, source)?;
1290        let mut item_capture_ix = None;
1291        let mut name_capture_ix = None;
1292        let mut context_capture_ix = None;
1293        let mut extra_context_capture_ix = None;
1294        let mut open_capture_ix = None;
1295        let mut close_capture_ix = None;
1296        let mut annotation_capture_ix = None;
1297        get_capture_indices(
1298            &query,
1299            &mut [
1300                ("item", &mut item_capture_ix),
1301                ("name", &mut name_capture_ix),
1302                ("context", &mut context_capture_ix),
1303                ("context.extra", &mut extra_context_capture_ix),
1304                ("open", &mut open_capture_ix),
1305                ("close", &mut close_capture_ix),
1306                ("annotation", &mut annotation_capture_ix),
1307            ],
1308        );
1309        if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1310            grammar.outline_config = Some(OutlineConfig {
1311                query,
1312                item_capture_ix,
1313                name_capture_ix,
1314                context_capture_ix,
1315                extra_context_capture_ix,
1316                open_capture_ix,
1317                close_capture_ix,
1318                annotation_capture_ix,
1319            });
1320        }
1321        Ok(self)
1322    }
1323
1324    pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1325        let grammar = self
1326            .grammar_mut()
1327            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1328        let query = Query::new(&grammar.ts_language, source)?;
1329
1330        let mut text_objects_by_capture_ix = Vec::new();
1331        for (ix, name) in query.capture_names().iter().enumerate() {
1332            if let Some(text_object) = TextObject::from_capture_name(name) {
1333                text_objects_by_capture_ix.push((ix as u32, text_object));
1334            }
1335        }
1336
1337        grammar.text_object_config = Some(TextObjectConfig {
1338            query,
1339            text_objects_by_capture_ix,
1340        });
1341        Ok(self)
1342    }
1343
1344    pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1345        let grammar = self
1346            .grammar_mut()
1347            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1348        let query = Query::new(&grammar.ts_language, source)?;
1349        let mut item_capture_ix = None;
1350        let mut name_capture_ix = None;
1351        let mut context_capture_ix = None;
1352        let mut collapse_capture_ix = None;
1353        let mut keep_capture_ix = None;
1354        get_capture_indices(
1355            &query,
1356            &mut [
1357                ("item", &mut item_capture_ix),
1358                ("name", &mut name_capture_ix),
1359                ("context", &mut context_capture_ix),
1360                ("keep", &mut keep_capture_ix),
1361                ("collapse", &mut collapse_capture_ix),
1362            ],
1363        );
1364        if let Some(item_capture_ix) = item_capture_ix {
1365            grammar.embedding_config = Some(EmbeddingConfig {
1366                query,
1367                item_capture_ix,
1368                name_capture_ix,
1369                context_capture_ix,
1370                collapse_capture_ix,
1371                keep_capture_ix,
1372            });
1373        }
1374        Ok(self)
1375    }
1376
1377    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1378        let grammar = self
1379            .grammar_mut()
1380            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1381        let query = Query::new(&grammar.ts_language, source)?;
1382        let mut open_capture_ix = None;
1383        let mut close_capture_ix = None;
1384        get_capture_indices(
1385            &query,
1386            &mut [
1387                ("open", &mut open_capture_ix),
1388                ("close", &mut close_capture_ix),
1389            ],
1390        );
1391        let patterns = (0..query.pattern_count())
1392            .map(|ix| {
1393                let mut config = BracketsPatternConfig::default();
1394                for setting in query.property_settings(ix) {
1395                    match setting.key.as_ref() {
1396                        "newline.only" => config.newline_only = true,
1397                        _ => {}
1398                    }
1399                }
1400                config
1401            })
1402            .collect();
1403        if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1404            grammar.brackets_config = Some(BracketsConfig {
1405                query,
1406                open_capture_ix,
1407                close_capture_ix,
1408                patterns,
1409            });
1410        }
1411        Ok(self)
1412    }
1413
1414    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1415        let grammar = self
1416            .grammar_mut()
1417            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1418        let query = Query::new(&grammar.ts_language, source)?;
1419        let mut indent_capture_ix = None;
1420        let mut start_capture_ix = None;
1421        let mut end_capture_ix = None;
1422        let mut outdent_capture_ix = None;
1423        get_capture_indices(
1424            &query,
1425            &mut [
1426                ("indent", &mut indent_capture_ix),
1427                ("start", &mut start_capture_ix),
1428                ("end", &mut end_capture_ix),
1429                ("outdent", &mut outdent_capture_ix),
1430            ],
1431        );
1432        if let Some(indent_capture_ix) = indent_capture_ix {
1433            grammar.indents_config = Some(IndentConfig {
1434                query,
1435                indent_capture_ix,
1436                start_capture_ix,
1437                end_capture_ix,
1438                outdent_capture_ix,
1439            });
1440        }
1441        Ok(self)
1442    }
1443
1444    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1445        let grammar = self
1446            .grammar_mut()
1447            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1448        let query = Query::new(&grammar.ts_language, source)?;
1449        let mut language_capture_ix = None;
1450        let mut injection_language_capture_ix = None;
1451        let mut content_capture_ix = None;
1452        let mut injection_content_capture_ix = None;
1453        get_capture_indices(
1454            &query,
1455            &mut [
1456                ("language", &mut language_capture_ix),
1457                ("injection.language", &mut injection_language_capture_ix),
1458                ("content", &mut content_capture_ix),
1459                ("injection.content", &mut injection_content_capture_ix),
1460            ],
1461        );
1462        language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1463            (None, Some(ix)) => Some(ix),
1464            (Some(_), Some(_)) => {
1465                return Err(anyhow!(
1466                    "both language and injection.language captures are present"
1467                ));
1468            }
1469            _ => language_capture_ix,
1470        };
1471        content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1472            (None, Some(ix)) => Some(ix),
1473            (Some(_), Some(_)) => {
1474                return Err(anyhow!(
1475                    "both content and injection.content captures are present"
1476                ));
1477            }
1478            _ => content_capture_ix,
1479        };
1480        let patterns = (0..query.pattern_count())
1481            .map(|ix| {
1482                let mut config = InjectionPatternConfig::default();
1483                for setting in query.property_settings(ix) {
1484                    match setting.key.as_ref() {
1485                        "language" | "injection.language" => {
1486                            config.language.clone_from(&setting.value);
1487                        }
1488                        "combined" | "injection.combined" => {
1489                            config.combined = true;
1490                        }
1491                        _ => {}
1492                    }
1493                }
1494                config
1495            })
1496            .collect();
1497        if let Some(content_capture_ix) = content_capture_ix {
1498            grammar.injection_config = Some(InjectionConfig {
1499                query,
1500                language_capture_ix,
1501                content_capture_ix,
1502                patterns,
1503            });
1504        }
1505        Ok(self)
1506    }
1507
1508    pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1509        let query = {
1510            let grammar = self
1511                .grammar
1512                .as_ref()
1513                .ok_or_else(|| anyhow!("no grammar for language"))?;
1514            Query::new(&grammar.ts_language, source)?
1515        };
1516
1517        let mut override_configs_by_id = HashMap::default();
1518        for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1519            let mut range_is_inclusive = false;
1520            if name.starts_with('_') {
1521                continue;
1522            }
1523            if let Some(prefix) = name.strip_suffix(".inclusive") {
1524                name = prefix;
1525                range_is_inclusive = true;
1526            }
1527
1528            let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1529            for server_name in &value.opt_into_language_servers {
1530                if !self
1531                    .config
1532                    .scope_opt_in_language_servers
1533                    .contains(server_name)
1534                {
1535                    util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1536                }
1537            }
1538
1539            override_configs_by_id.insert(
1540                ix as u32,
1541                OverrideEntry {
1542                    name: name.to_string(),
1543                    range_is_inclusive,
1544                    value,
1545                },
1546            );
1547        }
1548
1549        let referenced_override_names = self.config.overrides.keys().chain(
1550            self.config
1551                .brackets
1552                .disabled_scopes_by_bracket_ix
1553                .iter()
1554                .flatten(),
1555        );
1556
1557        for referenced_name in referenced_override_names {
1558            if !override_configs_by_id
1559                .values()
1560                .any(|entry| entry.name == *referenced_name)
1561            {
1562                Err(anyhow!(
1563                    "language {:?} has overrides in config not in query: {referenced_name:?}",
1564                    self.config.name
1565                ))?;
1566            }
1567        }
1568
1569        for entry in override_configs_by_id.values_mut() {
1570            entry.value.disabled_bracket_ixs = self
1571                .config
1572                .brackets
1573                .disabled_scopes_by_bracket_ix
1574                .iter()
1575                .enumerate()
1576                .filter_map(|(ix, disabled_scope_names)| {
1577                    if disabled_scope_names.contains(&entry.name) {
1578                        Some(ix as u16)
1579                    } else {
1580                        None
1581                    }
1582                })
1583                .collect();
1584        }
1585
1586        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1587
1588        let grammar = self
1589            .grammar_mut()
1590            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1591        grammar.override_config = Some(OverrideConfig {
1592            query,
1593            values: override_configs_by_id,
1594        });
1595        Ok(self)
1596    }
1597
1598    pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1599        let grammar = self
1600            .grammar_mut()
1601            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1602
1603        let query = Query::new(&grammar.ts_language, source)?;
1604        let mut redaction_capture_ix = None;
1605        get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1606
1607        if let Some(redaction_capture_ix) = redaction_capture_ix {
1608            grammar.redactions_config = Some(RedactionConfig {
1609                query,
1610                redaction_capture_ix,
1611            });
1612        }
1613
1614        Ok(self)
1615    }
1616
1617    fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1618        Arc::get_mut(self.grammar.as_mut()?)
1619    }
1620
1621    pub fn name(&self) -> LanguageName {
1622        self.config.name.clone()
1623    }
1624
1625    pub fn code_fence_block_name(&self) -> Arc<str> {
1626        self.config
1627            .code_fence_block_name
1628            .clone()
1629            .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1630    }
1631
1632    pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1633        self.context_provider.clone()
1634    }
1635
1636    pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1637        self.toolchain.clone()
1638    }
1639
1640    pub fn highlight_text<'a>(
1641        self: &'a Arc<Self>,
1642        text: &'a Rope,
1643        range: Range<usize>,
1644    ) -> Vec<(Range<usize>, HighlightId)> {
1645        let mut result = Vec::new();
1646        if let Some(grammar) = &self.grammar {
1647            let tree = grammar.parse_text(text, None);
1648            let captures =
1649                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1650                    grammar.highlights_query.as_ref()
1651                });
1652            let highlight_maps = vec![grammar.highlight_map()];
1653            let mut offset = 0;
1654            for chunk in
1655                BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1656            {
1657                let end_offset = offset + chunk.text.len();
1658                if let Some(highlight_id) = chunk.syntax_highlight_id {
1659                    if !highlight_id.is_default() {
1660                        result.push((offset..end_offset, highlight_id));
1661                    }
1662                }
1663                offset = end_offset;
1664            }
1665        }
1666        result
1667    }
1668
1669    pub fn path_suffixes(&self) -> &[String] {
1670        &self.config.matcher.path_suffixes
1671    }
1672
1673    pub fn should_autoclose_before(&self, c: char) -> bool {
1674        c.is_whitespace() || self.config.autoclose_before.contains(c)
1675    }
1676
1677    pub fn set_theme(&self, theme: &SyntaxTheme) {
1678        if let Some(grammar) = self.grammar.as_ref() {
1679            if let Some(highlights_query) = &grammar.highlights_query {
1680                *grammar.highlight_map.lock() =
1681                    HighlightMap::new(highlights_query.capture_names(), theme);
1682            }
1683        }
1684    }
1685
1686    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1687        self.grammar.as_ref()
1688    }
1689
1690    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1691        LanguageScope {
1692            language: self.clone(),
1693            override_id: None,
1694        }
1695    }
1696
1697    pub fn lsp_id(&self) -> String {
1698        self.config.name.lsp_id()
1699    }
1700
1701    pub fn prettier_parser_name(&self) -> Option<&str> {
1702        self.config.prettier_parser_name.as_deref()
1703    }
1704
1705    pub fn config(&self) -> &LanguageConfig {
1706        &self.config
1707    }
1708}
1709
1710impl LanguageScope {
1711    pub fn path_suffixes(&self) -> &[String] {
1712        &self.language.path_suffixes()
1713    }
1714
1715    pub fn language_name(&self) -> LanguageName {
1716        self.language.config.name.clone()
1717    }
1718
1719    pub fn collapsed_placeholder(&self) -> &str {
1720        self.language.config.collapsed_placeholder.as_ref()
1721    }
1722
1723    /// Returns line prefix that is inserted in e.g. line continuations or
1724    /// in `toggle comments` action.
1725    pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1726        Override::as_option(
1727            self.config_override().map(|o| &o.line_comments),
1728            Some(&self.language.config.line_comments),
1729        )
1730        .map_or([].as_slice(), |e| e.as_slice())
1731    }
1732
1733    pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1734        Override::as_option(
1735            self.config_override().map(|o| &o.block_comment),
1736            self.language.config.block_comment.as_ref(),
1737        )
1738        .map(|e| (&e.0, &e.1))
1739    }
1740
1741    /// Returns a list of language-specific word characters.
1742    ///
1743    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1744    /// the purpose of actions like 'move to next word end` or whole-word search.
1745    /// It additionally accounts for language's additional word characters.
1746    pub fn word_characters(&self) -> Option<&HashSet<char>> {
1747        Override::as_option(
1748            self.config_override().map(|o| &o.word_characters),
1749            Some(&self.language.config.word_characters),
1750        )
1751    }
1752
1753    /// Returns a list of language-specific characters that are considered part of
1754    /// a completion query.
1755    pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
1756        Override::as_option(
1757            self.config_override()
1758                .map(|o| &o.completion_query_characters),
1759            Some(&self.language.config.completion_query_characters),
1760        )
1761    }
1762
1763    /// Returns a list of bracket pairs for a given language with an additional
1764    /// piece of information about whether the particular bracket pair is currently active for a given language.
1765    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1766        let mut disabled_ids = self
1767            .config_override()
1768            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1769        self.language
1770            .config
1771            .brackets
1772            .pairs
1773            .iter()
1774            .enumerate()
1775            .map(move |(ix, bracket)| {
1776                let mut is_enabled = true;
1777                if let Some(next_disabled_ix) = disabled_ids.first() {
1778                    if ix == *next_disabled_ix as usize {
1779                        disabled_ids = &disabled_ids[1..];
1780                        is_enabled = false;
1781                    }
1782                }
1783                (bracket, is_enabled)
1784            })
1785    }
1786
1787    pub fn should_autoclose_before(&self, c: char) -> bool {
1788        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1789    }
1790
1791    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1792        let config = &self.language.config;
1793        let opt_in_servers = &config.scope_opt_in_language_servers;
1794        if opt_in_servers.iter().any(|o| *o == *name) {
1795            if let Some(over) = self.config_override() {
1796                over.opt_into_language_servers.iter().any(|o| *o == *name)
1797            } else {
1798                false
1799            }
1800        } else {
1801            true
1802        }
1803    }
1804
1805    pub fn override_name(&self) -> Option<&str> {
1806        let id = self.override_id?;
1807        let grammar = self.language.grammar.as_ref()?;
1808        let override_config = grammar.override_config.as_ref()?;
1809        override_config.values.get(&id).map(|e| e.name.as_str())
1810    }
1811
1812    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1813        let id = self.override_id?;
1814        let grammar = self.language.grammar.as_ref()?;
1815        let override_config = grammar.override_config.as_ref()?;
1816        override_config.values.get(&id).map(|e| &e.value)
1817    }
1818}
1819
1820impl Hash for Language {
1821    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1822        self.id.hash(state)
1823    }
1824}
1825
1826impl PartialEq for Language {
1827    fn eq(&self, other: &Self) -> bool {
1828        self.id.eq(&other.id)
1829    }
1830}
1831
1832impl Eq for Language {}
1833
1834impl Debug for Language {
1835    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1836        f.debug_struct("Language")
1837            .field("name", &self.config.name)
1838            .finish()
1839    }
1840}
1841
1842impl Grammar {
1843    pub fn id(&self) -> GrammarId {
1844        self.id
1845    }
1846
1847    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1848        with_parser(|parser| {
1849            parser
1850                .set_language(&self.ts_language)
1851                .expect("incompatible grammar");
1852            let mut chunks = text.chunks_in_range(0..text.len());
1853            parser
1854                .parse_with_options(
1855                    &mut move |offset, _| {
1856                        chunks.seek(offset);
1857                        chunks.next().unwrap_or("").as_bytes()
1858                    },
1859                    old_tree.as_ref(),
1860                    None,
1861                )
1862                .unwrap()
1863        })
1864    }
1865
1866    pub fn highlight_map(&self) -> HighlightMap {
1867        self.highlight_map.lock().clone()
1868    }
1869
1870    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1871        let capture_id = self
1872            .highlights_query
1873            .as_ref()?
1874            .capture_index_for_name(name)?;
1875        Some(self.highlight_map.lock().get(capture_id))
1876    }
1877}
1878
1879impl CodeLabel {
1880    pub fn fallback_for_completion(
1881        item: &lsp::CompletionItem,
1882        language: Option<&Language>,
1883    ) -> Self {
1884        let highlight_id = item.kind.and_then(|kind| {
1885            let grammar = language?.grammar()?;
1886            use lsp::CompletionItemKind as Kind;
1887            match kind {
1888                Kind::CLASS => grammar.highlight_id_for_name("type"),
1889                Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
1890                Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
1891                Kind::ENUM => grammar
1892                    .highlight_id_for_name("enum")
1893                    .or_else(|| grammar.highlight_id_for_name("type")),
1894                Kind::FIELD => grammar.highlight_id_for_name("property"),
1895                Kind::FUNCTION => grammar.highlight_id_for_name("function"),
1896                Kind::INTERFACE => grammar.highlight_id_for_name("type"),
1897                Kind::METHOD => grammar
1898                    .highlight_id_for_name("function.method")
1899                    .or_else(|| grammar.highlight_id_for_name("function")),
1900                Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
1901                Kind::PROPERTY => grammar.highlight_id_for_name("property"),
1902                Kind::STRUCT => grammar.highlight_id_for_name("type"),
1903                Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
1904                Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
1905                _ => None,
1906            }
1907        });
1908
1909        let label = &item.label;
1910        let label_length = label.len();
1911        let runs = highlight_id
1912            .map(|highlight_id| vec![(0..label_length, highlight_id)])
1913            .unwrap_or_default();
1914        let text = if let Some(detail) = &item.detail {
1915            format!("{label} {detail}")
1916        } else if let Some(description) = item
1917            .label_details
1918            .as_ref()
1919            .and_then(|label_details| label_details.description.as_ref())
1920        {
1921            format!("{label} {description}")
1922        } else {
1923            label.clone()
1924        };
1925        Self {
1926            text,
1927            runs,
1928            filter_range: 0..label_length,
1929        }
1930    }
1931
1932    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1933        let mut result = Self {
1934            runs: Vec::new(),
1935            filter_range: 0..text.len(),
1936            text,
1937        };
1938        if let Some(filter_text) = filter_text {
1939            if let Some(ix) = result.text.find(filter_text) {
1940                result.filter_range = ix..ix + filter_text.len();
1941            }
1942        }
1943        result
1944    }
1945
1946    pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
1947        let start_ix = self.text.len();
1948        self.text.push_str(text);
1949        let end_ix = self.text.len();
1950        if let Some(highlight) = highlight {
1951            self.runs.push((start_ix..end_ix, highlight));
1952        }
1953    }
1954
1955    pub fn text(&self) -> &str {
1956        self.text.as_str()
1957    }
1958
1959    pub fn filter_text(&self) -> &str {
1960        &self.text[self.filter_range.clone()]
1961    }
1962}
1963
1964impl From<String> for CodeLabel {
1965    fn from(value: String) -> Self {
1966        Self::plain(value, None)
1967    }
1968}
1969
1970impl From<&str> for CodeLabel {
1971    fn from(value: &str) -> Self {
1972        Self::plain(value.to_string(), None)
1973    }
1974}
1975
1976impl Ord for LanguageMatcher {
1977    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1978        self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1979            self.first_line_pattern
1980                .as_ref()
1981                .map(Regex::as_str)
1982                .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1983        })
1984    }
1985}
1986
1987impl PartialOrd for LanguageMatcher {
1988    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1989        Some(self.cmp(other))
1990    }
1991}
1992
1993impl Eq for LanguageMatcher {}
1994
1995impl PartialEq for LanguageMatcher {
1996    fn eq(&self, other: &Self) -> bool {
1997        self.path_suffixes == other.path_suffixes
1998            && self.first_line_pattern.as_ref().map(Regex::as_str)
1999                == other.first_line_pattern.as_ref().map(Regex::as_str)
2000    }
2001}
2002
2003#[cfg(any(test, feature = "test-support"))]
2004impl Default for FakeLspAdapter {
2005    fn default() -> Self {
2006        Self {
2007            name: "the-fake-language-server",
2008            capabilities: lsp::LanguageServer::full_capabilities(),
2009            initializer: None,
2010            disk_based_diagnostics_progress_token: None,
2011            initialization_options: None,
2012            disk_based_diagnostics_sources: Vec::new(),
2013            prettier_plugins: Vec::new(),
2014            language_server_binary: LanguageServerBinary {
2015                path: "/the/fake/lsp/path".into(),
2016                arguments: vec![],
2017                env: Default::default(),
2018            },
2019            label_for_completion: None,
2020        }
2021    }
2022}
2023
2024#[cfg(any(test, feature = "test-support"))]
2025#[async_trait(?Send)]
2026impl LspAdapter for FakeLspAdapter {
2027    fn name(&self) -> LanguageServerName {
2028        LanguageServerName(self.name.into())
2029    }
2030
2031    async fn check_if_user_installed(
2032        &self,
2033        _: &dyn LspAdapterDelegate,
2034        _: Arc<dyn LanguageToolchainStore>,
2035        _: &AsyncApp,
2036    ) -> Option<LanguageServerBinary> {
2037        Some(self.language_server_binary.clone())
2038    }
2039
2040    fn get_language_server_command<'a>(
2041        self: Arc<Self>,
2042        _: Arc<dyn LspAdapterDelegate>,
2043        _: Arc<dyn LanguageToolchainStore>,
2044        _: LanguageServerBinaryOptions,
2045        _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
2046        _: &'a mut AsyncApp,
2047    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
2048        async move { Ok(self.language_server_binary.clone()) }.boxed_local()
2049    }
2050
2051    async fn fetch_latest_server_version(
2052        &self,
2053        _: &dyn LspAdapterDelegate,
2054    ) -> Result<Box<dyn 'static + Send + Any>> {
2055        unreachable!();
2056    }
2057
2058    async fn fetch_server_binary(
2059        &self,
2060        _: Box<dyn 'static + Send + Any>,
2061        _: PathBuf,
2062        _: &dyn LspAdapterDelegate,
2063    ) -> Result<LanguageServerBinary> {
2064        unreachable!();
2065    }
2066
2067    async fn cached_server_binary(
2068        &self,
2069        _: PathBuf,
2070        _: &dyn LspAdapterDelegate,
2071    ) -> Option<LanguageServerBinary> {
2072        unreachable!();
2073    }
2074
2075    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2076        self.disk_based_diagnostics_sources.clone()
2077    }
2078
2079    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2080        self.disk_based_diagnostics_progress_token.clone()
2081    }
2082
2083    async fn initialization_options(
2084        self: Arc<Self>,
2085        _: &dyn Fs,
2086        _: &Arc<dyn LspAdapterDelegate>,
2087    ) -> Result<Option<Value>> {
2088        Ok(self.initialization_options.clone())
2089    }
2090
2091    async fn label_for_completion(
2092        &self,
2093        item: &lsp::CompletionItem,
2094        language: &Arc<Language>,
2095    ) -> Option<CodeLabel> {
2096        let label_for_completion = self.label_for_completion.as_ref()?;
2097        label_for_completion(item, language)
2098    }
2099}
2100
2101fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
2102    for (ix, name) in query.capture_names().iter().enumerate() {
2103        for (capture_name, index) in captures.iter_mut() {
2104            if capture_name == name {
2105                **index = Some(ix as u32);
2106                break;
2107            }
2108        }
2109    }
2110}
2111
2112pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2113    lsp::Position::new(point.row, point.column)
2114}
2115
2116pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2117    Unclipped(PointUtf16::new(point.line, point.character))
2118}
2119
2120pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2121    if range.start > range.end {
2122        Err(anyhow!(
2123            "Inverted range provided to an LSP request: {:?}-{:?}",
2124            range.start,
2125            range.end
2126        ))
2127    } else {
2128        Ok(lsp::Range {
2129            start: point_to_lsp(range.start),
2130            end: point_to_lsp(range.end),
2131        })
2132    }
2133}
2134
2135pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2136    let mut start = point_from_lsp(range.start);
2137    let mut end = point_from_lsp(range.end);
2138    if start > end {
2139        log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2140        mem::swap(&mut start, &mut end);
2141    }
2142    start..end
2143}
2144
2145#[cfg(test)]
2146mod tests {
2147    use super::*;
2148    use gpui::TestAppContext;
2149
2150    #[gpui::test(iterations = 10)]
2151    async fn test_language_loading(cx: &mut TestAppContext) {
2152        let languages = LanguageRegistry::test(cx.executor());
2153        let languages = Arc::new(languages);
2154        languages.register_native_grammars([
2155            ("json", tree_sitter_json::LANGUAGE),
2156            ("rust", tree_sitter_rust::LANGUAGE),
2157        ]);
2158        languages.register_test_language(LanguageConfig {
2159            name: "JSON".into(),
2160            grammar: Some("json".into()),
2161            matcher: LanguageMatcher {
2162                path_suffixes: vec!["json".into()],
2163                ..Default::default()
2164            },
2165            ..Default::default()
2166        });
2167        languages.register_test_language(LanguageConfig {
2168            name: "Rust".into(),
2169            grammar: Some("rust".into()),
2170            matcher: LanguageMatcher {
2171                path_suffixes: vec!["rs".into()],
2172                ..Default::default()
2173            },
2174            ..Default::default()
2175        });
2176        assert_eq!(
2177            languages.language_names(),
2178            &[
2179                "JSON".to_string(),
2180                "Plain Text".to_string(),
2181                "Rust".to_string(),
2182            ]
2183        );
2184
2185        let rust1 = languages.language_for_name("Rust");
2186        let rust2 = languages.language_for_name("Rust");
2187
2188        // Ensure language is still listed even if it's being loaded.
2189        assert_eq!(
2190            languages.language_names(),
2191            &[
2192                "JSON".to_string(),
2193                "Plain Text".to_string(),
2194                "Rust".to_string(),
2195            ]
2196        );
2197
2198        let (rust1, rust2) = futures::join!(rust1, rust2);
2199        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2200
2201        // Ensure language is still listed even after loading it.
2202        assert_eq!(
2203            languages.language_names(),
2204            &[
2205                "JSON".to_string(),
2206                "Plain Text".to_string(),
2207                "Rust".to_string(),
2208            ]
2209        );
2210
2211        // Loading an unknown language returns an error.
2212        assert!(languages.language_for_name("Unknown").await.is_err());
2213    }
2214}