language.rs

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