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