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 outline;
  15pub mod proto;
  16mod syntax_map;
  17mod task_context;
  18mod toolchain;
  19
  20#[cfg(test)]
  21pub mod buffer_tests;
  22pub mod markdown;
  23
  24use crate::language_settings::SoftWrap;
  25use anyhow::{anyhow, Context, Result};
  26use async_trait::async_trait;
  27use collections::{HashMap, HashSet};
  28use futures::Future;
  29use gpui::{AppContext, AsyncAppContext, Model, SharedString, Task};
  30pub use highlight_map::HighlightMap;
  31use http_client::HttpClient;
  32pub use language_registry::{LanguageName, LoadedLanguage};
  33use lsp::{
  34    CodeActionKind, InitializeParams, LanguageServerBinary, LanguageServerBinaryOptions,
  35    LanguageServerName,
  36};
  37use parking_lot::Mutex;
  38use regex::Regex;
  39use schemars::{
  40    gen::SchemaGenerator,
  41    schema::{InstanceType, Schema, SchemaObject},
  42    JsonSchema,
  43};
  44use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
  45use serde_json::Value;
  46use settings::WorktreeId;
  47use smol::future::FutureExt as _;
  48use std::num::NonZeroU32;
  49use std::{
  50    any::Any,
  51    ffi::OsStr,
  52    fmt::Debug,
  53    hash::Hash,
  54    mem,
  55    ops::{DerefMut, Range},
  56    path::{Path, PathBuf},
  57    pin::Pin,
  58    str,
  59    sync::{
  60        atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
  61        Arc, LazyLock,
  62    },
  63};
  64use syntax_map::{QueryCursorHandle, SyntaxSnapshot};
  65use task::RunnableTag;
  66pub use task_context::{ContextProvider, RunnableRange};
  67use theme::SyntaxTheme;
  68pub use toolchain::{LanguageToolchainStore, Toolchain, ToolchainList, ToolchainLister};
  69use tree_sitter::{self, wasmtime, Query, QueryCursor, WasmStore};
  70use util::serde::default_true;
  71
  72pub use buffer::Operation;
  73pub use buffer::*;
  74pub use diagnostic_set::DiagnosticEntry;
  75pub use language_registry::{
  76    AvailableLanguage, LanguageNotFound, LanguageQueries, LanguageRegistry,
  77    LanguageServerBinaryStatus, QUERY_FILENAME_PREFIXES,
  78};
  79pub use lsp::LanguageServerId;
  80pub use outline::*;
  81pub use syntax_map::{OwnedSyntaxLayer, SyntaxLayer};
  82pub use text::{AnchorRangeExt, LineEnding};
  83pub use tree_sitter::{Node, Parser, Tree, TreeCursor};
  84
  85/// Initializes the `language` crate.
  86///
  87/// This should be called before making use of items from the create.
  88pub fn init(cx: &mut AppContext) {
  89    language_settings::init(cx);
  90}
  91
  92static QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Mutex::new(vec![]);
  93static PARSERS: Mutex<Vec<Parser>> = Mutex::new(vec![]);
  94
  95pub fn with_parser<F, R>(func: F) -> R
  96where
  97    F: FnOnce(&mut Parser) -> R,
  98{
  99    let mut parser = PARSERS.lock().pop().unwrap_or_else(|| {
 100        let mut parser = Parser::new();
 101        parser
 102            .set_wasm_store(WasmStore::new(&WASM_ENGINE).unwrap())
 103            .unwrap();
 104        parser
 105    });
 106    parser.set_included_ranges(&[]).unwrap();
 107    let result = func(&mut parser);
 108    PARSERS.lock().push(parser);
 109    result
 110}
 111
 112pub fn with_query_cursor<F, R>(func: F) -> R
 113where
 114    F: FnOnce(&mut QueryCursor) -> R,
 115{
 116    let mut cursor = QueryCursorHandle::new();
 117    func(cursor.deref_mut())
 118}
 119
 120static NEXT_LANGUAGE_ID: LazyLock<AtomicUsize> = LazyLock::new(Default::default);
 121static NEXT_GRAMMAR_ID: LazyLock<AtomicUsize> = LazyLock::new(Default::default);
 122static WASM_ENGINE: LazyLock<wasmtime::Engine> = LazyLock::new(|| {
 123    wasmtime::Engine::new(&wasmtime::Config::new()).expect("Failed to create Wasmtime engine")
 124});
 125
 126/// A shared grammar for plain text, exposed for reuse by downstream crates.
 127pub static PLAIN_TEXT: LazyLock<Arc<Language>> = LazyLock::new(|| {
 128    Arc::new(Language::new(
 129        LanguageConfig {
 130            name: "Plain Text".into(),
 131            soft_wrap: Some(SoftWrap::EditorWidth),
 132            matcher: LanguageMatcher {
 133                path_suffixes: vec!["txt".to_owned()],
 134                first_line_pattern: None,
 135            },
 136            ..Default::default()
 137        },
 138        None,
 139    ))
 140});
 141
 142/// Types that represent a position in a buffer, and can be converted into
 143/// an LSP position, to send to a language server.
 144pub trait ToLspPosition {
 145    /// Converts the value into an LSP position.
 146    fn to_lsp_position(self) -> lsp::Position;
 147}
 148
 149#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 150pub struct Location {
 151    pub buffer: Model<Buffer>,
 152    pub range: Range<Anchor>,
 153}
 154
 155/// Represents a Language Server, with certain cached sync properties.
 156/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
 157/// once at startup, and caches the results.
 158pub struct CachedLspAdapter {
 159    pub name: LanguageServerName,
 160    pub disk_based_diagnostic_sources: Vec<String>,
 161    pub disk_based_diagnostics_progress_token: Option<String>,
 162    language_ids: HashMap<String, String>,
 163    pub adapter: Arc<dyn LspAdapter>,
 164    pub reinstall_attempt_count: AtomicU64,
 165    cached_binary: futures::lock::Mutex<Option<LanguageServerBinary>>,
 166}
 167
 168impl Debug for CachedLspAdapter {
 169    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 170        f.debug_struct("CachedLspAdapter")
 171            .field("name", &self.name)
 172            .field(
 173                "disk_based_diagnostic_sources",
 174                &self.disk_based_diagnostic_sources,
 175            )
 176            .field(
 177                "disk_based_diagnostics_progress_token",
 178                &self.disk_based_diagnostics_progress_token,
 179            )
 180            .field("language_ids", &self.language_ids)
 181            .field("reinstall_attempt_count", &self.reinstall_attempt_count)
 182            .finish_non_exhaustive()
 183    }
 184}
 185
 186impl CachedLspAdapter {
 187    pub fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
 188        let name = adapter.name();
 189        let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
 190        let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
 191        let language_ids = adapter.language_ids();
 192
 193        Arc::new(CachedLspAdapter {
 194            name,
 195            disk_based_diagnostic_sources,
 196            disk_based_diagnostics_progress_token,
 197            language_ids,
 198            adapter,
 199            cached_binary: Default::default(),
 200            reinstall_attempt_count: AtomicU64::new(0),
 201        })
 202    }
 203
 204    pub fn name(&self) -> LanguageServerName {
 205        self.adapter.name().clone()
 206    }
 207
 208    pub async fn get_language_server_command(
 209        self: Arc<Self>,
 210        delegate: Arc<dyn LspAdapterDelegate>,
 211        toolchains: Arc<dyn LanguageToolchainStore>,
 212        binary_options: LanguageServerBinaryOptions,
 213        cx: &mut AsyncAppContext,
 214    ) -> Result<LanguageServerBinary> {
 215        let cached_binary = self.cached_binary.lock().await;
 216        self.adapter
 217            .clone()
 218            .get_language_server_command(delegate, toolchains, binary_options, cached_binary, cx)
 219            .await
 220    }
 221
 222    pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 223        self.adapter.code_action_kinds()
 224    }
 225
 226    pub fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
 227        self.adapter.process_diagnostics(params)
 228    }
 229
 230    pub async fn process_completions(&self, completion_items: &mut [lsp::CompletionItem]) {
 231        self.adapter.process_completions(completion_items).await
 232    }
 233
 234    pub async fn labels_for_completions(
 235        &self,
 236        completion_items: &[lsp::CompletionItem],
 237        language: &Arc<Language>,
 238    ) -> Result<Vec<Option<CodeLabel>>> {
 239        self.adapter
 240            .clone()
 241            .labels_for_completions(completion_items, language)
 242            .await
 243    }
 244
 245    pub async fn labels_for_symbols(
 246        &self,
 247        symbols: &[(String, lsp::SymbolKind)],
 248        language: &Arc<Language>,
 249    ) -> Result<Vec<Option<CodeLabel>>> {
 250        self.adapter
 251            .clone()
 252            .labels_for_symbols(symbols, language)
 253            .await
 254    }
 255
 256    pub fn language_id(&self, language_name: &LanguageName) -> String {
 257        self.language_ids
 258            .get(language_name.0.as_ref())
 259            .cloned()
 260            .unwrap_or_else(|| language_name.lsp_id())
 261    }
 262}
 263
 264/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
 265// e.g. to display a notification or fetch data from the web.
 266#[async_trait]
 267pub trait LspAdapterDelegate: Send + Sync {
 268    fn show_notification(&self, message: &str, cx: &mut AppContext);
 269    fn http_client(&self) -> Arc<dyn HttpClient>;
 270    fn worktree_id(&self) -> WorktreeId;
 271    fn worktree_root_path(&self) -> &Path;
 272    fn update_status(&self, language: LanguageServerName, status: LanguageServerBinaryStatus);
 273    async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>>;
 274
 275    async fn npm_package_installed_version(
 276        &self,
 277        package_name: &str,
 278    ) -> Result<Option<(PathBuf, String)>>;
 279    async fn which(&self, command: &OsStr) -> Option<PathBuf>;
 280    async fn shell_env(&self) -> HashMap<String, String>;
 281    async fn read_text_file(&self, path: PathBuf) -> Result<String>;
 282    async fn try_exec(&self, binary: LanguageServerBinary) -> Result<()>;
 283}
 284
 285#[async_trait(?Send)]
 286pub trait LspAdapter: 'static + Send + Sync {
 287    fn name(&self) -> LanguageServerName;
 288
 289    fn get_language_server_command<'a>(
 290        self: Arc<Self>,
 291        delegate: Arc<dyn LspAdapterDelegate>,
 292        toolchains: Arc<dyn LanguageToolchainStore>,
 293        binary_options: LanguageServerBinaryOptions,
 294        mut cached_binary: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
 295        cx: &'a mut AsyncAppContext,
 296    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
 297        async move {
 298            // First we check whether the adapter can give us a user-installed binary.
 299            // If so, we do *not* want to cache that, because each worktree might give us a different
 300            // binary:
 301            //
 302            //      worktree 1: user-installed at `.bin/gopls`
 303            //      worktree 2: user-installed at `~/bin/gopls`
 304            //      worktree 3: no gopls found in PATH -> fallback to Zed installation
 305            //
 306            // We only want to cache when we fall back to the global one,
 307            // because we don't want to download and overwrite our global one
 308            // for each worktree we might have open.
 309            if binary_options.allow_path_lookup {
 310                if let Some(binary) = self.check_if_user_installed(delegate.as_ref(), toolchains, cx).await {
 311                    log::info!(
 312                        "found user-installed language server for {}. path: {:?}, arguments: {:?}",
 313                        self.name().0,
 314                        binary.path,
 315                        binary.arguments
 316                    );
 317                    return Ok(binary);
 318                }
 319            }
 320
 321            if !binary_options.allow_binary_download {
 322                return Err(anyhow!("downloading language servers disabled"));
 323            }
 324
 325            if let Some(cached_binary) = cached_binary.as_ref() {
 326                return Ok(cached_binary.clone());
 327            }
 328
 329            let Some(container_dir) = delegate.language_server_download_dir(&self.name()).await else {
 330                anyhow::bail!("no language server download dir defined")
 331            };
 332
 333            let mut binary = try_fetch_server_binary(self.as_ref(), &delegate, container_dir.to_path_buf(), cx).await;
 334
 335            if let Err(error) = binary.as_ref() {
 336                if let Some(prev_downloaded_binary) = self
 337                    .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
 338                    .await
 339                {
 340                    log::info!(
 341                        "failed to fetch newest version of language server {:?}. error: {:?}, falling back to using {:?}",
 342                        self.name(),
 343                        error,
 344                        prev_downloaded_binary.path
 345                    );
 346                    binary = Ok(prev_downloaded_binary);
 347                } else {
 348                    delegate.update_status(
 349                        self.name(),
 350                        LanguageServerBinaryStatus::Failed {
 351                            error: format!("{error:?}"),
 352                        },
 353                    );
 354                }
 355            }
 356
 357            if let Ok(binary) = &binary {
 358                *cached_binary = Some(binary.clone());
 359            }
 360
 361            binary
 362        }
 363        .boxed_local()
 364    }
 365
 366    async fn check_if_user_installed(
 367        &self,
 368        _: &dyn LspAdapterDelegate,
 369        _: Arc<dyn LanguageToolchainStore>,
 370        _: &AsyncAppContext,
 371    ) -> Option<LanguageServerBinary> {
 372        None
 373    }
 374
 375    async fn fetch_latest_server_version(
 376        &self,
 377        delegate: &dyn LspAdapterDelegate,
 378    ) -> Result<Box<dyn 'static + Send + Any>>;
 379
 380    fn will_fetch_server(
 381        &self,
 382        _: &Arc<dyn LspAdapterDelegate>,
 383        _: &mut AsyncAppContext,
 384    ) -> Option<Task<Result<()>>> {
 385        None
 386    }
 387
 388    async fn fetch_server_binary(
 389        &self,
 390        latest_version: Box<dyn 'static + Send + Any>,
 391        container_dir: PathBuf,
 392        delegate: &dyn LspAdapterDelegate,
 393    ) -> Result<LanguageServerBinary>;
 394
 395    async fn cached_server_binary(
 396        &self,
 397        container_dir: PathBuf,
 398        delegate: &dyn LspAdapterDelegate,
 399    ) -> Option<LanguageServerBinary>;
 400
 401    fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
 402
 403    /// Post-processes completions provided by the language server.
 404    async fn process_completions(&self, _: &mut [lsp::CompletionItem]) {}
 405
 406    async fn labels_for_completions(
 407        self: Arc<Self>,
 408        completions: &[lsp::CompletionItem],
 409        language: &Arc<Language>,
 410    ) -> Result<Vec<Option<CodeLabel>>> {
 411        let mut labels = Vec::new();
 412        for (ix, completion) in completions.iter().enumerate() {
 413            let label = self.label_for_completion(completion, language).await;
 414            if let Some(label) = label {
 415                labels.resize(ix + 1, None);
 416                *labels.last_mut().unwrap() = Some(label);
 417            }
 418        }
 419        Ok(labels)
 420    }
 421
 422    async fn label_for_completion(
 423        &self,
 424        _: &lsp::CompletionItem,
 425        _: &Arc<Language>,
 426    ) -> Option<CodeLabel> {
 427        None
 428    }
 429
 430    async fn labels_for_symbols(
 431        self: Arc<Self>,
 432        symbols: &[(String, lsp::SymbolKind)],
 433        language: &Arc<Language>,
 434    ) -> Result<Vec<Option<CodeLabel>>> {
 435        let mut labels = Vec::new();
 436        for (ix, (name, kind)) in symbols.iter().enumerate() {
 437            let label = self.label_for_symbol(name, *kind, language).await;
 438            if let Some(label) = label {
 439                labels.resize(ix + 1, None);
 440                *labels.last_mut().unwrap() = Some(label);
 441            }
 442        }
 443        Ok(labels)
 444    }
 445
 446    async fn label_for_symbol(
 447        &self,
 448        _: &str,
 449        _: lsp::SymbolKind,
 450        _: &Arc<Language>,
 451    ) -> Option<CodeLabel> {
 452        None
 453    }
 454
 455    /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp::InitializeParams`]
 456    async fn initialization_options(
 457        self: Arc<Self>,
 458        _: &Arc<dyn LspAdapterDelegate>,
 459    ) -> Result<Option<Value>> {
 460        Ok(None)
 461    }
 462
 463    async fn workspace_configuration(
 464        self: Arc<Self>,
 465        _: &Arc<dyn LspAdapterDelegate>,
 466        _: Arc<dyn LanguageToolchainStore>,
 467        _cx: &mut AsyncAppContext,
 468    ) -> Result<Value> {
 469        Ok(serde_json::json!({}))
 470    }
 471
 472    /// Returns a list of code actions supported by a given LspAdapter
 473    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 474        Some(vec![
 475            CodeActionKind::EMPTY,
 476            CodeActionKind::QUICKFIX,
 477            CodeActionKind::REFACTOR,
 478            CodeActionKind::REFACTOR_EXTRACT,
 479            CodeActionKind::SOURCE,
 480        ])
 481    }
 482
 483    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
 484        Default::default()
 485    }
 486
 487    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
 488        None
 489    }
 490
 491    fn language_ids(&self) -> HashMap<String, String> {
 492        Default::default()
 493    }
 494
 495    /// Support custom initialize params.
 496    fn prepare_initialize_params(&self, original: InitializeParams) -> Result<InitializeParams> {
 497        Ok(original)
 498    }
 499}
 500
 501async fn try_fetch_server_binary<L: LspAdapter + 'static + Send + Sync + ?Sized>(
 502    adapter: &L,
 503    delegate: &Arc<dyn LspAdapterDelegate>,
 504    container_dir: PathBuf,
 505    cx: &mut AsyncAppContext,
 506) -> Result<LanguageServerBinary> {
 507    if let Some(task) = adapter.will_fetch_server(delegate, cx) {
 508        task.await?;
 509    }
 510
 511    let name = adapter.name();
 512    log::info!("fetching latest version of language server {:?}", name.0);
 513    delegate.update_status(name.clone(), LanguageServerBinaryStatus::CheckingForUpdate);
 514
 515    let latest_version = adapter
 516        .fetch_latest_server_version(delegate.as_ref())
 517        .await?;
 518
 519    log::info!("downloading language server {:?}", name.0);
 520    delegate.update_status(adapter.name(), LanguageServerBinaryStatus::Downloading);
 521    let binary = adapter
 522        .fetch_server_binary(latest_version, container_dir, delegate.as_ref())
 523        .await;
 524
 525    delegate.update_status(name.clone(), LanguageServerBinaryStatus::None);
 526    binary
 527}
 528
 529#[derive(Clone, Debug, Default, PartialEq, Eq)]
 530pub struct CodeLabel {
 531    /// The text to display.
 532    pub text: String,
 533    /// Syntax highlighting runs.
 534    pub runs: Vec<(Range<usize>, HighlightId)>,
 535    /// The portion of the text that should be used in fuzzy filtering.
 536    pub filter_range: Range<usize>,
 537}
 538
 539#[derive(Clone, Deserialize, JsonSchema)]
 540pub struct LanguageConfig {
 541    /// Human-readable name of the language.
 542    pub name: LanguageName,
 543    /// The name of this language for a Markdown code fence block
 544    pub code_fence_block_name: Option<Arc<str>>,
 545    // The name of the grammar in a WASM bundle (experimental).
 546    pub grammar: Option<Arc<str>>,
 547    /// The criteria for matching this language to a given file.
 548    #[serde(flatten)]
 549    pub matcher: LanguageMatcher,
 550    /// List of bracket types in a language.
 551    #[serde(default)]
 552    #[schemars(schema_with = "bracket_pair_config_json_schema")]
 553    pub brackets: BracketPairConfig,
 554    /// If set to true, auto indentation uses last non empty line to determine
 555    /// the indentation level for a new line.
 556    #[serde(default = "auto_indent_using_last_non_empty_line_default")]
 557    pub auto_indent_using_last_non_empty_line: bool,
 558    // Whether indentation of pasted content should be adjusted based on the context.
 559    #[serde(default)]
 560    pub auto_indent_on_paste: Option<bool>,
 561    /// A regex that is used to determine whether the indentation level should be
 562    /// increased in the following line.
 563    #[serde(default, deserialize_with = "deserialize_regex")]
 564    #[schemars(schema_with = "regex_json_schema")]
 565    pub increase_indent_pattern: Option<Regex>,
 566    /// A regex that is used to determine whether the indentation level should be
 567    /// decreased in the following line.
 568    #[serde(default, deserialize_with = "deserialize_regex")]
 569    #[schemars(schema_with = "regex_json_schema")]
 570    pub decrease_indent_pattern: Option<Regex>,
 571    /// A list of characters that trigger the automatic insertion of a closing
 572    /// bracket when they immediately precede the point where an opening
 573    /// bracket is inserted.
 574    #[serde(default)]
 575    pub autoclose_before: String,
 576    /// A placeholder used internally by Semantic Index.
 577    #[serde(default)]
 578    pub collapsed_placeholder: String,
 579    /// A line comment string that is inserted in e.g. `toggle comments` action.
 580    /// A language can have multiple flavours of line comments. All of the provided line comments are
 581    /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
 582    #[serde(default)]
 583    pub line_comments: Vec<Arc<str>>,
 584    /// Starting and closing characters of a block comment.
 585    #[serde(default)]
 586    pub block_comment: Option<(Arc<str>, Arc<str>)>,
 587    /// A list of language servers that are allowed to run on subranges of a given language.
 588    #[serde(default)]
 589    pub scope_opt_in_language_servers: Vec<LanguageServerName>,
 590    #[serde(default)]
 591    pub overrides: HashMap<String, LanguageConfigOverride>,
 592    /// A list of characters that Zed should treat as word characters for the
 593    /// purpose of features that operate on word boundaries, like 'move to next word end'
 594    /// or a whole-word search in buffer search.
 595    #[serde(default)]
 596    pub word_characters: HashSet<char>,
 597    /// Whether to indent lines using tab characters, as opposed to multiple
 598    /// spaces.
 599    #[serde(default)]
 600    pub hard_tabs: Option<bool>,
 601    /// How many columns a tab should occupy.
 602    #[serde(default)]
 603    pub tab_size: Option<NonZeroU32>,
 604    /// How to soft-wrap long lines of text.
 605    #[serde(default)]
 606    pub soft_wrap: Option<SoftWrap>,
 607    /// The name of a Prettier parser that will be used for this language when no file path is available.
 608    /// If there's a parser name in the language settings, that will be used instead.
 609    #[serde(default)]
 610    pub prettier_parser_name: Option<String>,
 611    /// If true, this language is only for syntax highlighting via an injection into other
 612    /// languages, but should not appear to the user as a distinct language.
 613    #[serde(default)]
 614    pub hidden: bool,
 615}
 616
 617#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
 618pub struct LanguageMatcher {
 619    /// 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`.
 620    #[serde(default)]
 621    pub path_suffixes: Vec<String>,
 622    /// A regex pattern that determines whether the language should be assigned to a file or not.
 623    #[serde(
 624        default,
 625        serialize_with = "serialize_regex",
 626        deserialize_with = "deserialize_regex"
 627    )]
 628    #[schemars(schema_with = "regex_json_schema")]
 629    pub first_line_pattern: Option<Regex>,
 630}
 631
 632/// Represents a language for the given range. Some languages (e.g. HTML)
 633/// interleave several languages together, thus a single buffer might actually contain
 634/// several nested scopes.
 635#[derive(Clone, Debug)]
 636pub struct LanguageScope {
 637    language: Arc<Language>,
 638    override_id: Option<u32>,
 639}
 640
 641#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
 642pub struct LanguageConfigOverride {
 643    #[serde(default)]
 644    pub line_comments: Override<Vec<Arc<str>>>,
 645    #[serde(default)]
 646    pub block_comment: Override<(Arc<str>, Arc<str>)>,
 647    #[serde(skip_deserializing)]
 648    #[schemars(skip)]
 649    pub disabled_bracket_ixs: Vec<u16>,
 650    #[serde(default)]
 651    pub word_characters: Override<HashSet<char>>,
 652    #[serde(default)]
 653    pub opt_into_language_servers: Vec<LanguageServerName>,
 654}
 655
 656#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
 657#[serde(untagged)]
 658pub enum Override<T> {
 659    Remove { remove: bool },
 660    Set(T),
 661}
 662
 663impl<T> Default for Override<T> {
 664    fn default() -> Self {
 665        Override::Remove { remove: false }
 666    }
 667}
 668
 669impl<T> Override<T> {
 670    fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
 671        match this {
 672            Some(Self::Set(value)) => Some(value),
 673            Some(Self::Remove { remove: true }) => None,
 674            Some(Self::Remove { remove: false }) | None => original,
 675        }
 676    }
 677}
 678
 679impl Default for LanguageConfig {
 680    fn default() -> Self {
 681        Self {
 682            name: LanguageName::new(""),
 683            code_fence_block_name: None,
 684            grammar: None,
 685            matcher: LanguageMatcher::default(),
 686            brackets: Default::default(),
 687            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
 688            auto_indent_on_paste: None,
 689            increase_indent_pattern: Default::default(),
 690            decrease_indent_pattern: Default::default(),
 691            autoclose_before: Default::default(),
 692            line_comments: Default::default(),
 693            block_comment: Default::default(),
 694            scope_opt_in_language_servers: Default::default(),
 695            overrides: Default::default(),
 696            word_characters: Default::default(),
 697            collapsed_placeholder: Default::default(),
 698            hard_tabs: None,
 699            tab_size: None,
 700            soft_wrap: None,
 701            prettier_parser_name: None,
 702            hidden: false,
 703        }
 704    }
 705}
 706
 707fn auto_indent_using_last_non_empty_line_default() -> bool {
 708    true
 709}
 710
 711fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
 712    let source = Option::<String>::deserialize(d)?;
 713    if let Some(source) = source {
 714        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
 715    } else {
 716        Ok(None)
 717    }
 718}
 719
 720fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
 721    Schema::Object(SchemaObject {
 722        instance_type: Some(InstanceType::String.into()),
 723        ..Default::default()
 724    })
 725}
 726
 727fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
 728where
 729    S: Serializer,
 730{
 731    match regex {
 732        Some(regex) => serializer.serialize_str(regex.as_str()),
 733        None => serializer.serialize_none(),
 734    }
 735}
 736
 737#[doc(hidden)]
 738#[cfg(any(test, feature = "test-support"))]
 739pub struct FakeLspAdapter {
 740    pub name: &'static str,
 741    pub initialization_options: Option<Value>,
 742    pub prettier_plugins: Vec<&'static str>,
 743    pub disk_based_diagnostics_progress_token: Option<String>,
 744    pub disk_based_diagnostics_sources: Vec<String>,
 745    pub language_server_binary: LanguageServerBinary,
 746
 747    pub capabilities: lsp::ServerCapabilities,
 748    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
 749}
 750
 751/// Configuration of handling bracket pairs for a given language.
 752///
 753/// This struct includes settings for defining which pairs of characters are considered brackets and
 754/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
 755#[derive(Clone, Debug, Default, JsonSchema)]
 756pub struct BracketPairConfig {
 757    /// A list of character pairs that should be treated as brackets in the context of a given language.
 758    pub pairs: Vec<BracketPair>,
 759    /// A list of tree-sitter scopes for which a given bracket should not be active.
 760    /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
 761    #[schemars(skip)]
 762    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
 763}
 764
 765fn bracket_pair_config_json_schema(gen: &mut SchemaGenerator) -> Schema {
 766    Option::<Vec<BracketPairContent>>::json_schema(gen)
 767}
 768
 769#[derive(Deserialize, JsonSchema)]
 770pub struct BracketPairContent {
 771    #[serde(flatten)]
 772    pub bracket_pair: BracketPair,
 773    #[serde(default)]
 774    pub not_in: Vec<String>,
 775}
 776
 777impl<'de> Deserialize<'de> for BracketPairConfig {
 778    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 779    where
 780        D: Deserializer<'de>,
 781    {
 782        let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
 783        let mut brackets = Vec::with_capacity(result.len());
 784        let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
 785        for entry in result {
 786            brackets.push(entry.bracket_pair);
 787            disabled_scopes_by_bracket_ix.push(entry.not_in);
 788        }
 789
 790        Ok(BracketPairConfig {
 791            pairs: brackets,
 792            disabled_scopes_by_bracket_ix,
 793        })
 794    }
 795}
 796
 797/// Describes a single bracket pair and how an editor should react to e.g. inserting
 798/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
 799#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
 800pub struct BracketPair {
 801    /// Starting substring for a bracket.
 802    pub start: String,
 803    /// Ending substring for a bracket.
 804    pub end: String,
 805    /// True if `end` should be automatically inserted right after `start` characters.
 806    pub close: bool,
 807    /// True if selected text should be surrounded by `start` and `end` characters.
 808    #[serde(default = "default_true")]
 809    pub surround: bool,
 810    /// True if an extra newline should be inserted while the cursor is in the middle
 811    /// of that bracket pair.
 812    pub newline: bool,
 813}
 814
 815#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 816pub(crate) struct LanguageId(usize);
 817
 818impl LanguageId {
 819    pub(crate) fn new() -> Self {
 820        Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
 821    }
 822}
 823
 824pub struct Language {
 825    pub(crate) id: LanguageId,
 826    pub(crate) config: LanguageConfig,
 827    pub(crate) grammar: Option<Arc<Grammar>>,
 828    pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
 829    pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
 830}
 831
 832#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 833pub struct GrammarId(pub usize);
 834
 835impl GrammarId {
 836    pub(crate) fn new() -> Self {
 837        Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
 838    }
 839}
 840
 841pub struct Grammar {
 842    id: GrammarId,
 843    pub ts_language: tree_sitter::Language,
 844    pub(crate) error_query: Query,
 845    pub(crate) highlights_query: Option<Query>,
 846    pub(crate) brackets_config: Option<BracketConfig>,
 847    pub(crate) redactions_config: Option<RedactionConfig>,
 848    pub(crate) runnable_config: Option<RunnableConfig>,
 849    pub(crate) indents_config: Option<IndentConfig>,
 850    pub outline_config: Option<OutlineConfig>,
 851    pub embedding_config: Option<EmbeddingConfig>,
 852    pub(crate) injection_config: Option<InjectionConfig>,
 853    pub(crate) override_config: Option<OverrideConfig>,
 854    pub(crate) highlight_map: Mutex<HighlightMap>,
 855}
 856
 857struct IndentConfig {
 858    query: Query,
 859    indent_capture_ix: u32,
 860    start_capture_ix: Option<u32>,
 861    end_capture_ix: Option<u32>,
 862    outdent_capture_ix: Option<u32>,
 863}
 864
 865pub struct OutlineConfig {
 866    pub query: Query,
 867    pub item_capture_ix: u32,
 868    pub name_capture_ix: u32,
 869    pub context_capture_ix: Option<u32>,
 870    pub extra_context_capture_ix: Option<u32>,
 871    pub open_capture_ix: Option<u32>,
 872    pub close_capture_ix: Option<u32>,
 873    pub annotation_capture_ix: Option<u32>,
 874}
 875
 876#[derive(Debug)]
 877pub struct EmbeddingConfig {
 878    pub query: Query,
 879    pub item_capture_ix: u32,
 880    pub name_capture_ix: Option<u32>,
 881    pub context_capture_ix: Option<u32>,
 882    pub collapse_capture_ix: Option<u32>,
 883    pub keep_capture_ix: Option<u32>,
 884}
 885
 886struct InjectionConfig {
 887    query: Query,
 888    content_capture_ix: u32,
 889    language_capture_ix: Option<u32>,
 890    patterns: Vec<InjectionPatternConfig>,
 891}
 892
 893struct RedactionConfig {
 894    pub query: Query,
 895    pub redaction_capture_ix: u32,
 896}
 897
 898#[derive(Clone, Debug, PartialEq)]
 899enum RunnableCapture {
 900    Named(SharedString),
 901    Run,
 902}
 903
 904struct RunnableConfig {
 905    pub query: Query,
 906    /// A mapping from capture indice to capture kind
 907    pub extra_captures: Vec<RunnableCapture>,
 908}
 909
 910struct OverrideConfig {
 911    query: Query,
 912    values: HashMap<u32, OverrideEntry>,
 913}
 914
 915#[derive(Debug)]
 916struct OverrideEntry {
 917    name: String,
 918    range_is_inclusive: bool,
 919    value: LanguageConfigOverride,
 920}
 921
 922#[derive(Default, Clone)]
 923struct InjectionPatternConfig {
 924    language: Option<Box<str>>,
 925    combined: bool,
 926}
 927
 928struct BracketConfig {
 929    query: Query,
 930    open_capture_ix: u32,
 931    close_capture_ix: u32,
 932}
 933
 934impl Language {
 935    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
 936        Self::new_with_id(LanguageId::new(), config, ts_language)
 937    }
 938
 939    fn new_with_id(
 940        id: LanguageId,
 941        config: LanguageConfig,
 942        ts_language: Option<tree_sitter::Language>,
 943    ) -> Self {
 944        Self {
 945            id,
 946            config,
 947            grammar: ts_language.map(|ts_language| {
 948                Arc::new(Grammar {
 949                    id: GrammarId::new(),
 950                    highlights_query: None,
 951                    brackets_config: None,
 952                    outline_config: None,
 953                    embedding_config: None,
 954                    indents_config: None,
 955                    injection_config: None,
 956                    override_config: None,
 957                    redactions_config: None,
 958                    runnable_config: None,
 959                    error_query: Query::new(&ts_language, "(ERROR) @error").unwrap(),
 960                    ts_language,
 961                    highlight_map: Default::default(),
 962                })
 963            }),
 964            context_provider: None,
 965            toolchain: None,
 966        }
 967    }
 968
 969    pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
 970        self.context_provider = provider;
 971        self
 972    }
 973
 974    pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
 975        self.toolchain = provider;
 976        self
 977    }
 978
 979    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
 980        if let Some(query) = queries.highlights {
 981            self = self
 982                .with_highlights_query(query.as_ref())
 983                .context("Error loading highlights query")?;
 984        }
 985        if let Some(query) = queries.brackets {
 986            self = self
 987                .with_brackets_query(query.as_ref())
 988                .context("Error loading brackets query")?;
 989        }
 990        if let Some(query) = queries.indents {
 991            self = self
 992                .with_indents_query(query.as_ref())
 993                .context("Error loading indents query")?;
 994        }
 995        if let Some(query) = queries.outline {
 996            self = self
 997                .with_outline_query(query.as_ref())
 998                .context("Error loading outline query")?;
 999        }
