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