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