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