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