language.rs

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