language.rs

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