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