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::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, 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}
 614
 615#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
 616pub struct LanguageMatcher {
 617    /// 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`.
 618    #[serde(default)]
 619    pub path_suffixes: Vec<String>,
 620    /// A regex pattern that determines whether the language should be assigned to a file or not.
 621    #[serde(
 622        default,
 623        serialize_with = "serialize_regex",
 624        deserialize_with = "deserialize_regex"
 625    )]
 626    #[schemars(schema_with = "regex_json_schema")]
 627    pub first_line_pattern: Option<Regex>,
 628}
 629
 630/// Represents a language for the given range. Some languages (e.g. HTML)
 631/// interleave several languages together, thus a single buffer might actually contain
 632/// several nested scopes.
 633#[derive(Clone, Debug)]
 634pub struct LanguageScope {
 635    language: Arc<Language>,
 636    override_id: Option<u32>,
 637}
 638
 639#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
 640pub struct LanguageConfigOverride {
 641    #[serde(default)]
 642    pub line_comments: Override<Vec<Arc<str>>>,
 643    #[serde(default)]
 644    pub block_comment: Override<(Arc<str>, Arc<str>)>,
 645    #[serde(skip_deserializing)]
 646    #[schemars(skip)]
 647    pub disabled_bracket_ixs: Vec<u16>,
 648    #[serde(default)]
 649    pub word_characters: Override<HashSet<char>>,
 650    #[serde(default)]
 651    pub opt_into_language_servers: Vec<String>,
 652}
 653
 654#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
 655#[serde(untagged)]
 656pub enum Override<T> {
 657    Remove { remove: bool },
 658    Set(T),
 659}
 660
 661impl<T> Default for Override<T> {
 662    fn default() -> Self {
 663        Override::Remove { remove: false }
 664    }
 665}
 666
 667impl<T> Override<T> {
 668    fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
 669        match this {
 670            Some(Self::Set(value)) => Some(value),
 671            Some(Self::Remove { remove: true }) => None,
 672            Some(Self::Remove { remove: false }) | None => original,
 673        }
 674    }
 675}
 676
 677impl Default for LanguageConfig {
 678    fn default() -> Self {
 679        Self {
 680            name: "".into(),
 681            code_fence_block_name: None,
 682            grammar: None,
 683            matcher: LanguageMatcher::default(),
 684            brackets: Default::default(),
 685            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
 686            increase_indent_pattern: Default::default(),
 687            decrease_indent_pattern: Default::default(),
 688            autoclose_before: Default::default(),
 689            line_comments: Default::default(),
 690            block_comment: Default::default(),
 691            scope_opt_in_language_servers: Default::default(),
 692            overrides: Default::default(),
 693            word_characters: Default::default(),
 694            collapsed_placeholder: Default::default(),
 695            hard_tabs: Default::default(),
 696            tab_size: Default::default(),
 697            soft_wrap: Default::default(),
 698        }
 699    }
 700}
 701
 702fn auto_indent_using_last_non_empty_line_default() -> bool {
 703    true
 704}
 705
 706fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
 707    let source = Option::<String>::deserialize(d)?;
 708    if let Some(source) = source {
 709        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
 710    } else {
 711        Ok(None)
 712    }
 713}
 714
 715fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
 716    Schema::Object(SchemaObject {
 717        instance_type: Some(InstanceType::String.into()),
 718        ..Default::default()
 719    })
 720}
 721
 722fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
 723where
 724    S: Serializer,
 725{
 726    match regex {
 727        Some(regex) => serializer.serialize_str(regex.as_str()),
 728        None => serializer.serialize_none(),
 729    }
 730}
 731
 732#[doc(hidden)]
 733#[cfg(any(test, feature = "test-support"))]
 734pub struct FakeLspAdapter {
 735    pub name: &'static str,
 736    pub initialization_options: Option<Value>,
 737    pub capabilities: lsp::ServerCapabilities,
 738    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
 739    pub disk_based_diagnostics_progress_token: Option<String>,
 740    pub disk_based_diagnostics_sources: Vec<String>,
 741    pub prettier_plugins: Vec<&'static str>,
 742    pub language_server_binary: LanguageServerBinary,
 743}
 744
 745/// Configuration of handling bracket pairs for a given language.
 746///
 747/// This struct includes settings for defining which pairs of characters are considered brackets and
 748/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
 749#[derive(Clone, Debug, Default, JsonSchema)]
 750pub struct BracketPairConfig {
 751    /// A list of character pairs that should be treated as brackets in the context of a given language.
 752    pub pairs: Vec<BracketPair>,
 753    /// A list of tree-sitter scopes for which a given bracket should not be active.
 754    /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
 755    #[schemars(skip)]
 756    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
 757}
 758
 759fn bracket_pair_config_json_schema(gen: &mut SchemaGenerator) -> Schema {
 760    Option::<Vec<BracketPairContent>>::json_schema(gen)
 761}
 762
 763#[derive(Deserialize, JsonSchema)]
 764pub struct BracketPairContent {
 765    #[serde(flatten)]
 766    pub bracket_pair: BracketPair,
 767    #[serde(default)]
 768    pub not_in: Vec<String>,
 769}
 770
 771impl<'de> Deserialize<'de> for BracketPairConfig {
 772    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 773    where
 774        D: Deserializer<'de>,
 775    {
 776        let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
 777        let mut brackets = Vec::with_capacity(result.len());
 778        let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
 779        for entry in result {
 780            brackets.push(entry.bracket_pair);
 781            disabled_scopes_by_bracket_ix.push(entry.not_in);
 782        }
 783
 784        Ok(BracketPairConfig {
 785            pairs: brackets,
 786            disabled_scopes_by_bracket_ix,
 787        })
 788    }
 789}
 790
 791/// Describes a single bracket pair and how an editor should react to e.g. inserting
 792/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
 793#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
 794pub struct BracketPair {
 795    /// Starting substring for a bracket.
 796    pub start: String,
 797    /// Ending substring for a bracket.
 798    pub end: String,
 799    /// True if `end` should be automatically inserted right after `start` characters.
 800    pub close: bool,
 801    /// True if an extra newline should be inserted while the cursor is in the middle
 802    /// of that bracket pair.
 803    pub newline: bool,
 804}
 805
 806#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 807pub(crate) struct LanguageId(usize);
 808
 809impl LanguageId {
 810    pub(crate) fn new() -> Self {
 811        Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
 812    }
 813}
 814
 815pub struct Language {
 816    pub(crate) id: LanguageId,
 817    pub(crate) config: LanguageConfig,
 818    pub(crate) grammar: Option<Arc<Grammar>>,
 819    pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
 820}
 821
 822#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 823pub struct GrammarId(pub usize);
 824
 825impl GrammarId {
 826    pub(crate) fn new() -> Self {
 827        Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
 828    }
 829}
 830
 831pub struct Grammar {
 832    id: GrammarId,
 833    pub ts_language: tree_sitter::Language,
 834    pub(crate) error_query: Query,
 835    pub(crate) highlights_query: Option<Query>,
 836    pub(crate) brackets_config: Option<BracketConfig>,
 837    pub(crate) redactions_config: Option<RedactionConfig>,
 838    pub(crate) runnable_config: Option<RunnableConfig>,
 839    pub(crate) indents_config: Option<IndentConfig>,
 840    pub outline_config: Option<OutlineConfig>,
 841    pub embedding_config: Option<EmbeddingConfig>,
 842    pub(crate) injection_config: Option<InjectionConfig>,
 843    pub(crate) override_config: Option<OverrideConfig>,
 844    pub(crate) highlight_map: Mutex<HighlightMap>,
 845}
 846
 847struct IndentConfig {
 848    query: Query,
 849    indent_capture_ix: u32,
 850    start_capture_ix: Option<u32>,
 851    end_capture_ix: Option<u32>,
 852    outdent_capture_ix: Option<u32>,
 853}
 854
 855pub struct OutlineConfig {
 856    pub query: Query,
 857    pub item_capture_ix: u32,
 858    pub name_capture_ix: u32,
 859    pub context_capture_ix: Option<u32>,
 860    pub extra_context_capture_ix: Option<u32>,
 861}
 862
 863#[derive(Debug)]
 864pub struct EmbeddingConfig {
 865    pub query: Query,
 866    pub item_capture_ix: u32,
 867    pub name_capture_ix: Option<u32>,
 868    pub context_capture_ix: Option<u32>,
 869    pub collapse_capture_ix: Option<u32>,
 870    pub keep_capture_ix: Option<u32>,
 871}
 872
 873struct InjectionConfig {
 874    query: Query,
 875    content_capture_ix: u32,
 876    language_capture_ix: Option<u32>,
 877    patterns: Vec<InjectionPatternConfig>,
 878}
 879
 880struct RedactionConfig {
 881    pub query: Query,
 882    pub redaction_capture_ix: u32,
 883}
 884
 885#[derive(Clone, Debug, PartialEq)]
 886enum RunnableCapture {
 887    Named(SharedString),
 888    Run,
 889}
 890
 891struct RunnableConfig {
 892    pub query: Query,
 893    /// A mapping from capture indice to capture kind
 894    pub extra_captures: Vec<RunnableCapture>,
 895}
 896
 897struct OverrideConfig {
 898    query: Query,
 899    values: HashMap<u32, (String, LanguageConfigOverride)>,
 900}
 901
 902#[derive(Default, Clone)]
 903struct InjectionPatternConfig {
 904    language: Option<Box<str>>,
 905    combined: bool,
 906}
 907
 908struct BracketConfig {
 909    query: Query,
 910    open_capture_ix: u32,
 911    close_capture_ix: u32,
 912}
 913
 914impl Language {
 915    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
 916        Self::new_with_id(LanguageId::new(), config, ts_language)
 917    }
 918
 919    fn new_with_id(
 920        id: LanguageId,
 921        config: LanguageConfig,
 922        ts_language: Option<tree_sitter::Language>,
 923    ) -> Self {
 924        Self {
 925            id,
 926            config,
 927            grammar: ts_language.map(|ts_language| {
 928                Arc::new(Grammar {
 929                    id: GrammarId::new(),
 930                    highlights_query: None,
 931                    brackets_config: None,
 932                    outline_config: None,
 933                    embedding_config: None,
 934                    indents_config: None,
 935                    injection_config: None,
 936                    override_config: None,
 937                    redactions_config: None,
 938                    runnable_config: None,
 939                    error_query: Query::new(&ts_language, "(ERROR) @error").unwrap(),
 940                    ts_language,
 941                    highlight_map: Default::default(),
 942                })
 943            }),
 944            context_provider: None,
 945        }
 946    }
 947
 948    pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
 949        self.context_provider = provider;
 950        self
 951    }
 952
 953    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
 954        if let Some(query) = queries.highlights {
 955            self = self
 956                .with_highlights_query(query.as_ref())
 957                .context("Error loading highlights query")?;
 958        }
 959        if let Some(query) = queries.brackets {
 960            self = self
 961                .with_brackets_query(query.as_ref())
 962                .context("Error loading brackets query")?;
 963        }
 964        if let Some(query) = queries.indents {
 965            self = self
 966                .with_indents_query(query.as_ref())
 967                .context("Error loading indents query")?;
 968        }
 969        if let Some(query) = queries.outline {
 970            self = self
 971                .with_outline_query(query.as_ref())
 972                .context("Error loading outline query")?;
 973        }
 974        if let Some(query) = queries.embedding {
 975            self = self
 976                .with_embedding_query(query.as_ref())
 977                .context("Error loading embedding query")?;
 978        }
 979        if let Some(query) = queries.injections {
 980            self = self
 981                .with_injection_query(query.as_ref())
 982                .context("Error loading injection query")?;
 983        }
 984        if let Some(query) = queries.overrides {
 985            self = self
 986                .with_override_query(query.as_ref())
 987                .context("Error loading override query")?;
 988        }
 989        if let Some(query) = queries.redactions {
 990            self = self
 991                .with_redaction_query(query.as_ref())
 992                .context("Error loading redaction query")?;
 993        }
 994        if let Some(query) = queries.runnables {
 995            self = self
 996                .with_runnable_query(query.as_ref())
 997                .context("Error loading tests query")?;
 998        }
 999        Ok(self)
