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