1000        if let Some(query) = queries.embedding {
1001            self = self
1002                .with_embedding_query(query.as_ref())
1003                .context("Error loading embedding query")?;
1004        }
1005        if let Some(query) = queries.injections {
1006            self = self
1007                .with_injection_query(query.as_ref())
1008                .context("Error loading injection query")?;
1009        }
1010        if let Some(query) = queries.overrides {
1011            self = self
1012                .with_override_query(query.as_ref())
1013                .context("Error loading override query")?;
1014        }
1015        if let Some(query) = queries.redactions {
1016            self = self
1017                .with_redaction_query(query.as_ref())
1018                .context("Error loading redaction query")?;
1019        }
1020        if let Some(query) = queries.runnables {
1021            self = self
1022                .with_runnable_query(query.as_ref())
1023                .context("Error loading tests query")?;
1024        }
1025        Ok(self)
1026    }
1027
1028    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1029        let grammar = self
1030            .grammar_mut()
1031            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1032        grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1033        Ok(self)
1034    }
1035
1036    pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1037        let grammar = self
1038            .grammar_mut()
1039            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1040
1041        let query = Query::new(&grammar.ts_language, source)?;
1042        let mut extra_captures = Vec::with_capacity(query.capture_names().len());
1043
1044        for name in query.capture_names().iter() {
1045            let kind = if *name == "run" {
1046                RunnableCapture::Run
1047            } else {
1048                RunnableCapture::Named(name.to_string().into())
1049            };
1050            extra_captures.push(kind);
1051        }
1052
1053        grammar.runnable_config = Some(RunnableConfig {
1054            extra_captures,
1055            query,
1056        });
1057
1058        Ok(self)
1059    }
1060
1061    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1062        let grammar = self
1063            .grammar_mut()
1064            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1065        let query = Query::new(&grammar.ts_language, source)?;
1066        let mut item_capture_ix = None;
1067        let mut name_capture_ix = None;
1068        let mut context_capture_ix = None;
1069        let mut extra_context_capture_ix = None;
1070        let mut open_capture_ix = None;
1071        let mut close_capture_ix = None;
1072        let mut annotation_capture_ix = None;
1073        get_capture_indices(
1074            &query,
1075            &mut [
1076                ("item", &mut item_capture_ix),
1077                ("name", &mut name_capture_ix),
1078                ("context", &mut context_capture_ix),
1079                ("context.extra", &mut extra_context_capture_ix),
1080                ("open", &mut open_capture_ix),
1081                ("close", &mut close_capture_ix),
1082                ("annotation", &mut annotation_capture_ix),
1083            ],
1084        );
1085        if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1086            grammar.outline_config = Some(OutlineConfig {
1087                query,
1088                item_capture_ix,
1089                name_capture_ix,
1090                context_capture_ix,
1091                extra_context_capture_ix,
1092                open_capture_ix,
1093                close_capture_ix,
1094                annotation_capture_ix,
1095            });
1096        }
1097        Ok(self)
1098    }
1099
1100    pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1101        let grammar = self
1102            .grammar_mut()
1103            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1104        let query = Query::new(&grammar.ts_language, source)?;
1105        let mut item_capture_ix = None;
1106        let mut name_capture_ix = None;
1107        let mut context_capture_ix = None;
1108        let mut collapse_capture_ix = None;
1109        let mut keep_capture_ix = None;
1110        get_capture_indices(
1111            &query,
1112            &mut [
1113                ("item", &mut item_capture_ix),
1114                ("name", &mut name_capture_ix),
1115                ("context", &mut context_capture_ix),
1116                ("keep", &mut keep_capture_ix),
1117                ("collapse", &mut collapse_capture_ix),
1118            ],
1119        );
1120        if let Some(item_capture_ix) = item_capture_ix {
1121            grammar.embedding_config = Some(EmbeddingConfig {
1122                query,
1123                item_capture_ix,
1124                name_capture_ix,
1125                context_capture_ix,
1126                collapse_capture_ix,
1127                keep_capture_ix,
1128            });
1129        }
1130        Ok(self)
1131    }
1132
1133    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1134        let grammar = self
1135            .grammar_mut()
1136            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1137        let query = Query::new(&grammar.ts_language, source)?;
1138        let mut open_capture_ix = None;
1139        let mut close_capture_ix = None;
1140        get_capture_indices(
1141            &query,
1142            &mut [
1143                ("open", &mut open_capture_ix),
1144                ("close", &mut close_capture_ix),
1145            ],
1146        );
1147        if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1148            grammar.brackets_config = Some(BracketConfig {
1149                query,
1150                open_capture_ix,
1151                close_capture_ix,
1152            });
1153        }
1154        Ok(self)
1155    }
1156
1157    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1158        let grammar = self
1159            .grammar_mut()
1160            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1161        let query = Query::new(&grammar.ts_language, source)?;
1162        let mut indent_capture_ix = None;
1163        let mut start_capture_ix = None;
1164        let mut end_capture_ix = None;
1165        let mut outdent_capture_ix = None;
1166        get_capture_indices(
1167            &query,
1168            &mut [
1169                ("indent", &mut indent_capture_ix),
1170                ("start", &mut start_capture_ix),
1171                ("end", &mut end_capture_ix),
1172                ("outdent", &mut outdent_capture_ix),
1173            ],
1174        );
1175        if let Some(indent_capture_ix) = indent_capture_ix {
1176            grammar.indents_config = Some(IndentConfig {
1177                query,
1178                indent_capture_ix,
1179                start_capture_ix,
1180                end_capture_ix,
1181                outdent_capture_ix,
1182            });
1183        }
1184        Ok(self)
1185    }
1186
1187    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1188        let grammar = self
1189            .grammar_mut()
1190            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1191        let query = Query::new(&grammar.ts_language, source)?;
1192        let mut language_capture_ix = None;
1193        let mut content_capture_ix = None;
1194        get_capture_indices(
1195            &query,
1196            &mut [
1197                ("language", &mut language_capture_ix),
1198                ("content", &mut content_capture_ix),
1199            ],
1200        );
1201        let patterns = (0..query.pattern_count())
1202            .map(|ix| {
1203                let mut config = InjectionPatternConfig::default();
1204                for setting in query.property_settings(ix) {
1205                    match setting.key.as_ref() {
1206                        "language" => {
1207                            config.language.clone_from(&setting.value);
1208                        }
1209                        "combined" => {
1210                            config.combined = true;
1211                        }
1212                        _ => {}
1213                    }
1214                }
1215                config
1216            })
1217            .collect();
1218        if let Some(content_capture_ix) = content_capture_ix {
1219            grammar.injection_config = Some(InjectionConfig {
1220                query,
1221                language_capture_ix,
1222                content_capture_ix,
1223                patterns,
1224            });
1225        }
1226        Ok(self)
1227    }
1228
1229    pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1230        let query = {
1231            let grammar = self
1232                .grammar
1233                .as_ref()
1234                .ok_or_else(|| anyhow!("no grammar for language"))?;
1235            Query::new(&grammar.ts_language, source)?
1236        };
1237
1238        let mut override_configs_by_id = HashMap::default();
1239        for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1240            let mut range_is_inclusive = false;
1241            if name.starts_with('_') {
1242                continue;
1243            }
1244            if let Some(prefix) = name.strip_suffix(".inclusive") {
1245                name = prefix;
1246                range_is_inclusive = true;
1247            }
1248
1249            let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1250            for server_name in &value.opt_into_language_servers {
1251                if !self
1252                    .config
1253                    .scope_opt_in_language_servers
1254                    .contains(server_name)
1255                {
1256                    util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1257                }
1258            }
1259
1260            override_configs_by_id.insert(
1261                ix as u32,
1262                OverrideEntry {
1263                    name: name.to_string(),
1264                    range_is_inclusive,
1265                    value,
1266                },
1267            );
1268        }
1269
1270        let referenced_override_names = self.config.overrides.keys().chain(
1271            self.config
1272                .brackets
1273                .disabled_scopes_by_bracket_ix
1274                .iter()
1275                .flatten(),
1276        );
1277
1278        for referenced_name in referenced_override_names {
1279            if !override_configs_by_id
1280                .values()
1281                .any(|entry| entry.name == *referenced_name)
1282            {
1283                Err(anyhow!(
1284                    "language {:?} has overrides in config not in query: {referenced_name:?}",
1285                    self.config.name
1286                ))?;
1287            }
1288        }
1289
1290        for entry in override_configs_by_id.values_mut() {
1291            entry.value.disabled_bracket_ixs = self
1292                .config
1293                .brackets
1294                .disabled_scopes_by_bracket_ix
1295                .iter()
1296                .enumerate()
1297                .filter_map(|(ix, disabled_scope_names)| {
1298                    if disabled_scope_names.contains(&entry.name) {
1299                        Some(ix as u16)
1300                    } else {
1301                        None
1302                    }
1303                })
1304                .collect();
1305        }
1306
1307        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1308
1309        let grammar = self
1310            .grammar_mut()
1311            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1312        grammar.override_config = Some(OverrideConfig {
1313            query,
1314            values: override_configs_by_id,
1315        });
1316        Ok(self)
1317    }
1318
1319    pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1320        let grammar = self
1321            .grammar_mut()
1322            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1323
1324        let query = Query::new(&grammar.ts_language, source)?;
1325        let mut redaction_capture_ix = None;
1326        get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1327
1328        if let Some(redaction_capture_ix) = redaction_capture_ix {
1329            grammar.redactions_config = Some(RedactionConfig {
1330                query,
1331                redaction_capture_ix,
1332            });
1333        }
1334
1335        Ok(self)
1336    }
1337
1338    fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1339        Arc::get_mut(self.grammar.as_mut()?)
1340    }
1341
1342    pub fn name(&self) -> LanguageName {
1343        self.config.name.clone()
1344    }
1345
1346    pub fn code_fence_block_name(&self) -> Arc<str> {
1347        self.config
1348            .code_fence_block_name
1349            .clone()
1350            .unwrap_or_else(|| self.config.name.0.to_lowercase().into())
1351    }
1352
1353    pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1354        self.context_provider.clone()
1355    }
1356
1357    pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1358        self.toolchain.clone()
1359    }
1360
1361    pub fn highlight_text<'a>(
1362        self: &'a Arc<Self>,
1363        text: &'a Rope,
1364        range: Range<usize>,
1365    ) -> Vec<(Range<usize>, HighlightId)> {
1366        let mut result = Vec::new();
1367        if let Some(grammar) = &self.grammar {
1368            let tree = grammar.parse_text(text, None);
1369            let captures =
1370                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1371                    grammar.highlights_query.as_ref()
1372                });
1373            let highlight_maps = vec![grammar.highlight_map()];
1374            let mut offset = 0;
1375            for chunk in
1376                BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1377            {
1378                let end_offset = offset + chunk.text.len();
1379                if let Some(highlight_id) = chunk.syntax_highlight_id {
1380                    if !highlight_id.is_default() {
1381                        result.push((offset..end_offset, highlight_id));
1382                    }
1383                }
1384                offset = end_offset;
1385            }
1386        }
1387        result
1388    }
1389
1390    pub fn path_suffixes(&self) -> &[String] {
1391        &self.config.matcher.path_suffixes
1392    }
1393
1394    pub fn should_autoclose_before(&self, c: char) -> bool {
1395        c.is_whitespace() || self.config.autoclose_before.contains(c)
1396    }
1397
1398    pub fn set_theme(&self, theme: &SyntaxTheme) {
1399        if let Some(grammar) = self.grammar.as_ref() {
1400            if let Some(highlights_query) = &grammar.highlights_query {
1401                *grammar.highlight_map.lock() =
1402                    HighlightMap::new(highlights_query.capture_names(), theme);
1403            }
1404        }
1405    }
1406
1407    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1408        self.grammar.as_ref()
1409    }
1410
1411    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1412        LanguageScope {
1413            language: self.clone(),
1414            override_id: None,
1415        }
1416    }
1417
1418    pub fn lsp_id(&self) -> String {
1419        self.config.name.lsp_id()
1420    }
1421
1422    pub fn prettier_parser_name(&self) -> Option<&str> {
1423        self.config.prettier_parser_name.as_deref()
1424    }
1425
1426    pub fn config(&self) -> &LanguageConfig {
1427        &self.config
1428    }
1429}
1430
1431impl LanguageScope {
1432    pub fn path_suffixes(&self) -> &[String] {
1433        &self.language.path_suffixes()
1434    }
1435
1436    pub fn language_name(&self) -> LanguageName {
1437        self.language.config.name.clone()
1438    }
1439
1440    pub fn collapsed_placeholder(&self) -> &str {
1441        self.language.config.collapsed_placeholder.as_ref()
1442    }
1443
1444    /// Returns line prefix that is inserted in e.g. line continuations or
1445    /// in `toggle comments` action.
1446    pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1447        Override::as_option(
1448            self.config_override().map(|o| &o.line_comments),
1449            Some(&self.language.config.line_comments),
1450        )
1451        .map_or(&[] as &[_], |e| e.as_slice())
1452    }
1453
1454    pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1455        Override::as_option(
1456            self.config_override().map(|o| &o.block_comment),
1457            self.language.config.block_comment.as_ref(),
1458        )
1459        .map(|e| (&e.0, &e.1))
1460    }
1461
1462    /// Returns a list of language-specific word characters.
1463    ///
1464    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1465    /// the purpose of actions like 'move to next word end` or whole-word search.
1466    /// It additionally accounts for language's additional word characters.
1467    pub fn word_characters(&self) -> Option<&HashSet<char>> {
1468        Override::as_option(
1469            self.config_override().map(|o| &o.word_characters),
1470            Some(&self.language.config.word_characters),
1471        )
1472    }
1473
1474    /// Returns a list of bracket pairs for a given language with an additional
1475    /// piece of information about whether the particular bracket pair is currently active for a given language.
1476    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1477        let mut disabled_ids = self
1478            .config_override()
1479            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1480        self.language
1481            .config
1482            .brackets
1483            .pairs
1484            .iter()
1485            .enumerate()
1486            .map(move |(ix, bracket)| {
1487                let mut is_enabled = true;
1488                if let Some(next_disabled_ix) = disabled_ids.first() {
1489                    if ix == *next_disabled_ix as usize {
1490                        disabled_ids = &disabled_ids[1..];
1491                        is_enabled = false;
1492                    }
1493                }
1494                (bracket, is_enabled)
1495            })
1496    }
1497
1498    pub fn should_autoclose_before(&self, c: char) -> bool {
1499        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1500    }
1501
1502    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1503        let config = &self.language.config;
1504        let opt_in_servers = &config.scope_opt_in_language_servers;
1505        if opt_in_servers.iter().any(|o| *o == *name) {
1506            if let Some(over) = self.config_override() {
1507                over.opt_into_language_servers.iter().any(|o| *o == *name)
1508            } else {
1509                false
1510            }
1511        } else {
1512            true
1513        }
1514    }
1515
1516    pub fn override_name(&self) -> Option<&str> {
1517        let id = self.override_id?;
1518        let grammar = self.language.grammar.as_ref()?;
1519        let override_config = grammar.override_config.as_ref()?;
1520        override_config.values.get(&id).map(|e| e.name.as_str())
1521    }
1522
1523    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1524        let id = self.override_id?;
1525        let grammar = self.language.grammar.as_ref()?;
1526        let override_config = grammar.override_config.as_ref()?;
1527        override_config.values.get(&id).map(|e| &e.value)
1528    }
1529}
1530
1531impl Hash for Language {
1532    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1533        self.id.hash(state)
1534    }
1535}
1536
1537impl PartialEq for Language {
1538    fn eq(&self, other: &Self) -> bool {
1539        self.id.eq(&other.id)
1540    }
1541}
1542
1543impl Eq for Language {}
1544
1545impl Debug for Language {
1546    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1547        f.debug_struct("Language")
1548            .field("name", &self.config.name)
1549            .finish()
1550    }
1551}
1552
1553impl Grammar {
1554    pub fn id(&self) -> GrammarId {
1555        self.id
1556    }
1557
1558    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1559        with_parser(|parser| {
1560            parser
1561                .set_language(&self.ts_language)
1562                .expect("incompatible grammar");
1563            let mut chunks = text.chunks_in_range(0..text.len());
1564            parser
1565                .parse_with(
1566                    &mut move |offset, _| {
1567                        chunks.seek(offset);
1568                        chunks.next().unwrap_or("").as_bytes()
1569                    },
1570                    old_tree.as_ref(),
1571                )
1572                .unwrap()
1573        })
1574    }
1575
1576    pub fn highlight_map(&self) -> HighlightMap {
1577        self.highlight_map.lock().clone()
1578    }
1579
1580    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1581        let capture_id = self
1582            .highlights_query
1583            .as_ref()?
1584            .capture_index_for_name(name)?;
1585        Some(self.highlight_map.lock().get(capture_id))
1586    }
1587}
1588
1589impl CodeLabel {
1590    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1591        let mut result = Self {
1592            runs: Vec::new(),
1593            filter_range: 0..text.len(),
1594            text,
1595        };
1596        if let Some(filter_text) = filter_text {
1597            if let Some(ix) = result.text.find(filter_text) {
1598                result.filter_range = ix..ix + filter_text.len();
1599            }
1600        }
1601        result
1602    }
1603
1604    pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
1605        let start_ix = self.text.len();
1606        self.text.push_str(text);
1607        let end_ix = self.text.len();
1608        if let Some(highlight) = highlight {
1609            self.runs.push((start_ix..end_ix, highlight));
1610        }
1611    }
1612
1613    pub fn text(&self) -> &str {
1614        self.text.as_str()
1615    }
1616}
1617
1618impl From<String> for CodeLabel {
1619    fn from(value: String) -> Self {
1620        Self::plain(value, None)
1621    }
1622}
1623
1624impl From<&str> for CodeLabel {
1625    fn from(value: &str) -> Self {
1626        Self::plain(value.to_string(), None)
1627    }
1628}
1629
1630impl Ord for LanguageMatcher {
1631    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1632        self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1633            self.first_line_pattern
1634                .as_ref()
1635                .map(Regex::as_str)
1636                .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1637        })
1638    }
1639}
1640
1641impl PartialOrd for LanguageMatcher {
1642    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1643        Some(self.cmp(other))
1644    }
1645}
1646
1647impl Eq for LanguageMatcher {}
1648
1649impl PartialEq for LanguageMatcher {
1650    fn eq(&self, other: &Self) -> bool {
1651        self.path_suffixes == other.path_suffixes
1652            && self.first_line_pattern.as_ref().map(Regex::as_str)
1653                == other.first_line_pattern.as_ref().map(Regex::as_str)
1654    }
1655}
1656
1657#[cfg(any(test, feature = "test-support"))]
1658impl Default for FakeLspAdapter {
1659    fn default() -> Self {
1660        Self {
1661            name: "the-fake-language-server",
1662            capabilities: lsp::LanguageServer::full_capabilities(),
1663            initializer: None,
1664            disk_based_diagnostics_progress_token: None,
1665            initialization_options: None,
1666            disk_based_diagnostics_sources: Vec::new(),
1667            prettier_plugins: Vec::new(),
1668            language_server_binary: LanguageServerBinary {
1669                path: "/the/fake/lsp/path".into(),
1670                arguments: vec![],
1671                env: Default::default(),
1672            },
1673        }
1674    }
1675}
1676
1677#[cfg(any(test, feature = "test-support"))]
1678#[async_trait(?Send)]
1679impl LspAdapter for FakeLspAdapter {
1680    fn name(&self) -> LanguageServerName {
1681        LanguageServerName(self.name.into())
1682    }
1683
1684    async fn check_if_user_installed(
1685        &self,
1686        _: &dyn LspAdapterDelegate,
1687        _: Arc<dyn LanguageToolchainStore>,
1688        _: &AsyncAppContext,
1689    ) -> Option<LanguageServerBinary> {
1690        Some(self.language_server_binary.clone())
1691    }
1692
1693    fn get_language_server_command<'a>(
1694        self: Arc<Self>,
1695        _: Arc<dyn LspAdapterDelegate>,
1696        _: Arc<dyn LanguageToolchainStore>,
1697        _: LanguageServerBinaryOptions,
1698        _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
1699        _: &'a mut AsyncAppContext,
1700    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
1701        async move { Ok(self.language_server_binary.clone()) }.boxed_local()
1702    }
1703
1704    async fn fetch_latest_server_version(
1705        &self,
1706        _: &dyn LspAdapterDelegate,
1707    ) -> Result<Box<dyn 'static + Send + Any>> {
1708        unreachable!();
1709    }
1710
1711    async fn fetch_server_binary(
1712        &self,
1713        _: Box<dyn 'static + Send + Any>,
1714        _: PathBuf,
1715        _: &dyn LspAdapterDelegate,
1716    ) -> Result<LanguageServerBinary> {
1717        unreachable!();
1718    }
1719
1720    async fn cached_server_binary(
1721        &self,
1722        _: PathBuf,
1723        _: &dyn LspAdapterDelegate,
1724    ) -> Option<LanguageServerBinary> {
1725        unreachable!();
1726    }
1727
1728    fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1729
1730    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1731        self.disk_based_diagnostics_sources.clone()
1732    }
1733
1734    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1735        self.disk_based_diagnostics_progress_token.clone()
1736    }
1737
1738    async fn initialization_options(
1739        self: Arc<Self>,
1740        _: &Arc<dyn LspAdapterDelegate>,
1741    ) -> Result<Option<Value>> {
1742        Ok(self.initialization_options.clone())
1743    }
1744}
1745
1746fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1747    for (ix, name) in query.capture_names().iter().enumerate() {
1748        for (capture_name, index) in captures.iter_mut() {
1749            if capture_name == name {
1750                **index = Some(ix as u32);
1751                break;
1752            }
1753        }
1754    }
1755}
1756
1757pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1758    lsp::Position::new(point.row, point.column)
1759}
1760
1761pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1762    Unclipped(PointUtf16::new(point.line, point.character))
1763}
1764
1765pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1766    lsp::Range {
1767        start: point_to_lsp(range.start),
1768        end: point_to_lsp(range.end),
1769    }
1770}
1771
1772pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1773    let mut start = point_from_lsp(range.start);
1774    let mut end = point_from_lsp(range.end);
1775    if start > end {
1776        mem::swap(&mut start, &mut end);
1777    }
1778    start..end
1779}
1780
1781#[cfg(test)]
1782mod tests {
1783    use super::*;
1784    use gpui::TestAppContext;
1785
1786    #[gpui::test(iterations = 10)]
1787    async fn test_language_loading(cx: &mut TestAppContext) {
1788        let languages = LanguageRegistry::test(cx.executor());
1789        let languages = Arc::new(languages);
1790        languages.register_native_grammars([
1791            ("json", tree_sitter_json::LANGUAGE),
1792            ("rust", tree_sitter_rust::LANGUAGE),
1793        ]);
1794        languages.register_test_language(LanguageConfig {
1795            name: "JSON".into(),
1796            grammar: Some("json".into()),
1797            matcher: LanguageMatcher {
1798                path_suffixes: vec!["json".into()],
1799                ..Default::default()
1800            },
1801            ..Default::default()
1802        });
1803        languages.register_test_language(LanguageConfig {
1804            name: "Rust".into(),
1805            grammar: Some("rust".into()),
1806            matcher: LanguageMatcher {
1807                path_suffixes: vec!["rs".into()],
1808                ..Default::default()
1809            },
1810            ..Default::default()
1811        });
1812        assert_eq!(
1813            languages.language_names(),
1814            &[
1815                "JSON".to_string(),
1816                "Plain Text".to_string(),
1817                "Rust".to_string(),
1818            ]
1819        );
1820
1821        let rust1 = languages.language_for_name("Rust");
1822        let rust2 = languages.language_for_name("Rust");
1823
1824        // Ensure language is still listed even if it's being loaded.
1825        assert_eq!(
1826            languages.language_names(),
1827            &[
1828                "JSON".to_string(),
1829                "Plain Text".to_string(),
1830                "Rust".to_string(),
1831            ]
1832        );
1833
1834        let (rust1, rust2) = futures::join!(rust1, rust2);
1835        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1836
1837        // Ensure language is still listed even after loading it.
1838        assert_eq!(
1839            languages.language_names(),
1840            &[
1841                "JSON".to_string(),
1842                "Plain Text".to_string(),
1843                "Rust".to_string(),
1844            ]
1845        );
1846
1847        // Loading an unknown language returns an error.
1848        assert!(languages.language_for_name("Unknown").await.is_err());
1849    }
1850}