1000    }
1001
1002    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1003        let grammar = self
1004            .grammar_mut()
1005            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1006        grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1007        Ok(self)
1008    }
1009
1010    pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1011        let grammar = self
1012            .grammar_mut()
1013            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1014
1015        let query = Query::new(&grammar.ts_language, source)?;
1016        let mut extra_captures = Vec::with_capacity(query.capture_names().len());
1017
1018        for name in query.capture_names().iter() {
1019            let kind = if *name == "run" {
1020                RunnableCapture::Run
1021            } else {
1022                RunnableCapture::Named(name.to_string().into())
1023            };
1024            extra_captures.push(kind);
1025        }
1026
1027        grammar.runnable_config = Some(RunnableConfig {
1028            extra_captures,
1029            query,
1030        });
1031
1032        Ok(self)
1033    }
1034
1035    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1036        let grammar = self
1037            .grammar_mut()
1038            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1039        let query = Query::new(&grammar.ts_language, source)?;
1040        let mut item_capture_ix = None;
1041        let mut name_capture_ix = None;
1042        let mut context_capture_ix = None;
1043        let mut extra_context_capture_ix = None;
1044        get_capture_indices(
1045            &query,
1046            &mut [
1047                ("item", &mut item_capture_ix),
1048                ("name", &mut name_capture_ix),
1049                ("context", &mut context_capture_ix),
1050                ("context.extra", &mut extra_context_capture_ix),
1051            ],
1052        );
1053        if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1054            grammar.outline_config = Some(OutlineConfig {
1055                query,
1056                item_capture_ix,
1057                name_capture_ix,
1058                context_capture_ix,
1059                extra_context_capture_ix,
1060            });
1061        }
1062        Ok(self)
1063    }
1064
1065    pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1066        let grammar = self
1067            .grammar_mut()
1068            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1069        let query = Query::new(&grammar.ts_language, source)?;
1070        let mut item_capture_ix = None;
1071        let mut name_capture_ix = None;
1072        let mut context_capture_ix = None;
1073        let mut collapse_capture_ix = None;
1074        let mut keep_capture_ix = None;
1075        get_capture_indices(
1076            &query,
1077            &mut [
1078                ("item", &mut item_capture_ix),
1079                ("name", &mut name_capture_ix),
1080                ("context", &mut context_capture_ix),
1081                ("keep", &mut keep_capture_ix),
1082                ("collapse", &mut collapse_capture_ix),
1083            ],
1084        );
1085        if let Some(item_capture_ix) = item_capture_ix {
1086            grammar.embedding_config = Some(EmbeddingConfig {
1087                query,
1088                item_capture_ix,
1089                name_capture_ix,
1090                context_capture_ix,
1091                collapse_capture_ix,
1092                keep_capture_ix,
1093            });
1094        }
1095        Ok(self)
1096    }
1097
1098    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1099        let grammar = self
1100            .grammar_mut()
1101            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1102        let query = Query::new(&grammar.ts_language, source)?;
1103        let mut open_capture_ix = None;
1104        let mut close_capture_ix = None;
1105        get_capture_indices(
1106            &query,
1107            &mut [
1108                ("open", &mut open_capture_ix),
1109                ("close", &mut close_capture_ix),
1110            ],
1111        );
1112        if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1113            grammar.brackets_config = Some(BracketConfig {
1114                query,
1115                open_capture_ix,
1116                close_capture_ix,
1117            });
1118        }
1119        Ok(self)
1120    }
1121
1122    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1123        let grammar = self
1124            .grammar_mut()
1125            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1126        let query = Query::new(&grammar.ts_language, source)?;
1127        let mut indent_capture_ix = None;
1128        let mut start_capture_ix = None;
1129        let mut end_capture_ix = None;
1130        let mut outdent_capture_ix = None;
1131        get_capture_indices(
1132            &query,
1133            &mut [
1134                ("indent", &mut indent_capture_ix),
1135                ("start", &mut start_capture_ix),
1136                ("end", &mut end_capture_ix),
1137                ("outdent", &mut outdent_capture_ix),
1138            ],
1139        );
1140        if let Some(indent_capture_ix) = indent_capture_ix {
1141            grammar.indents_config = Some(IndentConfig {
1142                query,
1143                indent_capture_ix,
1144                start_capture_ix,
1145                end_capture_ix,
1146                outdent_capture_ix,
1147            });
1148        }
1149        Ok(self)
1150    }
1151
1152    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1153        let grammar = self
1154            .grammar_mut()
1155            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1156        let query = Query::new(&grammar.ts_language, source)?;
1157        let mut language_capture_ix = None;
1158        let mut content_capture_ix = None;
1159        get_capture_indices(
1160            &query,
1161            &mut [
1162                ("language", &mut language_capture_ix),
1163                ("content", &mut content_capture_ix),
1164            ],
1165        );
1166        let patterns = (0..query.pattern_count())
1167            .map(|ix| {
1168                let mut config = InjectionPatternConfig::default();
1169                for setting in query.property_settings(ix) {
1170                    match setting.key.as_ref() {
1171                        "language" => {
1172                            config.language.clone_from(&setting.value);
1173                        }
1174                        "combined" => {
1175                            config.combined = true;
1176                        }
1177                        _ => {}
1178                    }
1179                }
1180                config
1181            })
1182            .collect();
1183        if let Some(content_capture_ix) = content_capture_ix {
1184            grammar.injection_config = Some(InjectionConfig {
1185                query,
1186                language_capture_ix,
1187                content_capture_ix,
1188                patterns,
1189            });
1190        }
1191        Ok(self)
1192    }
1193
1194    pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1195        let query = {
1196            let grammar = self
1197                .grammar
1198                .as_ref()
1199                .ok_or_else(|| anyhow!("no grammar for language"))?;
1200            Query::new(&grammar.ts_language, source)?
1201        };
1202
1203        let mut override_configs_by_id = HashMap::default();
1204        for (ix, name) in query.capture_names().iter().enumerate() {
1205            if !name.starts_with('_') {
1206                let value = self.config.overrides.remove(*name).unwrap_or_default();
1207                for server_name in &value.opt_into_language_servers {
1208                    if !self
1209                        .config
1210                        .scope_opt_in_language_servers
1211                        .contains(server_name)
1212                    {
1213                        util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1214                    }
1215                }
1216
1217                override_configs_by_id.insert(ix as u32, (name.to_string(), value));
1218            }
1219        }
1220
1221        if !self.config.overrides.is_empty() {
1222            let keys = self.config.overrides.keys().collect::<Vec<_>>();
1223            Err(anyhow!(
1224                "language {:?} has overrides in config not in query: {keys:?}",
1225                self.config.name
1226            ))?;
1227        }
1228
1229        for disabled_scope_name in self
1230            .config
1231            .brackets
1232            .disabled_scopes_by_bracket_ix
1233            .iter()
1234            .flatten()
1235        {
1236            if !override_configs_by_id
1237                .values()
1238                .any(|(scope_name, _)| scope_name == disabled_scope_name)
1239            {
1240                Err(anyhow!(
1241                    "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1242                    self.config.name
1243                ))?;
1244            }
1245        }
1246
1247        for (name, override_config) in override_configs_by_id.values_mut() {
1248            override_config.disabled_bracket_ixs = self
1249                .config
1250                .brackets
1251                .disabled_scopes_by_bracket_ix
1252                .iter()
1253                .enumerate()
1254                .filter_map(|(ix, disabled_scope_names)| {
1255                    if disabled_scope_names.contains(name) {
1256                        Some(ix as u16)
1257                    } else {
1258                        None
1259                    }
1260                })
1261                .collect();
1262        }
1263
1264        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1265
1266        let grammar = self
1267            .grammar_mut()
1268            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1269        grammar.override_config = Some(OverrideConfig {
1270            query,
1271            values: override_configs_by_id,
1272        });
1273        Ok(self)
1274    }
1275
1276    pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1277        let grammar = self
1278            .grammar_mut()
1279            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1280
1281        let query = Query::new(&grammar.ts_language, source)?;
1282        let mut redaction_capture_ix = None;
1283        get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1284
1285        if let Some(redaction_capture_ix) = redaction_capture_ix {
1286            grammar.redactions_config = Some(RedactionConfig {
1287                query,
1288                redaction_capture_ix,
1289            });
1290        }
1291
1292        Ok(self)
1293    }
1294
1295    fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1296        Arc::get_mut(self.grammar.as_mut()?)
1297    }
1298
1299    pub fn name(&self) -> Arc<str> {
1300        self.config.name.clone()
1301    }
1302
1303    pub fn code_fence_block_name(&self) -> Arc<str> {
1304        self.config
1305            .code_fence_block_name
1306            .clone()
1307            .unwrap_or_else(|| self.config.name.to_lowercase().into())
1308    }
1309
1310    pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1311        self.context_provider.clone()
1312    }
1313
1314    pub fn highlight_text<'a>(
1315        self: &'a Arc<Self>,
1316        text: &'a Rope,
1317        range: Range<usize>,
1318    ) -> Vec<(Range<usize>, HighlightId)> {
1319        let mut result = Vec::new();
1320        if let Some(grammar) = &self.grammar {
1321            let tree = grammar.parse_text(text, None);
1322            let captures =
1323                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1324                    grammar.highlights_query.as_ref()
1325                });
1326            let highlight_maps = vec![grammar.highlight_map()];
1327            let mut offset = 0;
1328            for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1329                let end_offset = offset + chunk.text.len();
1330                if let Some(highlight_id) = chunk.syntax_highlight_id {
1331                    if !highlight_id.is_default() {
1332                        result.push((offset..end_offset, highlight_id));
1333                    }
1334                }
1335                offset = end_offset;
1336            }
1337        }
1338        result
1339    }
1340
1341    pub fn path_suffixes(&self) -> &[String] {
1342        &self.config.matcher.path_suffixes
1343    }
1344
1345    pub fn should_autoclose_before(&self, c: char) -> bool {
1346        c.is_whitespace() || self.config.autoclose_before.contains(c)
1347    }
1348
1349    pub fn set_theme(&self, theme: &SyntaxTheme) {
1350        if let Some(grammar) = self.grammar.as_ref() {
1351            if let Some(highlights_query) = &grammar.highlights_query {
1352                *grammar.highlight_map.lock() =
1353                    HighlightMap::new(highlights_query.capture_names(), theme);
1354            }
1355        }
1356    }
1357
1358    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1359        self.grammar.as_ref()
1360    }
1361
1362    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1363        LanguageScope {
1364            language: self.clone(),
1365            override_id: None,
1366        }
1367    }
1368
1369    pub fn lsp_id(&self) -> String {
1370        match self.config.name.as_ref() {
1371            "Plain Text" => "plaintext".to_string(),
1372            language_name => language_name.to_lowercase(),
1373        }
1374    }
1375}
1376
1377impl LanguageScope {
1378    pub fn collapsed_placeholder(&self) -> &str {
1379        self.language.config.collapsed_placeholder.as_ref()
1380    }
1381
1382    /// Returns line prefix that is inserted in e.g. line continuations or
1383    /// in `toggle comments` action.
1384    pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1385        Override::as_option(
1386            self.config_override().map(|o| &o.line_comments),
1387            Some(&self.language.config.line_comments),
1388        )
1389        .map_or(&[] as &[_], |e| e.as_slice())
1390    }
1391
1392    pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1393        Override::as_option(
1394            self.config_override().map(|o| &o.block_comment),
1395            self.language.config.block_comment.as_ref(),
1396        )
1397        .map(|e| (&e.0, &e.1))
1398    }
1399
1400    /// Returns a list of language-specific word characters.
1401    ///
1402    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1403    /// the purpose of actions like 'move to next word end` or whole-word search.
1404    /// It additionally accounts for language's additional word characters.
1405    pub fn word_characters(&self) -> Option<&HashSet<char>> {
1406        Override::as_option(
1407            self.config_override().map(|o| &o.word_characters),
1408            Some(&self.language.config.word_characters),
1409        )
1410    }
1411
1412    /// Returns a list of bracket pairs for a given language with an additional
1413    /// piece of information about whether the particular bracket pair is currently active for a given language.
1414    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1415        let mut disabled_ids = self
1416            .config_override()
1417            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1418        self.language
1419            .config
1420            .brackets
1421            .pairs
1422            .iter()
1423            .enumerate()
1424            .map(move |(ix, bracket)| {
1425                let mut is_enabled = true;
1426                if let Some(next_disabled_ix) = disabled_ids.first() {
1427                    if ix == *next_disabled_ix as usize {
1428                        disabled_ids = &disabled_ids[1..];
1429                        is_enabled = false;
1430                    }
1431                }
1432                (bracket, is_enabled)
1433            })
1434    }
1435
1436    pub fn should_autoclose_before(&self, c: char) -> bool {
1437        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1438    }
1439
1440    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1441        let config = &self.language.config;
1442        let opt_in_servers = &config.scope_opt_in_language_servers;
1443        if opt_in_servers.iter().any(|o| *o == *name.0) {
1444            if let Some(over) = self.config_override() {
1445                over.opt_into_language_servers.iter().any(|o| *o == *name.0)
1446            } else {
1447                false
1448            }
1449        } else {
1450            true
1451        }
1452    }
1453
1454    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1455        let id = self.override_id?;
1456        let grammar = self.language.grammar.as_ref()?;
1457        let override_config = grammar.override_config.as_ref()?;
1458        override_config.values.get(&id).map(|e| &e.1)
1459    }
1460}
1461
1462impl Hash for Language {
1463    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1464        self.id.hash(state)
1465    }
1466}
1467
1468impl PartialEq for Language {
1469    fn eq(&self, other: &Self) -> bool {
1470        self.id.eq(&other.id)
1471    }
1472}
1473
1474impl Eq for Language {}
1475
1476impl Debug for Language {
1477    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1478        f.debug_struct("Language")
1479            .field("name", &self.config.name)
1480            .finish()
1481    }
1482}
1483
1484impl Grammar {
1485    pub fn id(&self) -> GrammarId {
1486        self.id
1487    }
1488
1489    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1490        with_parser(|parser| {
1491            parser
1492                .set_language(&self.ts_language)
1493                .expect("incompatible grammar");
1494            let mut chunks = text.chunks_in_range(0..text.len());
1495            parser
1496                .parse_with(
1497                    &mut move |offset, _| {
1498                        chunks.seek(offset);
1499                        chunks.next().unwrap_or("").as_bytes()
1500                    },
1501                    old_tree.as_ref(),
1502                )
1503                .unwrap()
1504        })
1505    }
1506
1507    pub fn highlight_map(&self) -> HighlightMap {
1508        self.highlight_map.lock().clone()
1509    }
1510
1511    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1512        let capture_id = self
1513            .highlights_query
1514            .as_ref()?
1515            .capture_index_for_name(name)?;
1516        Some(self.highlight_map.lock().get(capture_id))
1517    }
1518}
1519
1520impl CodeLabel {
1521    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1522        let mut result = Self {
1523            runs: Vec::new(),
1524            filter_range: 0..text.len(),
1525            text,
1526        };
1527        if let Some(filter_text) = filter_text {
1528            if let Some(ix) = result.text.find(filter_text) {
1529                result.filter_range = ix..ix + filter_text.len();
1530            }
1531        }
1532        result
1533    }
1534}
1535
1536impl Ord for LanguageMatcher {
1537    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1538        self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1539            self.first_line_pattern
1540                .as_ref()
1541                .map(Regex::as_str)
1542                .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1543        })
1544    }
1545}
1546
1547impl PartialOrd for LanguageMatcher {
1548    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1549        Some(self.cmp(other))
1550    }
1551}
1552
1553impl Eq for LanguageMatcher {}
1554
1555impl PartialEq for LanguageMatcher {
1556    fn eq(&self, other: &Self) -> bool {
1557        self.path_suffixes == other.path_suffixes
1558            && self.first_line_pattern.as_ref().map(Regex::as_str)
1559                == other.first_line_pattern.as_ref().map(Regex::as_str)
1560    }
1561}
1562
1563#[cfg(any(test, feature = "test-support"))]
1564impl Default for FakeLspAdapter {
1565    fn default() -> Self {
1566        Self {
1567            name: "the-fake-language-server",
1568            capabilities: lsp::LanguageServer::full_capabilities(),
1569            initializer: None,
1570            disk_based_diagnostics_progress_token: None,
1571            initialization_options: None,
1572            disk_based_diagnostics_sources: Vec::new(),
1573            prettier_plugins: Vec::new(),
1574            language_server_binary: LanguageServerBinary {
1575                path: "/the/fake/lsp/path".into(),
1576                arguments: vec![],
1577                env: Default::default(),
1578            },
1579        }
1580    }
1581}
1582
1583#[cfg(any(test, feature = "test-support"))]
1584#[async_trait(?Send)]
1585impl LspAdapter for FakeLspAdapter {
1586    fn name(&self) -> LanguageServerName {
1587        LanguageServerName(self.name.into())
1588    }
1589
1590    fn get_language_server_command<'a>(
1591        self: Arc<Self>,
1592        _: Arc<Language>,
1593        _: Arc<Path>,
1594        _: Arc<dyn LspAdapterDelegate>,
1595        _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
1596        _: &'a mut AsyncAppContext,
1597    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
1598        async move { Ok(self.language_server_binary.clone()) }.boxed_local()
1599    }
1600
1601    async fn fetch_latest_server_version(
1602        &self,
1603        _: &dyn LspAdapterDelegate,
1604    ) -> Result<Box<dyn 'static + Send + Any>> {
1605        unreachable!();
1606    }
1607
1608    async fn fetch_server_binary(
1609        &self,
1610        _: Box<dyn 'static + Send + Any>,
1611        _: PathBuf,
1612        _: &dyn LspAdapterDelegate,
1613    ) -> Result<LanguageServerBinary> {
1614        unreachable!();
1615    }
1616
1617    async fn cached_server_binary(
1618        &self,
1619        _: PathBuf,
1620        _: &dyn LspAdapterDelegate,
1621    ) -> Option<LanguageServerBinary> {
1622        unreachable!();
1623    }
1624
1625    async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1626        unreachable!();
1627    }
1628
1629    fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1630
1631    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1632        self.disk_based_diagnostics_sources.clone()
1633    }
1634
1635    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1636        self.disk_based_diagnostics_progress_token.clone()
1637    }
1638
1639    async fn initialization_options(
1640        self: Arc<Self>,
1641        _: &Arc<dyn LspAdapterDelegate>,
1642    ) -> Result<Option<Value>> {
1643        Ok(self.initialization_options.clone())
1644    }
1645
1646    fn as_fake(&self) -> Option<&FakeLspAdapter> {
1647        Some(self)
1648    }
1649}
1650
1651fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1652    for (ix, name) in query.capture_names().iter().enumerate() {
1653        for (capture_name, index) in captures.iter_mut() {
1654            if capture_name == name {
1655                **index = Some(ix as u32);
1656                break;
1657            }
1658        }
1659    }
1660}
1661
1662pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1663    lsp::Position::new(point.row, point.column)
1664}
1665
1666pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1667    Unclipped(PointUtf16::new(point.line, point.character))
1668}
1669
1670pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1671    lsp::Range {
1672        start: point_to_lsp(range.start),
1673        end: point_to_lsp(range.end),
1674    }
1675}
1676
1677pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1678    let mut start = point_from_lsp(range.start);
1679    let mut end = point_from_lsp(range.end);
1680    if start > end {
1681        mem::swap(&mut start, &mut end);
1682    }
1683    start..end
1684}
1685
1686#[cfg(test)]
1687mod tests {
1688    use super::*;
1689    use gpui::TestAppContext;
1690
1691    #[gpui::test(iterations = 10)]
1692    async fn test_language_loading(cx: &mut TestAppContext) {
1693        let languages = LanguageRegistry::test(cx.executor());
1694        let languages = Arc::new(languages);
1695        languages.register_native_grammars([
1696            ("json", tree_sitter_json::language()),
1697            ("rust", tree_sitter_rust::language()),
1698        ]);
1699        languages.register_test_language(LanguageConfig {
1700            name: "JSON".into(),
1701            grammar: Some("json".into()),
1702            matcher: LanguageMatcher {
1703                path_suffixes: vec!["json".into()],
1704                ..Default::default()
1705            },
1706            ..Default::default()
1707        });
1708        languages.register_test_language(LanguageConfig {
1709            name: "Rust".into(),
1710            grammar: Some("rust".into()),
1711            matcher: LanguageMatcher {
1712                path_suffixes: vec!["rs".into()],
1713                ..Default::default()
1714            },
1715            ..Default::default()
1716        });
1717        assert_eq!(
1718            languages.language_names(),
1719            &[
1720                "JSON".to_string(),
1721                "Plain Text".to_string(),
1722                "Rust".to_string(),
1723            ]
1724        );
1725
1726        let rust1 = languages.language_for_name("Rust");
1727        let rust2 = languages.language_for_name("Rust");
1728
1729        // Ensure language is still listed even if it's being loaded.
1730        assert_eq!(
1731            languages.language_names(),
1732            &[
1733                "JSON".to_string(),
1734                "Plain Text".to_string(),
1735                "Rust".to_string(),
1736            ]
1737        );
1738
1739        let (rust1, rust2) = futures::join!(rust1, rust2);
1740        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1741
1742        // Ensure language is still listed even after loading it.
1743        assert_eq!(
1744            languages.language_names(),
1745            &[
1746                "JSON".to_string(),
1747                "Plain Text".to_string(),
1748                "Rust".to_string(),
1749            ]
1750        );
1751
1752        // Loading an unknown language returns an error.
1753        assert!(languages.language_for_name("Unknown").await.is_err());
1754    }
1755}