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