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