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