language.rs

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