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