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