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