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)]
 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(default, deserialize_with = "deserialize_regex")]
 694    #[schemars(schema_with = "regex_json_schema")]
 695    pub increase_indent_pattern: Option<Regex>,
 696    /// A regex that is used to determine whether the indentation level should be
 697    /// decreased in the following line.
 698    #[serde(default, deserialize_with = "deserialize_regex")]
 699    #[schemars(schema_with = "regex_json_schema")]
 700    pub decrease_indent_pattern: Option<Regex>,
 701    /// A list of characters that trigger the automatic insertion of a closing
 702    /// bracket when they immediately precede the point where an opening
 703    /// bracket is inserted.
 704    #[serde(default)]
 705    pub autoclose_before: String,
 706    /// A placeholder used internally by Semantic Index.
 707    #[serde(default)]
 708    pub collapsed_placeholder: String,
 709    /// A line comment string that is inserted in e.g. `toggle comments` action.
 710    /// A language can have multiple flavours of line comments. All of the provided line comments are
 711    /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
 712    #[serde(default)]
 713    pub line_comments: Vec<Arc<str>>,
 714    /// Starting and closing characters of a block comment.
 715    #[serde(default)]
 716    pub block_comment: Option<(Arc<str>, Arc<str>)>,
 717    /// A list of language servers that are allowed to run on subranges of a given language.
 718    #[serde(default)]
 719    pub scope_opt_in_language_servers: Vec<LanguageServerName>,
 720    #[serde(default)]
 721    pub overrides: HashMap<String, LanguageConfigOverride>,
 722    /// A list of characters that Zed should treat as word characters for the
 723    /// purpose of features that operate on word boundaries, like 'move to next word end'
 724    /// or a whole-word search in buffer search.
 725    #[serde(default)]
 726    pub word_characters: HashSet<char>,
 727    /// Whether to indent lines using tab characters, as opposed to multiple
 728    /// spaces.
 729    #[serde(default)]
 730    pub hard_tabs: Option<bool>,
 731    /// How many columns a tab should occupy.
 732    #[serde(default)]
 733    pub tab_size: Option<NonZeroU32>,
 734    /// How to soft-wrap long lines of text.
 735    #[serde(default)]
 736    pub soft_wrap: Option<SoftWrap>,
 737    /// The name of a Prettier parser that will be used for this language when no file path is available.
 738    /// If there's a parser name in the language settings, that will be used instead.
 739    #[serde(default)]
 740    pub prettier_parser_name: Option<String>,
 741    /// If true, this language is only for syntax highlighting via an injection into other
 742    /// languages, but should not appear to the user as a distinct language.
 743    #[serde(default)]
 744    pub hidden: bool,
 745    /// If configured, this language contains JSX style tags, and should support auto-closing of those tags.
 746    #[serde(default)]
 747    pub jsx_tag_auto_close: Option<JsxTagAutoCloseConfig>,
 748    /// A list of characters that Zed should treat as word characters for completion queries.
 749    #[serde(default)]
 750    pub completion_query_characters: HashSet<char>,
 751    /// A list of preferred debuggers for this language.
 752    #[serde(default)]
 753    pub debuggers: IndexSet<SharedString>,
 754}
 755
 756#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
 757pub struct LanguageMatcher {
 758    /// 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`.
 759    #[serde(default)]
 760    pub path_suffixes: Vec<String>,
 761    /// A regex pattern that determines whether the language should be assigned to a file or not.
 762    #[serde(
 763        default,
 764        serialize_with = "serialize_regex",
 765        deserialize_with = "deserialize_regex"
 766    )]
 767    #[schemars(schema_with = "regex_json_schema")]
 768    pub first_line_pattern: Option<Regex>,
 769}
 770
 771/// The configuration for JSX tag auto-closing.
 772#[derive(Clone, Deserialize, JsonSchema)]
 773pub struct JsxTagAutoCloseConfig {
 774    /// The name of the node for a opening tag
 775    pub open_tag_node_name: String,
 776    /// The name of the node for an closing tag
 777    pub close_tag_node_name: String,
 778    /// The name of the node for a complete element with children for open and close tags
 779    pub jsx_element_node_name: String,
 780    /// The name of the node found within both opening and closing
 781    /// tags that describes the tag name
 782    pub tag_name_node_name: String,
 783    /// Alternate Node names for tag names.
 784    /// Specifically needed as TSX represents the name in `<Foo.Bar>`
 785    /// as `member_expression` rather than `identifier` as usual
 786    #[serde(default)]
 787    pub tag_name_node_name_alternates: Vec<String>,
 788    /// Some grammars are smart enough to detect a closing tag
 789    /// that is not valid i.e. doesn't match it's corresponding
 790    /// opening tag or does not have a corresponding opening tag
 791    /// This should be set to the name of the node for invalid
 792    /// closing tags if the grammar contains such a node, otherwise
 793    /// detecting already closed tags will not work properly
 794    #[serde(default)]
 795    pub erroneous_close_tag_node_name: Option<String>,
 796    /// See above for erroneous_close_tag_node_name for details
 797    /// This should be set if the node used for the tag name
 798    /// within erroneous closing tags is different from the
 799    /// normal tag name node name
 800    #[serde(default)]
 801    pub erroneous_close_tag_name_node_name: Option<String>,
 802}
 803
 804/// Represents a language for the given range. Some languages (e.g. HTML)
 805/// interleave several languages together, thus a single buffer might actually contain
 806/// several nested scopes.
 807#[derive(Clone, Debug)]
 808pub struct LanguageScope {
 809    language: Arc<Language>,
 810    override_id: Option<u32>,
 811}
 812
 813#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
 814pub struct LanguageConfigOverride {
 815    #[serde(default)]
 816    pub line_comments: Override<Vec<Arc<str>>>,
 817    #[serde(default)]
 818    pub block_comment: Override<(Arc<str>, Arc<str>)>,
 819    #[serde(skip)]
 820    pub disabled_bracket_ixs: Vec<u16>,
 821    #[serde(default)]
 822    pub word_characters: Override<HashSet<char>>,
 823    #[serde(default)]
 824    pub completion_query_characters: Override<HashSet<char>>,
 825    #[serde(default)]
 826    pub opt_into_language_servers: Vec<LanguageServerName>,
 827}
 828
 829#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
 830#[serde(untagged)]
 831pub enum Override<T> {
 832    Remove { remove: bool },
 833    Set(T),
 834}
 835
 836impl<T> Default for Override<T> {
 837    fn default() -> Self {
 838        Override::Remove { remove: false }
 839    }
 840}
 841
 842impl<T> Override<T> {
 843    fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
 844        match this {
 845            Some(Self::Set(value)) => Some(value),
 846            Some(Self::Remove { remove: true }) => None,
 847            Some(Self::Remove { remove: false }) | None => original,
 848        }
 849    }
 850}
 851
 852impl Default for LanguageConfig {
 853    fn default() -> Self {
 854        Self {
 855            name: LanguageName::new(""),
 856            code_fence_block_name: None,
 857            grammar: None,
 858            matcher: LanguageMatcher::default(),
 859            brackets: Default::default(),
 860            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
 861            auto_indent_on_paste: None,
 862            increase_indent_pattern: Default::default(),
 863            decrease_indent_pattern: Default::default(),
 864            autoclose_before: Default::default(),
 865            line_comments: Default::default(),
 866            block_comment: Default::default(),
 867            scope_opt_in_language_servers: Default::default(),
 868            overrides: Default::default(),
 869            word_characters: Default::default(),
 870            collapsed_placeholder: Default::default(),
 871            hard_tabs: None,
 872            tab_size: None,
 873            soft_wrap: None,
 874            prettier_parser_name: None,
 875            hidden: false,
 876            jsx_tag_auto_close: None,
 877            completion_query_characters: Default::default(),
 878            debuggers: Default::default(),
 879        }
 880    }
 881}
 882
 883fn auto_indent_using_last_non_empty_line_default() -> bool {
 884    true
 885}
 886
 887fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
 888    let source = Option::<String>::deserialize(d)?;
 889    if let Some(source) = source {
 890        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
 891    } else {
 892        Ok(None)
 893    }
 894}
 895
 896fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
 897    Schema::Object(SchemaObject {
 898        instance_type: Some(InstanceType::String.into()),
 899        ..Default::default()
 900    })
 901}
 902
 903fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
 904where
 905    S: Serializer,
 906{
 907    match regex {
 908        Some(regex) => serializer.serialize_str(regex.as_str()),
 909        None => serializer.serialize_none(),
 910    }
 911}
 912
 913#[doc(hidden)]
 914#[cfg(any(test, feature = "test-support"))]
 915pub struct FakeLspAdapter {
 916    pub name: &'static str,
 917    pub initialization_options: Option<Value>,
 918    pub prettier_plugins: Vec<&'static str>,
 919    pub disk_based_diagnostics_progress_token: Option<String>,
 920    pub disk_based_diagnostics_sources: Vec<String>,
 921    pub language_server_binary: LanguageServerBinary,
 922
 923    pub capabilities: lsp::ServerCapabilities,
 924    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
 925    pub label_for_completion: Option<
 926        Box<
 927            dyn 'static
 928                + Send
 929                + Sync
 930                + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
 931        >,
 932    >,
 933}
 934
 935/// Configuration of handling bracket pairs for a given language.
 936///
 937/// This struct includes settings for defining which pairs of characters are considered brackets and
 938/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
 939#[derive(Clone, Debug, Default, JsonSchema)]
 940pub struct BracketPairConfig {
 941    /// A list of character pairs that should be treated as brackets in the context of a given language.
 942    pub pairs: Vec<BracketPair>,
 943    /// A list of tree-sitter scopes for which a given bracket should not be active.
 944    /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
 945    #[serde(skip)]
 946    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
 947}
 948
 949impl BracketPairConfig {
 950    pub fn is_closing_brace(&self, c: char) -> bool {
 951        self.pairs.iter().any(|pair| pair.end.starts_with(c))
 952    }
 953}
 954
 955fn bracket_pair_config_json_schema(r#gen: &mut SchemaGenerator) -> Schema {
 956    Option::<Vec<BracketPairContent>>::json_schema(r#gen)
 957}
 958
 959#[derive(Deserialize, JsonSchema)]
 960pub struct BracketPairContent {
 961    #[serde(flatten)]
 962    pub bracket_pair: BracketPair,
 963    #[serde(default)]
 964    pub not_in: Vec<String>,
 965}
 966
 967impl<'de> Deserialize<'de> for BracketPairConfig {
 968    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 969    where
 970        D: Deserializer<'de>,
 971    {
 972        let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
 973        let mut brackets = Vec::with_capacity(result.len());
 974        let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
 975        for entry in result {
 976            brackets.push(entry.bracket_pair);
 977            disabled_scopes_by_bracket_ix.push(entry.not_in);
 978        }
 979
 980        Ok(BracketPairConfig {
 981            pairs: brackets,
 982            disabled_scopes_by_bracket_ix,
 983        })
 984    }
 985}
 986
 987/// Describes a single bracket pair and how an editor should react to e.g. inserting
 988/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
 989#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
 990pub struct BracketPair {
 991    /// Starting substring for a bracket.
 992    pub start: String,
 993    /// Ending substring for a bracket.
 994    pub end: String,
 995    /// True if `end` should be automatically inserted right after `start` characters.
 996    pub close: bool,
 997    /// True if selected text should be surrounded by `start` and `end` characters.
 998    #[serde(default = "default_true")]
 999    pub surround: bool,
1000    /// True if an extra newline should be inserted while the cursor is in the middle
1001    /// of that bracket pair.
1002    pub newline: bool,
1003}
1004
1005#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1006pub struct LanguageId(usize);
1007
1008impl LanguageId {
1009    pub(crate) fn new() -> Self {
1010        Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
1011    }
1012}
1013
1014pub struct Language {
1015    pub(crate) id: LanguageId,
1016    pub(crate) config: LanguageConfig,
1017    pub(crate) grammar: Option<Arc<Grammar>>,
1018    pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
1019    pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
1020}
1021
1022#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1023pub struct GrammarId(pub usize);
1024
1025impl GrammarId {
1026    pub(crate) fn new() -> Self {
1027        Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
1028    }
1029}
1030
1031pub struct Grammar {
1032    id: GrammarId,
1033    pub ts_language: tree_sitter::Language,
1034    pub(crate) error_query: Option<Query>,
1035    pub(crate) highlights_query: Option<Query>,
1036    pub(crate) brackets_config: Option<BracketsConfig>,
1037    pub(crate) redactions_config: Option<RedactionConfig>,
1038    pub(crate) runnable_config: Option<RunnableConfig>,
1039    pub(crate) debug_variables_config: Option<DebugVariablesConfig>,
1040    pub(crate) indents_config: Option<IndentConfig>,
1041    pub outline_config: Option<OutlineConfig>,
1042    pub text_object_config: Option<TextObjectConfig>,
1043    pub embedding_config: Option<EmbeddingConfig>,
1044    pub(crate) injection_config: Option<InjectionConfig>,
1045    pub(crate) override_config: Option<OverrideConfig>,
1046    pub(crate) highlight_map: Mutex<HighlightMap>,
1047}
1048
1049struct IndentConfig {
1050    query: Query,
1051    indent_capture_ix: u32,
1052    start_capture_ix: Option<u32>,
1053    end_capture_ix: Option<u32>,
1054    outdent_capture_ix: Option<u32>,
1055}
1056
1057pub struct OutlineConfig {
1058    pub query: Query,
1059    pub item_capture_ix: u32,
1060    pub name_capture_ix: u32,
1061    pub context_capture_ix: Option<u32>,
1062    pub extra_context_capture_ix: Option<u32>,
1063    pub open_capture_ix: Option<u32>,
1064    pub close_capture_ix: Option<u32>,
1065    pub annotation_capture_ix: Option<u32>,
1066}
1067
1068#[derive(Debug, Clone, Copy, PartialEq)]
1069pub enum TextObject {
1070    InsideFunction,
1071    AroundFunction,
1072    InsideClass,
1073    AroundClass,
1074    InsideComment,
1075    AroundComment,
1076}
1077
1078impl TextObject {
1079    pub fn from_capture_name(name: &str) -> Option<TextObject> {
1080        match name {
1081            "function.inside" => Some(TextObject::InsideFunction),
1082            "function.around" => Some(TextObject::AroundFunction),
1083            "class.inside" => Some(TextObject::InsideClass),
1084            "class.around" => Some(TextObject::AroundClass),
1085            "comment.inside" => Some(TextObject::InsideComment),
1086            "comment.around" => Some(TextObject::AroundComment),
1087            _ => None,
1088        }
1089    }
1090
1091    pub fn around(&self) -> Option<Self> {
1092        match self {
1093            TextObject::InsideFunction => Some(TextObject::AroundFunction),
1094            TextObject::InsideClass => Some(TextObject::AroundClass),
1095            TextObject::InsideComment => Some(TextObject::AroundComment),
1096            _ => None,
1097        }
1098    }
1099}
1100
1101pub struct TextObjectConfig {
1102    pub query: Query,
1103    pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1104}
1105
1106#[derive(Debug)]
1107pub struct EmbeddingConfig {
1108    pub query: Query,
1109    pub item_capture_ix: u32,
1110    pub name_capture_ix: Option<u32>,
1111    pub context_capture_ix: Option<u32>,
1112    pub collapse_capture_ix: Option<u32>,
1113    pub keep_capture_ix: Option<u32>,
1114}
1115
1116struct InjectionConfig {
1117    query: Query,
1118    content_capture_ix: u32,
1119    language_capture_ix: Option<u32>,
1120    patterns: Vec<InjectionPatternConfig>,
1121}
1122
1123struct RedactionConfig {
1124    pub query: Query,
1125    pub redaction_capture_ix: u32,
1126}
1127
1128#[derive(Clone, Debug, PartialEq)]
1129enum RunnableCapture {
1130    Named(SharedString),
1131    Run,
1132}
1133
1134struct RunnableConfig {
1135    pub query: Query,
1136    /// A mapping from capture indice to capture kind
1137    pub extra_captures: Vec<RunnableCapture>,
1138}
1139
1140#[derive(Clone, Debug, PartialEq)]
1141enum DebugVariableCapture {
1142    Named(SharedString),
1143    Variable,
1144}
1145
1146#[derive(Debug)]
1147struct DebugVariablesConfig {
1148    pub query: Query,
1149    pub captures: Vec<DebugVariableCapture>,
1150}
1151
1152struct OverrideConfig {
1153    query: Query,
1154    values: HashMap<u32, OverrideEntry>,
1155}
1156
1157#[derive(Debug)]
1158struct OverrideEntry {
1159    name: String,
1160    range_is_inclusive: bool,
1161    value: LanguageConfigOverride,
1162}
1163
1164#[derive(Default, Clone)]
1165struct InjectionPatternConfig {
1166    language: Option<Box<str>>,
1167    combined: bool,
1168}
1169
1170struct BracketsConfig {
1171    query: Query,
1172    open_capture_ix: u32,
1173    close_capture_ix: u32,
1174    patterns: Vec<BracketsPatternConfig>,
1175}
1176
1177#[derive(Clone, Debug, Default)]
1178struct BracketsPatternConfig {
1179    newline_only: bool,
1180}
1181
1182impl Language {
1183    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1184        Self::new_with_id(LanguageId::new(), config, ts_language)
1185    }
1186
1187    pub fn id(&self) -> LanguageId {
1188        self.id
1189    }
1190
1191    fn new_with_id(
1192        id: LanguageId,
1193        config: LanguageConfig,
1194        ts_language: Option<tree_sitter::Language>,
1195    ) -> Self {
1196        Self {
1197            id,
1198            config,
1199            grammar: ts_language.map(|ts_language| {
1200                Arc::new(Grammar {
1201                    id: GrammarId::new(),
1202                    highlights_query: None,
1203                    brackets_config: None,
1204                    outline_config: None,
1205                    text_object_config: None,
1206                    embedding_config: None,
1207                    indents_config: None,
1208                    injection_config: None,
1209                    override_config: None,
1210                    redactions_config: None,
1211                    runnable_config: None,
1212                    debug_variables_config: None,
1213                    error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1214                    ts_language,
1215                    highlight_map: Default::default(),
1216                })
1217            }),
1218            context_provider: None,
1219            toolchain: None,
1220        }
1221    }
1222
1223    pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1224        self.context_provider = provider;
1225        self
1226    }
1227
1228    pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1229        self.toolchain = provider;
1230        self
1231    }
1232
1233    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1234        if let Some(query) = queries.highlights {
1235            self = self
1236                .with_highlights_query(query.as_ref())
1237                .context("Error loading highlights query")?;
1238        }
1239        if let Some(query) = queries.brackets {
1240            self = self
1241                .with_brackets_query(query.as_ref())
1242                .context("Error loading brackets query")?;
1243        }
1244        if let Some(query) = queries.indents {
1245            self = self
1246                .with_indents_query(query.as_ref())
1247                .context("Error loading indents query")?;
1248        }
1249        if let Some(query) = queries.outline {
1250            self = self
1251                .with_outline_query(query.as_ref())
1252                .context("Error loading outline query")?;
1253        }
1254        if let Some(query) = queries.embedding {
1255            self = self
1256                .with_embedding_query(query.as_ref())
1257                .context("Error loading embedding query")?;
1258        }
1259        if let Some(query) = queries.injections {
1260            self = self
1261                .with_injection_query(query.as_ref())
1262                .context("Error loading injection query")?;
1263        }
1264        if let Some(query) = queries.overrides {
1265            self = self
1266                .with_override_query(query.as_ref())
1267                .context("Error loading override query")?;
1268        }
1269        if let Some(query) = queries.redactions {
1270            self = self
1271                .with_redaction_query(query.as_ref())
1272                .context("Error loading redaction query")?;
1273        }
1274        if let Some(query) = queries.runnables {
1275            self = self
1276                .with_runnable_query(query.as_ref())
1277                .context("Error loading runnables query")?;
1278        }
1279        if let Some(query) = queries.text_objects {
1280            self = self
1281                .with_text_object_query(query.as_ref())
1282                .context("Error loading textobject query")?;
1283        }
1284        if let Some(query) = queries.debug_variables {
1285            self = self
1286                .with_debug_variables_query(query.as_ref())
1287                .context("Error loading debug variable query")?;
1288        }
1289        Ok(self)
1290    }
1291
1292    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1293        let grammar = self
1294            .grammar_mut()
1295            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1296        grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1297        Ok(self)
1298    }
1299
1300    pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1301        let grammar = self
1302            .grammar_mut()
1303            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1304
1305        let query = Query::new(&grammar.ts_language, source)?;
1306        let mut extra_captures = Vec::with_capacity(query.capture_names().len());
1307
1308        for name in query.capture_names().iter() {
1309            let kind = if *name == "run" {
1310                RunnableCapture::Run
1311            } else {
1312                RunnableCapture::Named(name.to_string().into())
1313            };
1314            extra_captures.push(kind);
1315        }
1316
1317        grammar.runnable_config = Some(RunnableConfig {
1318            extra_captures,
1319            query,
1320        });
1321
1322        Ok(self)
1323    }
1324
1325    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1326        let grammar = self
1327            .grammar_mut()
1328            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1329        let query = Query::new(&grammar.ts_language, source)?;
1330        let mut item_capture_ix = None;
1331        let mut name_capture_ix = None;
1332        let mut context_capture_ix = None;
1333        let mut extra_context_capture_ix = None;
1334        let mut open_capture_ix = None;
1335        let mut close_capture_ix = None;
1336        let mut annotation_capture_ix = None;
1337        get_capture_indices(
1338            &query,
1339            &mut [
1340                ("item", &mut item_capture_ix),
1341                ("name", &mut name_capture_ix),
1342                ("context", &mut context_capture_ix),
1343                ("context.extra", &mut extra_context_capture_ix),
1344                ("open", &mut open_capture_ix),
1345                ("close", &mut close_capture_ix),
1346                ("annotation", &mut annotation_capture_ix),
1347            ],
1348        );
1349        if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1350            grammar.outline_config = Some(OutlineConfig {
1351                query,
1352                item_capture_ix,
1353                name_capture_ix,
1354                context_capture_ix,
1355                extra_context_capture_ix,
1356                open_capture_ix,
1357                close_capture_ix,
1358                annotation_capture_ix,
1359            });
1360        }
1361        Ok(self)
1362    }
1363
1364    pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1365        let grammar = self
1366            .grammar_mut()
1367            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1368        let query = Query::new(&grammar.ts_language, source)?;
1369
1370        let mut text_objects_by_capture_ix = Vec::new();
1371        for (ix, name) in query.capture_names().iter().enumerate() {
1372            if let Some(text_object) = TextObject::from_capture_name(name) {
1373                text_objects_by_capture_ix.push((ix as u32, text_object));
1374            }
1375        }
1376
1377        grammar.text_object_config = Some(TextObjectConfig {
1378            query,
1379            text_objects_by_capture_ix,
1380        });
1381        Ok(self)
1382    }
1383
1384    pub fn with_debug_variables_query(mut self, source: &str) -> Result<Self> {
1385        let grammar = self
1386            .grammar_mut()
1387            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1388        let query = Query::new(&grammar.ts_language, source)?;
1389
1390        let mut captures = Vec::new();
1391        for name in query.capture_names() {
1392            captures.push(if *name == "debug_variable" {
1393                DebugVariableCapture::Variable
1394            } else {
1395                DebugVariableCapture::Named(name.to_string().into())
1396            });
1397        }
1398        grammar.debug_variables_config = Some(DebugVariablesConfig { query, captures });
1399
1400        Ok(self)
1401    }
1402
1403    pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1404        let grammar = self
1405            .grammar_mut()
1406            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1407        let query = Query::new(&grammar.ts_language, source)?;
1408        let mut item_capture_ix = None;
1409        let mut name_capture_ix = None;
1410        let mut context_capture_ix = None;
1411        let mut collapse_capture_ix = None;
1412        let mut keep_capture_ix = None;
1413        get_capture_indices(
1414            &query,
1415            &mut [
1416                ("item", &mut item_capture_ix),
1417                ("name", &mut name_capture_ix),
1418                ("context", &mut context_capture_ix),
1419                ("keep", &mut keep_capture_ix),
1420                ("collapse", &mut collapse_capture_ix),
1421            ],
1422        );
1423        if let Some(item_capture_ix) = item_capture_ix {
1424            grammar.embedding_config = Some(EmbeddingConfig {
1425                query,
1426                item_capture_ix,
1427                name_capture_ix,
1428                context_capture_ix,
1429                collapse_capture_ix,
1430                keep_capture_ix,
1431            });
1432        }
1433        Ok(self)
1434    }
1435
1436    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1437        let grammar = self
1438            .grammar_mut()
1439            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1440        let query = Query::new(&grammar.ts_language, source)?;
1441        let mut open_capture_ix = None;
1442        let mut close_capture_ix = None;
1443        get_capture_indices(
1444            &query,
1445            &mut [
1446                ("open", &mut open_capture_ix),
1447                ("close", &mut close_capture_ix),
1448            ],
1449        );
1450        let patterns = (0..query.pattern_count())
1451            .map(|ix| {
1452                let mut config = BracketsPatternConfig::default();
1453                for setting in query.property_settings(ix) {
1454                    match setting.key.as_ref() {
1455                        "newline.only" => config.newline_only = true,
1456                        _ => {}
1457                    }
1458                }
1459                config
1460            })
1461            .collect();
1462        if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1463            grammar.brackets_config = Some(BracketsConfig {
1464                query,
1465                open_capture_ix,
1466                close_capture_ix,
1467                patterns,
1468            });
1469        }
1470        Ok(self)
1471    }
1472
1473    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1474        let grammar = self
1475            .grammar_mut()
1476            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1477        let query = Query::new(&grammar.ts_language, source)?;
1478        let mut indent_capture_ix = None;
1479        let mut start_capture_ix = None;
1480        let mut end_capture_ix = None;
1481        let mut outdent_capture_ix = None;
1482        get_capture_indices(
1483            &query,
1484            &mut [
1485                ("indent", &mut indent_capture_ix),
1486                ("start", &mut start_capture_ix),
1487                ("end", &mut end_capture_ix),
1488                ("outdent", &mut outdent_capture_ix),
1489            ],
1490        );
1491        if let Some(indent_capture_ix) = indent_capture_ix {
1492            grammar.indents_config = Some(IndentConfig {
1493                query,
1494                indent_capture_ix,
1495                start_capture_ix,
1496                end_capture_ix,
1497                outdent_capture_ix,
1498            });
1499        }
1500        Ok(self)
1501    }
1502
1503    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1504        let grammar = self
1505            .grammar_mut()
1506            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1507        let query = Query::new(&grammar.ts_language, source)?;
1508        let mut language_capture_ix = None;
1509        let mut injection_language_capture_ix = None;
1510        let mut content_capture_ix = None;
1511        let mut injection_content_capture_ix = None;
1512        get_capture_indices(
1513            &query,
1514            &mut [
1515                ("language", &mut language_capture_ix),
1516                ("injection.language", &mut injection_language_capture_ix),
1517                ("content", &mut content_capture_ix),
1518                ("injection.content", &mut injection_content_capture_ix),
1519            ],
1520        );
1521        language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1522            (None, Some(ix)) => Some(ix),
1523            (Some(_), Some(_)) => {
1524                return Err(anyhow!(
1525                    "both language and injection.language captures are present"
1526                ));
1527            }
1528            _ => language_capture_ix,
1529        };
1530        content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1531            (None, Some(ix)) => Some(ix),
1532            (Some(_), Some(_)) => {
1533                return Err(anyhow!(
1534                    "both content and injection.content captures are present"
1535                ));
1536            }
1537            _ => content_capture_ix,
1538        };
1539        let patterns = (0..query.pattern_count())
1540            .map(|ix| {
1541                let mut config = InjectionPatternConfig::default();
1542                for setting in query.property_settings(ix) {
1543                    match setting.key.as_ref() {
1544                        "language" | "injection.language" => {
1545                            config.language.clone_from(&setting.value);
1546                        }
1547                        "combined" | "injection.combined" => {
1548                            config.combined = true;
1549                        }
1550                        _ => {}
1551                    }
1552                }
1553                config
1554            })
1555            .collect();
1556        if let Some(content_capture_ix) = content_capture_ix {
1557            grammar.injection_config = Some(InjectionConfig {
1558                query,
1559                language_capture_ix,
1560                content_capture_ix,
1561                patterns,
1562            });
1563        }
1564        Ok(self)
1565    }
1566
1567    pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1568        let query = {
1569            let grammar = self
1570                .grammar
1571                .as_ref()
1572                .ok_or_else(|| anyhow!("no grammar for language"))?;
1573            Query::new(&grammar.ts_language, source)?
1574        };
1575
1576        let mut override_configs_by_id = HashMap::default();
1577        for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1578            let mut range_is_inclusive = false;
1579            if name.starts_with('_') {
1580                continue;
1581            }
1582            if let Some(prefix) = name.strip_suffix(".inclusive") {
1583                name = prefix;
1584                range_is_inclusive = true;
1585            }
1586
1587            let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1588            for server_name in &value.opt_into_language_servers {
1589                if !self
1590                    .config
1591                    .scope_opt_in_language_servers
1592                    .contains(server_name)
1593                {
1594                    util::debug_panic!(
1595                        "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1596                    );
1597                }
1598            }
1599
1600            override_configs_by_id.insert(
1601                ix as u32,
1602                OverrideEntry {
1603                    name: name.to_string(),
1604                    range_is_inclusive,
1605                    value,
1606                },
1607            );
1608        }
1609
1610        let referenced_override_names = self.config.overrides.keys().chain(
1611            self.config
1612                .brackets
1613                .disabled_scopes_by_bracket_ix
1614                .iter()
1615                .flatten(),
1616        );
1617
1618        for referenced_name in referenced_override_names {
1619            if !override_configs_by_id
1620                .values()
1621                .any(|entry| entry.name == *referenced_name)
1622            {
1623                Err(anyhow!(
1624                    "language {:?} has overrides in config not in query: {referenced_name:?}",
1625                    self.config.name
1626                ))?;
1627            }
1628        }
1629
1630        for entry in override_configs_by_id.values_mut() {
1631            entry.value.disabled_bracket_ixs = self
1632                .config
1633                .brackets
1634                .disabled_scopes_by_bracket_ix
1635                .iter()
1636                .enumerate()
1637                .filter_map(|(ix, disabled_scope_names)| {
1638                    if disabled_scope_names.contains(&entry.name) {
1639                        Some(ix as u16)
1640                    } else {
1641                        None
1642                    }
1643                })
1644                .collect();
1645        }
1646
1647        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1648
1649        let grammar = self
1650            .grammar_mut()
1651            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1652        grammar.override_config = Some(OverrideConfig {
1653            query,
1654            values: override_configs_by_id,
1655        });
1656        Ok(self)
1657    }
1658
1659    pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1660        let grammar = self
1661            .grammar_mut()
1662            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1663
1664        let query = Query::new(&grammar.ts_language, source)?;
1665        let mut redaction_capture_ix = None;
1666        get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1667
1668        if let Some(redaction_capture_ix) = redaction_capture_ix {
1669            grammar.redactions_config = Some(RedactionConfig {
1670                query,
1671                redaction_capture_ix,
1672            });
1673        }
1674
1675        Ok(self)
1676    }
1677
1678    fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1679        Arc::get_mut(self.grammar.as_mut()?)
1680    }
1681
1682    pub fn name(&self) -> LanguageName {
1683        self.config.name.clone()
1684    }
1685
1686    pub fn code_fence_block_name(&self) -> Arc<str> {
1687        self.config
1688            .code_fence_block_name
1689            .clone()
1690            .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1691    }
1692
1693    pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1694        self.context_provider.clone()
1695    }
1696
1697    pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1698        self.toolchain.clone()
1699    }
1700
1701    pub fn highlight_text<'a>(
1702        self: &'a Arc<Self>,
1703        text: &'a Rope,
1704        range: Range<usize>,
1705    ) -> Vec<(Range<usize>, HighlightId)> {
1706        let mut result = Vec::new();
1707        if let Some(grammar) = &self.grammar {
1708            let tree = grammar.parse_text(text, None);
1709            let captures =
1710                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1711                    grammar.highlights_query.as_ref()
1712                });
1713            let highlight_maps = vec![grammar.highlight_map()];
1714            let mut offset = 0;
1715            for chunk in
1716                BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1717            {
1718                let end_offset = offset + chunk.text.len();
1719                if let Some(highlight_id) = chunk.syntax_highlight_id {
1720                    if !highlight_id.is_default() {
1721                        result.push((offset..end_offset, highlight_id));
1722                    }
1723                }
1724                offset = end_offset;
1725            }
1726        }
1727        result
1728    }
1729
1730    pub fn path_suffixes(&self) -> &[String] {
1731        &self.config.matcher.path_suffixes
1732    }
1733
1734    pub fn should_autoclose_before(&self, c: char) -> bool {
1735        c.is_whitespace() || self.config.autoclose_before.contains(c)
1736    }
1737
1738    pub fn set_theme(&self, theme: &SyntaxTheme) {
1739        if let Some(grammar) = self.grammar.as_ref() {
1740            if let Some(highlights_query) = &grammar.highlights_query {
1741                *grammar.highlight_map.lock() =
1742                    HighlightMap::new(highlights_query.capture_names(), theme);
1743            }
1744        }
1745    }
1746
1747    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1748        self.grammar.as_ref()
1749    }
1750
1751    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1752        LanguageScope {
1753            language: self.clone(),
1754            override_id: None,
1755        }
1756    }
1757
1758    pub fn lsp_id(&self) -> String {
1759        self.config.name.lsp_id()
1760    }
1761
1762    pub fn prettier_parser_name(&self) -> Option<&str> {
1763        self.config.prettier_parser_name.as_deref()
1764    }
1765
1766    pub fn config(&self) -> &LanguageConfig {
1767        &self.config
1768    }
1769}
1770
1771impl LanguageScope {
1772    pub fn path_suffixes(&self) -> &[String] {
1773        &self.language.path_suffixes()
1774    }
1775
1776    pub fn language_name(&self) -> LanguageName {
1777        self.language.config.name.clone()
1778    }
1779
1780    pub fn collapsed_placeholder(&self) -> &str {
1781        self.language.config.collapsed_placeholder.as_ref()
1782    }
1783
1784    /// Returns line prefix that is inserted in e.g. line continuations or
1785    /// in `toggle comments` action.
1786    pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1787        Override::as_option(
1788            self.config_override().map(|o| &o.line_comments),
1789            Some(&self.language.config.line_comments),
1790        )
1791        .map_or([].as_slice(), |e| e.as_slice())
1792    }
1793
1794    pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1795        Override::as_option(
1796            self.config_override().map(|o| &o.block_comment),
1797            self.language.config.block_comment.as_ref(),
1798        )
1799        .map(|e| (&e.0, &e.1))
1800    }
1801
1802    /// Returns a list of language-specific word characters.
1803    ///
1804    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1805    /// the purpose of actions like 'move to next word end` or whole-word search.
1806    /// It additionally accounts for language's additional word characters.
1807    pub fn word_characters(&self) -> Option<&HashSet<char>> {
1808        Override::as_option(
1809            self.config_override().map(|o| &o.word_characters),
1810            Some(&self.language.config.word_characters),
1811        )
1812    }
1813
1814    /// Returns a list of language-specific characters that are considered part of
1815    /// a completion query.
1816    pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
1817        Override::as_option(
1818            self.config_override()
1819                .map(|o| &o.completion_query_characters),
1820            Some(&self.language.config.completion_query_characters),
1821        )
1822    }
1823
1824    /// Returns a list of bracket pairs for a given language with an additional
1825    /// piece of information about whether the particular bracket pair is currently active for a given language.
1826    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1827        let mut disabled_ids = self
1828            .config_override()
1829            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1830        self.language
1831            .config
1832            .brackets
1833            .pairs
1834            .iter()
1835            .enumerate()
1836            .map(move |(ix, bracket)| {
1837                let mut is_enabled = true;
1838                if let Some(next_disabled_ix) = disabled_ids.first() {
1839                    if ix == *next_disabled_ix as usize {
1840                        disabled_ids = &disabled_ids[1..];
1841                        is_enabled = false;
1842                    }
1843                }
1844                (bracket, is_enabled)
1845            })
1846    }
1847
1848    pub fn should_autoclose_before(&self, c: char) -> bool {
1849        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1850    }
1851
1852    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1853        let config = &self.language.config;
1854        let opt_in_servers = &config.scope_opt_in_language_servers;
1855        if opt_in_servers.iter().any(|o| *o == *name) {
1856            if let Some(over) = self.config_override() {
1857                over.opt_into_language_servers.iter().any(|o| *o == *name)
1858            } else {
1859                false
1860            }
1861        } else {
1862            true
1863        }
1864    }
1865
1866    pub fn override_name(&self) -> Option<&str> {
1867        let id = self.override_id?;
1868        let grammar = self.language.grammar.as_ref()?;
1869        let override_config = grammar.override_config.as_ref()?;
1870        override_config.values.get(&id).map(|e| e.name.as_str())
1871    }
1872
1873    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1874        let id = self.override_id?;
1875        let grammar = self.language.grammar.as_ref()?;
1876        let override_config = grammar.override_config.as_ref()?;
1877        override_config.values.get(&id).map(|e| &e.value)
1878    }
1879}
1880
1881impl Hash for Language {
1882    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1883        self.id.hash(state)
1884    }
1885}
1886
1887impl PartialEq for Language {
1888    fn eq(&self, other: &Self) -> bool {
1889        self.id.eq(&other.id)
1890    }
1891}
1892
1893impl Eq for Language {}
1894
1895impl Debug for Language {
1896    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1897        f.debug_struct("Language")
1898            .field("name", &self.config.name)
1899            .finish()
1900    }
1901}
1902
1903impl Grammar {
1904    pub fn id(&self) -> GrammarId {
1905        self.id
1906    }
1907
1908    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1909        with_parser(|parser| {
1910            parser
1911                .set_language(&self.ts_language)
1912                .expect("incompatible grammar");
1913            let mut chunks = text.chunks_in_range(0..text.len());
1914            parser
1915                .parse_with_options(
1916                    &mut move |offset, _| {
1917                        chunks.seek(offset);
1918                        chunks.next().unwrap_or("").as_bytes()
1919                    },
1920                    old_tree.as_ref(),
1921                    None,
1922                )
1923                .unwrap()
1924        })
1925    }
1926
1927    pub fn highlight_map(&self) -> HighlightMap {
1928        self.highlight_map.lock().clone()
1929    }
1930
1931    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1932        let capture_id = self
1933            .highlights_query
1934            .as_ref()?
1935            .capture_index_for_name(name)?;
1936        Some(self.highlight_map.lock().get(capture_id))
1937    }
1938}
1939
1940impl CodeLabel {
1941    pub fn fallback_for_completion(
1942        item: &lsp::CompletionItem,
1943        language: Option<&Language>,
1944    ) -> Self {
1945        let highlight_id = item.kind.and_then(|kind| {
1946            let grammar = language?.grammar()?;
1947            use lsp::CompletionItemKind as Kind;
1948            match kind {
1949                Kind::CLASS => grammar.highlight_id_for_name("type"),
1950                Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
1951                Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
1952                Kind::ENUM => grammar
1953                    .highlight_id_for_name("enum")
1954                    .or_else(|| grammar.highlight_id_for_name("type")),
1955                Kind::ENUM_MEMBER => grammar
1956                    .highlight_id_for_name("variant")
1957                    .or_else(|| grammar.highlight_id_for_name("property")),
1958                Kind::FIELD => grammar.highlight_id_for_name("property"),
1959                Kind::FUNCTION => grammar.highlight_id_for_name("function"),
1960                Kind::INTERFACE => grammar.highlight_id_for_name("type"),
1961                Kind::METHOD => grammar
1962                    .highlight_id_for_name("function.method")
1963                    .or_else(|| grammar.highlight_id_for_name("function")),
1964                Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
1965                Kind::PROPERTY => grammar.highlight_id_for_name("property"),
1966                Kind::STRUCT => grammar.highlight_id_for_name("type"),
1967                Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
1968                Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
1969                _ => None,
1970            }
1971        });
1972
1973        let label = &item.label;
1974        let label_length = label.len();
1975        let runs = highlight_id
1976            .map(|highlight_id| vec![(0..label_length, highlight_id)])
1977            .unwrap_or_default();
1978        let text = if let Some(detail) = item.detail.as_deref().filter(|detail| detail != label) {
1979            format!("{label} {detail}")
1980        } else if let Some(description) = item
1981            .label_details
1982            .as_ref()
1983            .and_then(|label_details| label_details.description.as_deref())
1984            .filter(|description| description != label)
1985        {
1986            format!("{label} {description}")
1987        } else {
1988            label.clone()
1989        };
1990        Self {
1991            text,
1992            runs,
1993            filter_range: 0..label_length,
1994        }
1995    }
1996
1997    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1998        let mut result = Self {
1999            runs: Vec::new(),
2000            filter_range: 0..text.len(),
2001            text,
2002        };
2003        if let Some(filter_text) = filter_text {
2004            if let Some(ix) = result.text.find(filter_text) {
2005                result.filter_range = ix..ix + filter_text.len();
2006            }
2007        }
2008        result
2009    }
2010
2011    pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
2012        let start_ix = self.text.len();
2013        self.text.push_str(text);
2014        let end_ix = self.text.len();
2015        if let Some(highlight) = highlight {
2016            self.runs.push((start_ix..end_ix, highlight));
2017        }
2018    }
2019
2020    pub fn text(&self) -> &str {
2021        self.text.as_str()
2022    }
2023
2024    pub fn filter_text(&self) -> &str {
2025        &self.text[self.filter_range.clone()]
2026    }
2027}
2028
2029impl From<String> for CodeLabel {
2030    fn from(value: String) -> Self {
2031        Self::plain(value, None)
2032    }
2033}
2034
2035impl From<&str> for CodeLabel {
2036    fn from(value: &str) -> Self {
2037        Self::plain(value.to_string(), None)
2038    }
2039}
2040
2041impl Ord for LanguageMatcher {
2042    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2043        self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
2044            self.first_line_pattern
2045                .as_ref()
2046                .map(Regex::as_str)
2047                .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
2048        })
2049    }
2050}
2051
2052impl PartialOrd for LanguageMatcher {
2053    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2054        Some(self.cmp(other))
2055    }
2056}
2057
2058impl Eq for LanguageMatcher {}
2059
2060impl PartialEq for LanguageMatcher {
2061    fn eq(&self, other: &Self) -> bool {
2062        self.path_suffixes == other.path_suffixes
2063            && self.first_line_pattern.as_ref().map(Regex::as_str)
2064                == other.first_line_pattern.as_ref().map(Regex::as_str)
2065    }
2066}
2067
2068#[cfg(any(test, feature = "test-support"))]
2069impl Default for FakeLspAdapter {
2070    fn default() -> Self {
2071        Self {
2072            name: "the-fake-language-server",
2073            capabilities: lsp::LanguageServer::full_capabilities(),
2074            initializer: None,
2075            disk_based_diagnostics_progress_token: None,
2076            initialization_options: None,
2077            disk_based_diagnostics_sources: Vec::new(),
2078            prettier_plugins: Vec::new(),
2079            language_server_binary: LanguageServerBinary {
2080                path: "/the/fake/lsp/path".into(),
2081                arguments: vec![],
2082                env: Default::default(),
2083            },
2084            label_for_completion: None,
2085        }
2086    }
2087}
2088
2089#[cfg(any(test, feature = "test-support"))]
2090#[async_trait(?Send)]
2091impl LspAdapter for FakeLspAdapter {
2092    fn name(&self) -> LanguageServerName {
2093        LanguageServerName(self.name.into())
2094    }
2095
2096    async fn check_if_user_installed(
2097        &self,
2098        _: &dyn LspAdapterDelegate,
2099        _: Arc<dyn LanguageToolchainStore>,
2100        _: &AsyncApp,
2101    ) -> Option<LanguageServerBinary> {
2102        Some(self.language_server_binary.clone())
2103    }
2104
2105    fn get_language_server_command<'a>(
2106        self: Arc<Self>,
2107        _: Arc<dyn LspAdapterDelegate>,
2108        _: Arc<dyn LanguageToolchainStore>,
2109        _: LanguageServerBinaryOptions,
2110        _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
2111        _: &'a mut AsyncApp,
2112    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
2113        async move { Ok(self.language_server_binary.clone()) }.boxed_local()
2114    }
2115
2116    async fn fetch_latest_server_version(
2117        &self,
2118        _: &dyn LspAdapterDelegate,
2119    ) -> Result<Box<dyn 'static + Send + Any>> {
2120        unreachable!();
2121    }
2122
2123    async fn fetch_server_binary(
2124        &self,
2125        _: Box<dyn 'static + Send + Any>,
2126        _: PathBuf,
2127        _: &dyn LspAdapterDelegate,
2128    ) -> Result<LanguageServerBinary> {
2129        unreachable!();
2130    }
2131
2132    async fn cached_server_binary(
2133        &self,
2134        _: PathBuf,
2135        _: &dyn LspAdapterDelegate,
2136    ) -> Option<LanguageServerBinary> {
2137        unreachable!();
2138    }
2139
2140    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2141        self.disk_based_diagnostics_sources.clone()
2142    }
2143
2144    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2145        self.disk_based_diagnostics_progress_token.clone()
2146    }
2147
2148    async fn initialization_options(
2149        self: Arc<Self>,
2150        _: &dyn Fs,
2151        _: &Arc<dyn LspAdapterDelegate>,
2152    ) -> Result<Option<Value>> {
2153        Ok(self.initialization_options.clone())
2154    }
2155
2156    async fn label_for_completion(
2157        &self,
2158        item: &lsp::CompletionItem,
2159        language: &Arc<Language>,
2160    ) -> Option<CodeLabel> {
2161        let label_for_completion = self.label_for_completion.as_ref()?;
2162        label_for_completion(item, language)
2163    }
2164}
2165
2166fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
2167    for (ix, name) in query.capture_names().iter().enumerate() {
2168        for (capture_name, index) in captures.iter_mut() {
2169            if capture_name == name {
2170                **index = Some(ix as u32);
2171                break;
2172            }
2173        }
2174    }
2175}
2176
2177pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2178    lsp::Position::new(point.row, point.column)
2179}
2180
2181pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2182    Unclipped(PointUtf16::new(point.line, point.character))
2183}
2184
2185pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2186    if range.start > range.end {
2187        Err(anyhow!(
2188            "Inverted range provided to an LSP request: {:?}-{:?}",
2189            range.start,
2190            range.end
2191        ))
2192    } else {
2193        Ok(lsp::Range {
2194            start: point_to_lsp(range.start),
2195            end: point_to_lsp(range.end),
2196        })
2197    }
2198}
2199
2200pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2201    let mut start = point_from_lsp(range.start);
2202    let mut end = point_from_lsp(range.end);
2203    if start > end {
2204        log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2205        mem::swap(&mut start, &mut end);
2206    }
2207    start..end
2208}
2209
2210#[cfg(test)]
2211mod tests {
2212    use super::*;
2213    use gpui::TestAppContext;
2214
2215    #[gpui::test(iterations = 10)]
2216    async fn test_language_loading(cx: &mut TestAppContext) {
2217        let languages = LanguageRegistry::test(cx.executor());
2218        let languages = Arc::new(languages);
2219        languages.register_native_grammars([
2220            ("json", tree_sitter_json::LANGUAGE),
2221            ("rust", tree_sitter_rust::LANGUAGE),
2222        ]);
2223        languages.register_test_language(LanguageConfig {
2224            name: "JSON".into(),
2225            grammar: Some("json".into()),
2226            matcher: LanguageMatcher {
2227                path_suffixes: vec!["json".into()],
2228                ..Default::default()
2229            },
2230            ..Default::default()
2231        });
2232        languages.register_test_language(LanguageConfig {
2233            name: "Rust".into(),
2234            grammar: Some("rust".into()),
2235            matcher: LanguageMatcher {
2236                path_suffixes: vec!["rs".into()],
2237                ..Default::default()
2238            },
2239            ..Default::default()
2240        });
2241        assert_eq!(
2242            languages.language_names(),
2243            &[
2244                "JSON".to_string(),
2245                "Plain Text".to_string(),
2246                "Rust".to_string(),
2247            ]
2248        );
2249
2250        let rust1 = languages.language_for_name("Rust");
2251        let rust2 = languages.language_for_name("Rust");
2252
2253        // Ensure language is still listed even if it's being loaded.
2254        assert_eq!(
2255            languages.language_names(),
2256            &[
2257                "JSON".to_string(),
2258                "Plain Text".to_string(),
2259                "Rust".to_string(),
2260            ]
2261        );
2262
2263        let (rust1, rust2) = futures::join!(rust1, rust2);
2264        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2265
2266        // Ensure language is still listed even after loading it.
2267        assert_eq!(
2268            languages.language_names(),
2269            &[
2270                "JSON".to_string(),
2271                "Plain Text".to_string(),
2272                "Rust".to_string(),
2273            ]
2274        );
2275
2276        // Loading an unknown language returns an error.
2277        assert!(languages.language_for_name("Unknown").await.is_err());
2278    }
2279
2280    #[gpui::test]
2281    async fn test_completion_label_omits_duplicate_data() {
2282        let regular_completion_item_1 = lsp::CompletionItem {
2283            label: "regular1".to_string(),
2284            detail: Some("detail1".to_string()),
2285            label_details: Some(lsp::CompletionItemLabelDetails {
2286                detail: None,
2287                description: Some("description 1".to_string()),
2288            }),
2289            ..lsp::CompletionItem::default()
2290        };
2291
2292        let regular_completion_item_2 = lsp::CompletionItem {
2293            label: "regular2".to_string(),
2294            label_details: Some(lsp::CompletionItemLabelDetails {
2295                detail: None,
2296                description: Some("description 2".to_string()),
2297            }),
2298            ..lsp::CompletionItem::default()
2299        };
2300
2301        let completion_item_with_duplicate_detail_and_proper_description = lsp::CompletionItem {
2302            detail: Some(regular_completion_item_1.label.clone()),
2303            ..regular_completion_item_1.clone()
2304        };
2305
2306        let completion_item_with_duplicate_detail = lsp::CompletionItem {
2307            detail: Some(regular_completion_item_1.label.clone()),
2308            label_details: None,
2309            ..regular_completion_item_1.clone()
2310        };
2311
2312        let completion_item_with_duplicate_description = lsp::CompletionItem {
2313            label_details: Some(lsp::CompletionItemLabelDetails {
2314                detail: None,
2315                description: Some(regular_completion_item_2.label.clone()),
2316            }),
2317            ..regular_completion_item_2.clone()
2318        };
2319
2320        assert_eq!(
2321            CodeLabel::fallback_for_completion(&regular_completion_item_1, None).text,
2322            format!(
2323                "{} {}",
2324                regular_completion_item_1.label,
2325                regular_completion_item_1.detail.unwrap()
2326            ),
2327            "LSP completion items with both detail and label_details.description should prefer detail"
2328        );
2329        assert_eq!(
2330            CodeLabel::fallback_for_completion(&regular_completion_item_2, None).text,
2331            format!(
2332                "{} {}",
2333                regular_completion_item_2.label,
2334                regular_completion_item_2
2335                    .label_details
2336                    .as_ref()
2337                    .unwrap()
2338                    .description
2339                    .as_ref()
2340                    .unwrap()
2341            ),
2342            "LSP completion items without detail but with label_details.description should use that"
2343        );
2344        assert_eq!(
2345            CodeLabel::fallback_for_completion(
2346                &completion_item_with_duplicate_detail_and_proper_description,
2347                None
2348            )
2349            .text,
2350            format!(
2351                "{} {}",
2352                regular_completion_item_1.label,
2353                regular_completion_item_1
2354                    .label_details
2355                    .as_ref()
2356                    .unwrap()
2357                    .description
2358                    .as_ref()
2359                    .unwrap()
2360            ),
2361            "LSP completion items with both detail and label_details.description should prefer description only if the detail duplicates the completion label"
2362        );
2363        assert_eq!(
2364            CodeLabel::fallback_for_completion(&completion_item_with_duplicate_detail, None).text,
2365            regular_completion_item_1.label,
2366            "LSP completion items with duplicate label and detail, should omit the detail"
2367        );
2368        assert_eq!(
2369            CodeLabel::fallback_for_completion(&completion_item_with_duplicate_description, None)
2370                .text,
2371            regular_completion_item_2.label,
2372            "LSP completion items with duplicate label and detail, should omit the detail"
2373        );
2374    }
2375}