language.rs

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