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