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 it's API.
   9mod buffer;
  10mod diagnostic_set;
  11mod highlight_map;
  12pub mod language_settings;
  13mod outline;
  14pub mod proto;
  15mod syntax_map;
  16
  17#[cfg(test)]
  18mod buffer_tests;
  19pub mod markdown;
  20
  21use anyhow::{anyhow, Context, Result};
  22use async_trait::async_trait;
  23use collections::{HashMap, HashSet};
  24use futures::{
  25    channel::{mpsc, oneshot},
  26    future::Shared,
  27    FutureExt, TryFutureExt as _,
  28};
  29use gpui::{AppContext, AsyncAppContext, BackgroundExecutor, Task};
  30pub use highlight_map::HighlightMap;
  31use lazy_static::lazy_static;
  32use lsp::{CodeActionKind, LanguageServerBinary};
  33use parking_lot::{Mutex, RwLock};
  34use postage::watch;
  35use regex::Regex;
  36use serde::{de, Deserialize, Deserializer};
  37use serde_json::Value;
  38use std::{
  39    any::Any,
  40    borrow::Cow,
  41    cell::RefCell,
  42    fmt::Debug,
  43    hash::Hash,
  44    mem,
  45    ops::{Not, Range},
  46    path::{Path, PathBuf},
  47    str,
  48    sync::{
  49        atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
  50        Arc,
  51    },
  52};
  53use syntax_map::SyntaxSnapshot;
  54use theme::{SyntaxTheme, Theme};
  55use tree_sitter::{self, Query};
  56use unicase::UniCase;
  57use util::{http::HttpClient, paths::PathExt};
  58use util::{post_inc, ResultExt, TryFutureExt as _, UnwrapFuture};
  59
  60pub use buffer::Operation;
  61pub use buffer::*;
  62pub use diagnostic_set::DiagnosticEntry;
  63pub use lsp::LanguageServerId;
  64pub use outline::{Outline, OutlineItem};
  65pub use syntax_map::{OwnedSyntaxLayer, SyntaxLayer};
  66pub use text::LineEnding;
  67pub use tree_sitter::{Parser, Tree};
  68
  69/// Initializes the `language` crate.
  70///
  71/// This should be called before making use of items from the create.
  72pub fn init(cx: &mut AppContext) {
  73    language_settings::init(cx);
  74}
  75
  76#[derive(Clone, Default)]
  77struct LspBinaryStatusSender {
  78    txs: Arc<Mutex<Vec<mpsc::UnboundedSender<(Arc<Language>, LanguageServerBinaryStatus)>>>>,
  79}
  80
  81impl LspBinaryStatusSender {
  82    fn subscribe(&self) -> mpsc::UnboundedReceiver<(Arc<Language>, LanguageServerBinaryStatus)> {
  83        let (tx, rx) = mpsc::unbounded();
  84        self.txs.lock().push(tx);
  85        rx
  86    }
  87
  88    fn send(&self, language: Arc<Language>, status: LanguageServerBinaryStatus) {
  89        let mut txs = self.txs.lock();
  90        txs.retain(|tx| {
  91            tx.unbounded_send((language.clone(), status.clone()))
  92                .is_ok()
  93        });
  94    }
  95}
  96
  97thread_local! {
  98    static PARSER: RefCell<Parser> = {
  99        RefCell::new(Parser::new())
 100    };
 101}
 102
 103lazy_static! {
 104    pub(crate) static ref NEXT_GRAMMAR_ID: AtomicUsize = Default::default();
 105    /// A shared grammar for plain text, exposed for reuse by downstream crates.
 106    #[doc(hidden)]
 107    pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(
 108        LanguageConfig {
 109            name: "Plain Text".into(),
 110            ..Default::default()
 111        },
 112        None,
 113    ));
 114}
 115
 116/// Types that represent a position in a buffer, and can be converted into
 117/// an LSP position, to send to a language server.
 118pub trait ToLspPosition {
 119    /// Converts the value into an LSP position.
 120    fn to_lsp_position(self) -> lsp::Position;
 121}
 122
 123/// A name of a language server.
 124#[derive(Clone, Debug, PartialEq, Eq, Hash)]
 125pub struct LanguageServerName(pub Arc<str>);
 126
 127/// Represents a Language Server, with certain cached sync properties.
 128/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
 129/// once at startup, and caches the results.
 130pub struct CachedLspAdapter {
 131    pub name: LanguageServerName,
 132    pub short_name: &'static str,
 133    pub disk_based_diagnostic_sources: Vec<String>,
 134    pub disk_based_diagnostics_progress_token: Option<String>,
 135    pub language_ids: HashMap<String, String>,
 136    pub adapter: Arc<dyn LspAdapter>,
 137    pub reinstall_attempt_count: AtomicU64,
 138}
 139
 140impl CachedLspAdapter {
 141    pub async fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
 142        let name = adapter.name();
 143        let short_name = adapter.short_name();
 144        let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
 145        let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
 146        let language_ids = adapter.language_ids();
 147
 148        Arc::new(CachedLspAdapter {
 149            name,
 150            short_name,
 151            disk_based_diagnostic_sources,
 152            disk_based_diagnostics_progress_token,
 153            language_ids,
 154            adapter,
 155            reinstall_attempt_count: AtomicU64::new(0),
 156        })
 157    }
 158
 159    pub async fn fetch_latest_server_version(
 160        &self,
 161        delegate: &dyn LspAdapterDelegate,
 162    ) -> Result<Box<dyn 'static + Send + Any>> {
 163        self.adapter.fetch_latest_server_version(delegate).await
 164    }
 165
 166    pub fn will_fetch_server(
 167        &self,
 168        delegate: &Arc<dyn LspAdapterDelegate>,
 169        cx: &mut AsyncAppContext,
 170    ) -> Option<Task<Result<()>>> {
 171        self.adapter.will_fetch_server(delegate, cx)
 172    }
 173
 174    pub fn will_start_server(
 175        &self,
 176        delegate: &Arc<dyn LspAdapterDelegate>,
 177        cx: &mut AsyncAppContext,
 178    ) -> Option<Task<Result<()>>> {
 179        self.adapter.will_start_server(delegate, cx)
 180    }
 181
 182    pub async fn fetch_server_binary(
 183        &self,
 184        version: Box<dyn 'static + Send + Any>,
 185        container_dir: PathBuf,
 186        delegate: &dyn LspAdapterDelegate,
 187    ) -> Result<LanguageServerBinary> {
 188        self.adapter
 189            .fetch_server_binary(version, container_dir, delegate)
 190            .await
 191    }
 192
 193    pub async fn cached_server_binary(
 194        &self,
 195        container_dir: PathBuf,
 196        delegate: &dyn LspAdapterDelegate,
 197    ) -> Option<LanguageServerBinary> {
 198        self.adapter
 199            .cached_server_binary(container_dir, delegate)
 200            .await
 201    }
 202
 203    pub fn can_be_reinstalled(&self) -> bool {
 204        self.adapter.can_be_reinstalled()
 205    }
 206
 207    pub async fn installation_test_binary(
 208        &self,
 209        container_dir: PathBuf,
 210    ) -> Option<LanguageServerBinary> {
 211        self.adapter.installation_test_binary(container_dir).await
 212    }
 213
 214    pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 215        self.adapter.code_action_kinds()
 216    }
 217
 218    pub fn workspace_configuration(&self, workspace_root: &Path, cx: &mut AppContext) -> Value {
 219        self.adapter.workspace_configuration(workspace_root, cx)
 220    }
 221
 222    pub fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
 223        self.adapter.process_diagnostics(params)
 224    }
 225
 226    pub async fn process_completion(&self, completion_item: &mut lsp::CompletionItem) {
 227        self.adapter.process_completion(completion_item).await
 228    }
 229
 230    pub async fn label_for_completion(
 231        &self,
 232        completion_item: &lsp::CompletionItem,
 233        language: &Arc<Language>,
 234    ) -> Option<CodeLabel> {
 235        self.adapter
 236            .label_for_completion(completion_item, language)
 237            .await
 238    }
 239
 240    pub async fn label_for_symbol(
 241        &self,
 242        name: &str,
 243        kind: lsp::SymbolKind,
 244        language: &Arc<Language>,
 245    ) -> Option<CodeLabel> {
 246        self.adapter.label_for_symbol(name, kind, language).await
 247    }
 248
 249    pub fn prettier_plugins(&self) -> &[&'static str] {
 250        self.adapter.prettier_plugins()
 251    }
 252}
 253
 254/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
 255// e.g. to display a notification or fetch data from the web.
 256pub trait LspAdapterDelegate: Send + Sync {
 257    fn show_notification(&self, message: &str, cx: &mut AppContext);
 258    fn http_client(&self) -> Arc<dyn HttpClient>;
 259}
 260
 261#[async_trait]
 262pub trait LspAdapter: 'static + Send + Sync {
 263    fn name(&self) -> LanguageServerName;
 264
 265    fn short_name(&self) -> &'static str;
 266
 267    async fn fetch_latest_server_version(
 268        &self,
 269        delegate: &dyn LspAdapterDelegate,
 270    ) -> Result<Box<dyn 'static + Send + Any>>;
 271
 272    fn will_fetch_server(
 273        &self,
 274        _: &Arc<dyn LspAdapterDelegate>,
 275        _: &mut AsyncAppContext,
 276    ) -> Option<Task<Result<()>>> {
 277        None
 278    }
 279
 280    fn will_start_server(
 281        &self,
 282        _: &Arc<dyn LspAdapterDelegate>,
 283        _: &mut AsyncAppContext,
 284    ) -> Option<Task<Result<()>>> {
 285        None
 286    }
 287
 288    async fn fetch_server_binary(
 289        &self,
 290        version: Box<dyn 'static + Send + Any>,
 291        container_dir: PathBuf,
 292        delegate: &dyn LspAdapterDelegate,
 293    ) -> Result<LanguageServerBinary>;
 294
 295    async fn cached_server_binary(
 296        &self,
 297        container_dir: PathBuf,
 298        delegate: &dyn LspAdapterDelegate,
 299    ) -> Option<LanguageServerBinary>;
 300
 301    /// Returns true if a language server can be reinstalled.
 302    /// If language server initialization fails, a reinstallation will be attempted unless the value returned from this method is false.
 303    /// Implementations that rely on software already installed on user's system
 304    /// should have [`can_be_reinstalled`] return false.
 305    fn can_be_reinstalled(&self) -> bool {
 306        true
 307    }
 308
 309    async fn installation_test_binary(
 310        &self,
 311        container_dir: PathBuf,
 312    ) -> Option<LanguageServerBinary>;
 313
 314    fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
 315
 316    /// A callback called for each [`lsp_types::CompletionItem`] obtained from LSP server.
 317    /// Some LspAdapter implementations might want to modify the obtained item to
 318    /// change how it's displayed.
 319    async fn process_completion(&self, _: &mut lsp::CompletionItem) {}
 320
 321    async fn label_for_completion(
 322        &self,
 323        _: &lsp::CompletionItem,
 324        _: &Arc<Language>,
 325    ) -> Option<CodeLabel> {
 326        None
 327    }
 328
 329    async fn label_for_symbol(
 330        &self,
 331        _: &str,
 332        _: lsp::SymbolKind,
 333        _: &Arc<Language>,
 334    ) -> Option<CodeLabel> {
 335        None
 336    }
 337
 338    /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp_types::InitializeParams`]
 339    fn initialization_options(&self) -> Option<Value> {
 340        None
 341    }
 342
 343    fn workspace_configuration(&self, _: &Path, _: &mut AppContext) -> Value {
 344        serde_json::json!({})
 345    }
 346
 347    /// Returns a list of code actions supported by a given LspAdapter
 348    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 349        Some(vec![
 350            CodeActionKind::EMPTY,
 351            CodeActionKind::QUICKFIX,
 352            CodeActionKind::REFACTOR,
 353            CodeActionKind::REFACTOR_EXTRACT,
 354            CodeActionKind::SOURCE,
 355        ])
 356    }
 357
 358    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
 359        Default::default()
 360    }
 361
 362    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
 363        None
 364    }
 365
 366    fn language_ids(&self) -> HashMap<String, String> {
 367        Default::default()
 368    }
 369
 370    fn prettier_plugins(&self) -> &[&'static str] {
 371        &[]
 372    }
 373}
 374
 375#[derive(Clone, Debug, PartialEq, Eq)]
 376pub struct CodeLabel {
 377    /// The text to display.
 378    pub text: String,
 379    /// Syntax highlighting runs.
 380    pub runs: Vec<(Range<usize>, HighlightId)>,
 381    /// The portion of the text that should be used in fuzzy filtering.
 382    pub filter_range: Range<usize>,
 383}
 384
 385#[derive(Clone, Deserialize)]
 386pub struct LanguageConfig {
 387    /// Human-readable name of the language.
 388    pub name: Arc<str>,
 389    // The name of the grammar in a WASM bundle (experimental).
 390    pub grammar_name: Option<Arc<str>>,
 391    /// 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`.
 392    pub path_suffixes: Vec<String>,
 393    /// List of bracket types in a language.
 394    pub brackets: BracketPairConfig,
 395    /// A regex pattern that determines whether the language should be assigned to a file or not.
 396    #[serde(default, deserialize_with = "deserialize_regex")]
 397    pub first_line_pattern: Option<Regex>,
 398    /// If set to true, auto indentation uses last non empty line to determine
 399    /// the indentation level for a new line.
 400    #[serde(default = "auto_indent_using_last_non_empty_line_default")]
 401    pub auto_indent_using_last_non_empty_line: bool,
 402    /// A regex that is used to determine whether the indentation level should be
 403    /// increased in the following line.
 404    #[serde(default, deserialize_with = "deserialize_regex")]
 405    pub increase_indent_pattern: Option<Regex>,
 406    /// A regex that is used to determine whether the indentation level should be
 407    /// decreased in the following line.
 408    #[serde(default, deserialize_with = "deserialize_regex")]
 409    pub decrease_indent_pattern: Option<Regex>,
 410    /// A list of characters that trigger the automatic insertion of a closing
 411    /// bracket when they immediately precede the point where an opening
 412    /// bracket is inserted.
 413    #[serde(default)]
 414    pub autoclose_before: String,
 415    /// A placeholder used internally by Semantic Index.
 416    #[serde(default)]
 417    pub collapsed_placeholder: String,
 418    /// A line comment string that is inserted in e.g. `toggle comments` action.
 419    #[serde(default)]
 420    pub line_comment: Option<Arc<str>>,
 421    /// Starting and closing characters of a block comment.
 422    #[serde(default)]
 423    pub block_comment: Option<(Arc<str>, Arc<str>)>,
 424    /// A list of language servers that are allowed to run on subranges of a given language.
 425    #[serde(default)]
 426    pub scope_opt_in_language_servers: Vec<String>,
 427    #[serde(default)]
 428    pub overrides: HashMap<String, LanguageConfigOverride>,
 429    /// A list of characters that Zed should treat as word characters for the
 430    /// purpose of features that operate on word boundaries, like 'move to next word end'
 431    /// or a whole-word search in buffer search.
 432    #[serde(default)]
 433    pub word_characters: HashSet<char>,
 434    /// The name of a Prettier parser that should be used for this language.
 435    #[serde(default)]
 436    pub prettier_parser_name: Option<String>,
 437}
 438
 439/// Tree-sitter language queries for a given language.
 440#[derive(Debug, Default)]
 441pub struct LanguageQueries {
 442    pub highlights: Option<Cow<'static, str>>,
 443    pub brackets: Option<Cow<'static, str>>,
 444    pub indents: Option<Cow<'static, str>>,
 445    pub outline: Option<Cow<'static, str>>,
 446    pub embedding: Option<Cow<'static, str>>,
 447    pub injections: Option<Cow<'static, str>>,
 448    pub overrides: Option<Cow<'static, str>>,
 449}
 450
 451/// Represents a language for the given range. Some languages (e.g. HTML)
 452/// interleave several languages together, thus a single buffer might actually contain
 453/// several nested scopes.
 454#[derive(Clone, Debug)]
 455pub struct LanguageScope {
 456    language: Arc<Language>,
 457    override_id: Option<u32>,
 458}
 459
 460#[derive(Clone, Deserialize, Default, Debug)]
 461pub struct LanguageConfigOverride {
 462    #[serde(default)]
 463    pub line_comment: Override<Arc<str>>,
 464    #[serde(default)]
 465    pub block_comment: Override<(Arc<str>, Arc<str>)>,
 466    #[serde(skip_deserializing)]
 467    pub disabled_bracket_ixs: Vec<u16>,
 468    #[serde(default)]
 469    pub word_characters: Override<HashSet<char>>,
 470    #[serde(default)]
 471    pub opt_into_language_servers: Vec<String>,
 472}
 473
 474#[derive(Clone, Deserialize, Debug)]
 475#[serde(untagged)]
 476pub enum Override<T> {
 477    Remove { remove: bool },
 478    Set(T),
 479}
 480
 481impl<T> Default for Override<T> {
 482    fn default() -> Self {
 483        Override::Remove { remove: false }
 484    }
 485}
 486
 487impl<T> Override<T> {
 488    fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
 489        match this {
 490            Some(Self::Set(value)) => Some(value),
 491            Some(Self::Remove { remove: true }) => None,
 492            Some(Self::Remove { remove: false }) | None => original,
 493        }
 494    }
 495}
 496
 497impl Default for LanguageConfig {
 498    fn default() -> Self {
 499        Self {
 500            name: "".into(),
 501            grammar_name: None,
 502            path_suffixes: Default::default(),
 503            brackets: Default::default(),
 504            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
 505            first_line_pattern: Default::default(),
 506            increase_indent_pattern: Default::default(),
 507            decrease_indent_pattern: Default::default(),
 508            autoclose_before: Default::default(),
 509            line_comment: Default::default(),
 510            block_comment: Default::default(),
 511            scope_opt_in_language_servers: Default::default(),
 512            overrides: Default::default(),
 513            word_characters: Default::default(),
 514            prettier_parser_name: None,
 515            collapsed_placeholder: Default::default(),
 516        }
 517    }
 518}
 519
 520fn auto_indent_using_last_non_empty_line_default() -> bool {
 521    true
 522}
 523
 524fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
 525    let source = Option::<String>::deserialize(d)?;
 526    if let Some(source) = source {
 527        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
 528    } else {
 529        Ok(None)
 530    }
 531}
 532
 533#[doc(hidden)]
 534#[cfg(any(test, feature = "test-support"))]
 535pub struct FakeLspAdapter {
 536    pub name: &'static str,
 537    pub initialization_options: Option<Value>,
 538    pub capabilities: lsp::ServerCapabilities,
 539    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
 540    pub disk_based_diagnostics_progress_token: Option<String>,
 541    pub disk_based_diagnostics_sources: Vec<String>,
 542    pub prettier_plugins: Vec<&'static str>,
 543}
 544
 545/// Configuration of handling bracket pairs for a given language.
 546///
 547/// This struct includes settings for defining which pairs of characters are considered brackets and
 548/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
 549#[derive(Clone, Debug, Default)]
 550pub struct BracketPairConfig {
 551    /// A list of character pairs that should be treated as brackets in the context of a given language.
 552    pub pairs: Vec<BracketPair>,
 553    /// A list of tree-sitter scopes for which a given bracket should not be active.
 554    /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
 555    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
 556}
 557
 558impl<'de> Deserialize<'de> for BracketPairConfig {
 559    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 560    where
 561        D: Deserializer<'de>,
 562    {
 563        #[derive(Deserialize)]
 564        pub struct Entry {
 565            #[serde(flatten)]
 566            pub bracket_pair: BracketPair,
 567            #[serde(default)]
 568            pub not_in: Vec<String>,
 569        }
 570
 571        let result = Vec::<Entry>::deserialize(deserializer)?;
 572        let mut brackets = Vec::with_capacity(result.len());
 573        let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
 574        for entry in result {
 575            brackets.push(entry.bracket_pair);
 576            disabled_scopes_by_bracket_ix.push(entry.not_in);
 577        }
 578
 579        Ok(BracketPairConfig {
 580            pairs: brackets,
 581            disabled_scopes_by_bracket_ix,
 582        })
 583    }
 584}
 585
 586/// Describes a single bracket pair and how an editor should react to e.g. inserting
 587/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
 588#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
 589pub struct BracketPair {
 590    /// Starting substring for a bracket.
 591    pub start: String,
 592    /// Ending substring for a bracket.
 593    pub end: String,
 594    /// True if `end` should be automatically inserted right after `start` characters.
 595    pub close: bool,
 596    /// True if an extra newline should be inserted while the cursor is in the middle
 597    /// of that bracket pair.
 598    pub newline: bool,
 599}
 600
 601pub struct Language {
 602    pub(crate) config: LanguageConfig,
 603    pub(crate) grammar: Option<Arc<Grammar>>,
 604    pub(crate) adapters: Vec<Arc<CachedLspAdapter>>,
 605
 606    #[cfg(any(test, feature = "test-support"))]
 607    fake_adapter: Option<(
 608        mpsc::UnboundedSender<lsp::FakeLanguageServer>,
 609        Arc<FakeLspAdapter>,
 610    )>,
 611}
 612
 613pub struct Grammar {
 614    id: usize,
 615    pub ts_language: tree_sitter::Language,
 616    pub(crate) error_query: Query,
 617    pub(crate) highlights_query: Option<Query>,
 618    pub(crate) brackets_config: Option<BracketConfig>,
 619    pub(crate) indents_config: Option<IndentConfig>,
 620    pub outline_config: Option<OutlineConfig>,
 621    pub embedding_config: Option<EmbeddingConfig>,
 622    pub(crate) injection_config: Option<InjectionConfig>,
 623    pub(crate) override_config: Option<OverrideConfig>,
 624    pub(crate) highlight_map: Mutex<HighlightMap>,
 625}
 626
 627struct IndentConfig {
 628    query: Query,
 629    indent_capture_ix: u32,
 630    start_capture_ix: Option<u32>,
 631    end_capture_ix: Option<u32>,
 632    outdent_capture_ix: Option<u32>,
 633}
 634
 635pub struct OutlineConfig {
 636    pub query: Query,
 637    pub item_capture_ix: u32,
 638    pub name_capture_ix: u32,
 639    pub context_capture_ix: Option<u32>,
 640    pub extra_context_capture_ix: Option<u32>,
 641}
 642
 643#[derive(Debug)]
 644pub struct EmbeddingConfig {
 645    pub query: Query,
 646    pub item_capture_ix: u32,
 647    pub name_capture_ix: Option<u32>,
 648    pub context_capture_ix: Option<u32>,
 649    pub collapse_capture_ix: Option<u32>,
 650    pub keep_capture_ix: Option<u32>,
 651}
 652
 653struct InjectionConfig {
 654    query: Query,
 655    content_capture_ix: u32,
 656    language_capture_ix: Option<u32>,
 657    patterns: Vec<InjectionPatternConfig>,
 658}
 659
 660struct OverrideConfig {
 661    query: Query,
 662    values: HashMap<u32, (String, LanguageConfigOverride)>,
 663}
 664
 665#[derive(Default, Clone)]
 666struct InjectionPatternConfig {
 667    language: Option<Box<str>>,
 668    combined: bool,
 669}
 670
 671struct BracketConfig {
 672    query: Query,
 673    open_capture_ix: u32,
 674    close_capture_ix: u32,
 675}
 676
 677#[derive(Clone)]
 678pub enum LanguageServerBinaryStatus {
 679    CheckingForUpdate,
 680    Downloading,
 681    Downloaded,
 682    Cached,
 683    Failed { error: String },
 684}
 685
 686type AvailableLanguageId = usize;
 687
 688#[derive(Clone)]
 689struct AvailableLanguage {
 690    id: AvailableLanguageId,
 691    config: LanguageConfig,
 692    grammar: AvailableGrammar,
 693    lsp_adapters: Vec<Arc<dyn LspAdapter>>,
 694    loaded: bool,
 695}
 696
 697#[derive(Clone)]
 698enum AvailableGrammar {
 699    Native {
 700        grammar: tree_sitter::Language,
 701        asset_dir: &'static str,
 702        get_queries: fn(&str) -> LanguageQueries,
 703    },
 704    Wasm {
 705        _grammar_name: Arc<str>,
 706        _path: Arc<Path>,
 707    },
 708}
 709
 710pub struct LanguageRegistry {
 711    state: RwLock<LanguageRegistryState>,
 712    language_server_download_dir: Option<Arc<Path>>,
 713    login_shell_env_loaded: Shared<Task<()>>,
 714    #[allow(clippy::type_complexity)]
 715    lsp_binary_paths: Mutex<
 716        HashMap<LanguageServerName, Shared<Task<Result<LanguageServerBinary, Arc<anyhow::Error>>>>>,
 717    >,
 718    executor: Option<BackgroundExecutor>,
 719    lsp_binary_status_tx: LspBinaryStatusSender,
 720}
 721
 722struct LanguageRegistryState {
 723    next_language_server_id: usize,
 724    languages: Vec<Arc<Language>>,
 725    available_languages: Vec<AvailableLanguage>,
 726    next_available_language_id: AvailableLanguageId,
 727    loading_languages: HashMap<AvailableLanguageId, Vec<oneshot::Sender<Result<Arc<Language>>>>>,
 728    subscription: (watch::Sender<()>, watch::Receiver<()>),
 729    theme: Option<Arc<Theme>>,
 730    version: usize,
 731    reload_count: usize,
 732}
 733
 734pub struct PendingLanguageServer {
 735    pub server_id: LanguageServerId,
 736    pub task: Task<Result<lsp::LanguageServer>>,
 737    pub container_dir: Option<Arc<Path>>,
 738}
 739
 740impl LanguageRegistry {
 741    pub fn new(login_shell_env_loaded: Task<()>) -> Self {
 742        Self {
 743            state: RwLock::new(LanguageRegistryState {
 744                next_language_server_id: 0,
 745                languages: vec![PLAIN_TEXT.clone()],
 746                available_languages: Default::default(),
 747                next_available_language_id: 0,
 748                loading_languages: Default::default(),
 749                subscription: watch::channel(),
 750                theme: Default::default(),
 751                version: 0,
 752                reload_count: 0,
 753            }),
 754            language_server_download_dir: None,
 755            login_shell_env_loaded: login_shell_env_loaded.shared(),
 756            lsp_binary_paths: Default::default(),
 757            executor: None,
 758            lsp_binary_status_tx: Default::default(),
 759        }
 760    }
 761
 762    #[cfg(any(test, feature = "test-support"))]
 763    pub fn test() -> Self {
 764        Self::new(Task::ready(()))
 765    }
 766
 767    pub fn set_executor(&mut self, executor: BackgroundExecutor) {
 768        self.executor = Some(executor);
 769    }
 770
 771    /// Clear out all of the loaded languages and reload them from scratch.
 772    ///
 773    /// This is useful in development, when queries have changed.
 774    #[cfg(debug_assertions)]
 775    pub fn reload(&self) {
 776        self.state.write().reload();
 777    }
 778
 779    pub fn register(
 780        &self,
 781        asset_dir: &'static str,
 782        config: LanguageConfig,
 783        grammar: tree_sitter::Language,
 784        lsp_adapters: Vec<Arc<dyn LspAdapter>>,
 785        get_queries: fn(&str) -> LanguageQueries,
 786    ) {
 787        let state = &mut *self.state.write();
 788        state.available_languages.push(AvailableLanguage {
 789            id: post_inc(&mut state.next_available_language_id),
 790            config,
 791            grammar: AvailableGrammar::Native {
 792                grammar,
 793                get_queries,
 794                asset_dir,
 795            },
 796            lsp_adapters,
 797            loaded: false,
 798        });
 799    }
 800
 801    pub fn register_wasm(&self, path: Arc<Path>, grammar_name: Arc<str>, config: LanguageConfig) {
 802        let state = &mut *self.state.write();
 803        state.available_languages.push(AvailableLanguage {
 804            id: post_inc(&mut state.next_available_language_id),
 805            config,
 806            grammar: AvailableGrammar::Wasm {
 807                _grammar_name: grammar_name,
 808                _path: path,
 809            },
 810            lsp_adapters: Vec::new(),
 811            loaded: false,
 812        });
 813    }
 814
 815    pub fn language_names(&self) -> Vec<String> {
 816        let state = self.state.read();
 817        let mut result = state
 818            .available_languages
 819            .iter()
 820            .filter_map(|l| l.loaded.not().then_some(l.config.name.to_string()))
 821            .chain(state.languages.iter().map(|l| l.config.name.to_string()))
 822            .collect::<Vec<_>>();
 823        result.sort_unstable_by_key(|language_name| language_name.to_lowercase());
 824        result
 825    }
 826
 827    pub fn add(&self, language: Arc<Language>) {
 828        self.state.write().add(language);
 829    }
 830
 831    pub fn subscribe(&self) -> watch::Receiver<()> {
 832        self.state.read().subscription.1.clone()
 833    }
 834
 835    /// The number of times that the registry has been changed,
 836    /// by adding languages or reloading.
 837    pub fn version(&self) -> usize {
 838        self.state.read().version
 839    }
 840
 841    /// The number of times that the registry has been reloaded.
 842    pub fn reload_count(&self) -> usize {
 843        self.state.read().reload_count
 844    }
 845
 846    pub fn set_theme(&self, theme: Arc<Theme>) {
 847        let mut state = self.state.write();
 848        state.theme = Some(theme.clone());
 849        for language in &state.languages {
 850            language.set_theme(theme.syntax());
 851        }
 852    }
 853
 854    pub fn set_language_server_download_dir(&mut self, path: impl Into<Arc<Path>>) {
 855        self.language_server_download_dir = Some(path.into());
 856    }
 857
 858    pub fn language_for_name(
 859        self: &Arc<Self>,
 860        name: &str,
 861    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 862        let name = UniCase::new(name);
 863        self.get_or_load_language(|config| UniCase::new(config.name.as_ref()) == name)
 864    }
 865
 866    pub fn language_for_name_or_extension(
 867        self: &Arc<Self>,
 868        string: &str,
 869    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 870        let string = UniCase::new(string);
 871        self.get_or_load_language(|config| {
 872            UniCase::new(config.name.as_ref()) == string
 873                || config
 874                    .path_suffixes
 875                    .iter()
 876                    .any(|suffix| UniCase::new(suffix) == string)
 877        })
 878    }
 879
 880    pub fn language_for_file(
 881        self: &Arc<Self>,
 882        path: impl AsRef<Path>,
 883        content: Option<&Rope>,
 884    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 885        let path = path.as_ref();
 886        let filename = path.file_name().and_then(|name| name.to_str());
 887        let extension = path.extension_or_hidden_file_name();
 888        let path_suffixes = [extension, filename];
 889        self.get_or_load_language(|config| {
 890            let path_matches = config
 891                .path_suffixes
 892                .iter()
 893                .any(|suffix| path_suffixes.contains(&Some(suffix.as_str())));
 894            let content_matches = content.zip(config.first_line_pattern.as_ref()).map_or(
 895                false,
 896                |(content, pattern)| {
 897                    let end = content.clip_point(Point::new(0, 256), Bias::Left);
 898                    let end = content.point_to_offset(end);
 899                    let text = content.chunks_in_range(0..end).collect::<String>();
 900                    pattern.is_match(&text)
 901                },
 902            );
 903            path_matches || content_matches
 904        })
 905    }
 906
 907    fn get_or_load_language(
 908        self: &Arc<Self>,
 909        callback: impl Fn(&LanguageConfig) -> bool,
 910    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 911        let (tx, rx) = oneshot::channel();
 912
 913        let mut state = self.state.write();
 914        if let Some(language) = state
 915            .languages
 916            .iter()
 917            .find(|language| callback(&language.config))
 918        {
 919            let _ = tx.send(Ok(language.clone()));
 920        } else if let Some(executor) = self.executor.clone() {
 921            if let Some(language) = state
 922                .available_languages
 923                .iter()
 924                .find(|l| !l.loaded && callback(&l.config))
 925                .cloned()
 926            {
 927                let txs = state
 928                    .loading_languages
 929                    .entry(language.id)
 930                    .or_insert_with(|| {
 931                        let this = self.clone();
 932                        executor
 933                            .spawn(async move {
 934                                let id = language.id;
 935                                let name = language.config.name.clone();
 936                                let language = async {
 937                                    let (grammar, queries) = match language.grammar {
 938                                        AvailableGrammar::Native {
 939                                            grammar,
 940                                            asset_dir,
 941                                            get_queries,
 942                                        } => (grammar, (get_queries)(asset_dir)),
 943                                        AvailableGrammar::Wasm { .. } => {
 944                                            Err(anyhow!("not supported"))?
 945                                        }
 946                                    };
 947                                    Language::new(language.config, Some(grammar))
 948                                        .with_lsp_adapters(language.lsp_adapters)
 949                                        .await
 950                                        .with_queries(queries)
 951                                }
 952                                .await;
 953
 954                                match language {
 955                                    Ok(language) => {
 956                                        let language = Arc::new(language);
 957                                        let mut state = this.state.write();
 958
 959                                        state.add(language.clone());
 960                                        state.mark_language_loaded(id);
 961                                        if let Some(mut txs) = state.loading_languages.remove(&id) {
 962                                            for tx in txs.drain(..) {
 963                                                let _ = tx.send(Ok(language.clone()));
 964                                            }
 965                                        }
 966                                    }
 967                                    Err(e) => {
 968                                        log::error!("failed to load language {name}:\n{:?}", e);
 969                                        let mut state = this.state.write();
 970                                        state.mark_language_loaded(id);
 971                                        if let Some(mut txs) = state.loading_languages.remove(&id) {
 972                                            for tx in txs.drain(..) {
 973                                                let _ = tx.send(Err(anyhow!(
 974                                                    "failed to load language {}: {}",
 975                                                    name,
 976                                                    e
 977                                                )));
 978                                            }
 979                                        }
 980                                    }
 981                                };
 982                            })
 983                            .detach();
 984
 985                        Vec::new()
 986                    });
 987                txs.push(tx);
 988            } else {
 989                let _ = tx.send(Err(anyhow!("language not found")));
 990            }
 991        } else {
 992            let _ = tx.send(Err(anyhow!("executor does not exist")));
 993        }
 994
 995        rx.unwrap()
 996    }
 997
 998    pub fn to_vec(&self) -> Vec<Arc<Language>> {
 999        self.state.read().languages.iter().cloned().collect()
1000    }
1001
1002    pub fn create_pending_language_server(
1003        self: &Arc<Self>,
1004        stderr_capture: Arc<Mutex<Option<String>>>,
1005        language: Arc<Language>,
1006        adapter: Arc<CachedLspAdapter>,
1007        root_path: Arc<Path>,
1008        delegate: Arc<dyn LspAdapterDelegate>,
1009        cx: &mut AppContext,
1010    ) -> Option<PendingLanguageServer> {
1011        let server_id = self.state.write().next_language_server_id();
1012        log::info!(
1013            "starting language server {:?}, path: {root_path:?}, id: {server_id}",
1014            adapter.name.0
1015        );
1016
1017        #[cfg(any(test, feature = "test-support"))]
1018        if language.fake_adapter.is_some() {
1019            let task = cx.spawn(|cx| async move {
1020                let (servers_tx, fake_adapter) = language.fake_adapter.as_ref().unwrap();
1021                let (server, mut fake_server) = lsp::FakeLanguageServer::new(
1022                    fake_adapter.name.to_string(),
1023                    fake_adapter.capabilities.clone(),
1024                    cx.clone(),
1025                );
1026
1027                if let Some(initializer) = &fake_adapter.initializer {
1028                    initializer(&mut fake_server);
1029                }
1030
1031                let servers_tx = servers_tx.clone();
1032                cx.background_executor()
1033                    .spawn(async move {
1034                        if fake_server
1035                            .try_receive_notification::<lsp::notification::Initialized>()
1036                            .await
1037                            .is_some()
1038                        {
1039                            servers_tx.unbounded_send(fake_server).ok();
1040                        }
1041                    })
1042                    .detach();
1043
1044                Ok(server)
1045            });
1046
1047            return Some(PendingLanguageServer {
1048                server_id,
1049                task,
1050                container_dir: None,
1051            });
1052        }
1053
1054        let download_dir = self
1055            .language_server_download_dir
1056            .clone()
1057            .ok_or_else(|| anyhow!("language server download directory has not been assigned before starting server"))
1058            .log_err()?;
1059        let this = self.clone();
1060        let language = language.clone();
1061        let container_dir: Arc<Path> = Arc::from(download_dir.join(adapter.name.0.as_ref()));
1062        let root_path = root_path.clone();
1063        let adapter = adapter.clone();
1064        let login_shell_env_loaded = self.login_shell_env_loaded.clone();
1065        let lsp_binary_statuses = self.lsp_binary_status_tx.clone();
1066
1067        let task = {
1068            let container_dir = container_dir.clone();
1069            cx.spawn(move |mut cx| async move {
1070                login_shell_env_loaded.await;
1071
1072                let entry = this
1073                    .lsp_binary_paths
1074                    .lock()
1075                    .entry(adapter.name.clone())
1076                    .or_insert_with(|| {
1077                        let adapter = adapter.clone();
1078                        let language = language.clone();
1079                        let delegate = delegate.clone();
1080                        cx.spawn(|cx| {
1081                            get_binary(
1082                                adapter,
1083                                language,
1084                                delegate,
1085                                container_dir,
1086                                lsp_binary_statuses,
1087                                cx,
1088                            )
1089                            .map_err(Arc::new)
1090                        })
1091                        .shared()
1092                    })
1093                    .clone();
1094
1095                let binary = match entry.await {
1096                    Ok(binary) => binary,
1097                    Err(err) => anyhow::bail!("{err}"),
1098                };
1099
1100                if let Some(task) = adapter.will_start_server(&delegate, &mut cx) {
1101                    task.await?;
1102                }
1103
1104                lsp::LanguageServer::new(
1105                    stderr_capture,
1106                    server_id,
1107                    binary,
1108                    &root_path,
1109                    adapter.code_action_kinds(),
1110                    cx,
1111                )
1112            })
1113        };
1114
1115        Some(PendingLanguageServer {
1116            server_id,
1117            task,
1118            container_dir: Some(container_dir),
1119        })
1120    }
1121
1122    pub fn language_server_binary_statuses(
1123        &self,
1124    ) -> mpsc::UnboundedReceiver<(Arc<Language>, LanguageServerBinaryStatus)> {
1125        self.lsp_binary_status_tx.subscribe()
1126    }
1127
1128    pub fn delete_server_container(
1129        &self,
1130        adapter: Arc<CachedLspAdapter>,
1131        cx: &mut AppContext,
1132    ) -> Task<()> {
1133        log::info!("deleting server container");
1134
1135        let mut lock = self.lsp_binary_paths.lock();
1136        lock.remove(&adapter.name);
1137
1138        let download_dir = self
1139            .language_server_download_dir
1140            .clone()
1141            .expect("language server download directory has not been assigned before deleting server container");
1142
1143        cx.spawn(|_| async move {
1144            let container_dir = download_dir.join(adapter.name.0.as_ref());
1145            smol::fs::remove_dir_all(container_dir)
1146                .await
1147                .context("server container removal")
1148                .log_err();
1149        })
1150    }
1151
1152    pub fn next_language_server_id(&self) -> LanguageServerId {
1153        self.state.write().next_language_server_id()
1154    }
1155}
1156
1157impl LanguageRegistryState {
1158    fn next_language_server_id(&mut self) -> LanguageServerId {
1159        LanguageServerId(post_inc(&mut self.next_language_server_id))
1160    }
1161
1162    fn add(&mut self, language: Arc<Language>) {
1163        if let Some(theme) = self.theme.as_ref() {
1164            language.set_theme(theme.syntax());
1165        }
1166        self.languages.push(language);
1167        self.version += 1;
1168        *self.subscription.0.borrow_mut() = ();
1169    }
1170
1171    #[cfg(debug_assertions)]
1172    fn reload(&mut self) {
1173        self.languages.clear();
1174        self.version += 1;
1175        self.reload_count += 1;
1176        for language in &mut self.available_languages {
1177            language.loaded = false;
1178        }
1179        *self.subscription.0.borrow_mut() = ();
1180    }
1181
1182    /// Mark the given language a having been loaded, so that the
1183    /// language registry won't try to load it again.
1184    fn mark_language_loaded(&mut self, id: AvailableLanguageId) {
1185        for language in &mut self.available_languages {
1186            if language.id == id {
1187                language.loaded = true;
1188                break;
1189            }
1190        }
1191    }
1192}
1193
1194#[cfg(any(test, feature = "test-support"))]
1195impl Default for LanguageRegistry {
1196    fn default() -> Self {
1197        Self::test()
1198    }
1199}
1200
1201async fn get_binary(
1202    adapter: Arc<CachedLspAdapter>,
1203    language: Arc<Language>,
1204    delegate: Arc<dyn LspAdapterDelegate>,
1205    container_dir: Arc<Path>,
1206    statuses: LspBinaryStatusSender,
1207    mut cx: AsyncAppContext,
1208) -> Result<LanguageServerBinary> {
1209    if !container_dir.exists() {
1210        smol::fs::create_dir_all(&container_dir)
1211            .await
1212            .context("failed to create container directory")?;
1213    }
1214
1215    if let Some(task) = adapter.will_fetch_server(&delegate, &mut cx) {
1216        task.await?;
1217    }
1218
1219    let binary = fetch_latest_binary(
1220        adapter.clone(),
1221        language.clone(),
1222        delegate.as_ref(),
1223        &container_dir,
1224        statuses.clone(),
1225    )
1226    .await;
1227
1228    if let Err(error) = binary.as_ref() {
1229        if let Some(binary) = adapter
1230            .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
1231            .await
1232        {
1233            statuses.send(language.clone(), LanguageServerBinaryStatus::Cached);
1234            return Ok(binary);
1235        } else {
1236            statuses.send(
1237                language.clone(),
1238                LanguageServerBinaryStatus::Failed {
1239                    error: format!("{:?}", error),
1240                },
1241            );
1242        }
1243    }
1244
1245    binary
1246}
1247
1248async fn fetch_latest_binary(
1249    adapter: Arc<CachedLspAdapter>,
1250    language: Arc<Language>,
1251    delegate: &dyn LspAdapterDelegate,
1252    container_dir: &Path,
1253    lsp_binary_statuses_tx: LspBinaryStatusSender,
1254) -> Result<LanguageServerBinary> {
1255    let container_dir: Arc<Path> = container_dir.into();
1256    lsp_binary_statuses_tx.send(
1257        language.clone(),
1258        LanguageServerBinaryStatus::CheckingForUpdate,
1259    );
1260
1261    let version_info = adapter.fetch_latest_server_version(delegate).await?;
1262    lsp_binary_statuses_tx.send(language.clone(), LanguageServerBinaryStatus::Downloading);
1263
1264    let binary = adapter
1265        .fetch_server_binary(version_info, container_dir.to_path_buf(), delegate)
1266        .await?;
1267    lsp_binary_statuses_tx.send(language.clone(), LanguageServerBinaryStatus::Downloaded);
1268
1269    Ok(binary)
1270}
1271
1272impl Language {
1273    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1274        Self {
1275            config,
1276            grammar: ts_language.map(|ts_language| {
1277                Arc::new(Grammar {
1278                    id: NEXT_GRAMMAR_ID.fetch_add(1, SeqCst),
1279                    highlights_query: None,
1280                    brackets_config: None,
1281                    outline_config: None,
1282                    embedding_config: None,
1283                    indents_config: None,
1284                    injection_config: None,
1285                    override_config: None,
1286                    error_query: Query::new(&ts_language, "(ERROR) @error").unwrap(),
1287                    ts_language,
1288                    highlight_map: Default::default(),
1289                })
1290            }),
1291            adapters: Vec::new(),
1292
1293            #[cfg(any(test, feature = "test-support"))]
1294            fake_adapter: None,
1295        }
1296    }
1297
1298    pub fn lsp_adapters(&self) -> &[Arc<CachedLspAdapter>] {
1299        &self.adapters
1300    }
1301
1302    pub fn id(&self) -> Option<usize> {
1303        self.grammar.as_ref().map(|g| g.id)
1304    }
1305
1306    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1307        if let Some(query) = queries.highlights {
1308            self = self
1309                .with_highlights_query(query.as_ref())
1310                .context("Error loading highlights query")?;
1311        }
1312        if let Some(query) = queries.brackets {
1313            self = self
1314                .with_brackets_query(query.as_ref())
1315                .context("Error loading brackets query")?;
1316        }
1317        if let Some(query) = queries.indents {
1318            self = self
1319                .with_indents_query(query.as_ref())
1320                .context("Error loading indents query")?;
1321        }
1322        if let Some(query) = queries.outline {
1323            self = self
1324                .with_outline_query(query.as_ref())
1325                .context("Error loading outline query")?;
1326        }
1327        if let Some(query) = queries.embedding {
1328            self = self
1329                .with_embedding_query(query.as_ref())
1330                .context("Error loading embedding query")?;
1331        }
1332        if let Some(query) = queries.injections {
1333            self = self
1334                .with_injection_query(query.as_ref())
1335                .context("Error loading injection query")?;
1336        }
1337        if let Some(query) = queries.overrides {
1338            self = self
1339                .with_override_query(query.as_ref())
1340                .context("Error loading override query")?;
1341        }
1342        Ok(self)
1343    }
1344
1345    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1346        let grammar = self.grammar_mut();
1347        grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1348        Ok(self)
1349    }
1350
1351    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1352        let grammar = self.grammar_mut();
1353        let query = Query::new(&grammar.ts_language, source)?;
1354        let mut item_capture_ix = None;
1355        let mut name_capture_ix = None;
1356        let mut context_capture_ix = None;
1357        let mut extra_context_capture_ix = None;
1358        get_capture_indices(
1359            &query,
1360            &mut [
1361                ("item", &mut item_capture_ix),
1362                ("name", &mut name_capture_ix),
1363                ("context", &mut context_capture_ix),
1364                ("context.extra", &mut extra_context_capture_ix),
1365            ],
1366        );
1367        if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1368            grammar.outline_config = Some(OutlineConfig {
1369                query,
1370                item_capture_ix,
1371                name_capture_ix,
1372                context_capture_ix,
1373                extra_context_capture_ix,
1374            });
1375        }
1376        Ok(self)
1377    }
1378
1379    pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1380        let grammar = self.grammar_mut();
1381        let query = Query::new(&grammar.ts_language, source)?;
1382        let mut item_capture_ix = None;
1383        let mut name_capture_ix = None;
1384        let mut context_capture_ix = None;
1385        let mut collapse_capture_ix = None;
1386        let mut keep_capture_ix = None;
1387        get_capture_indices(
1388            &query,
1389            &mut [
1390                ("item", &mut item_capture_ix),
1391                ("name", &mut name_capture_ix),
1392                ("context", &mut context_capture_ix),
1393                ("keep", &mut keep_capture_ix),
1394                ("collapse", &mut collapse_capture_ix),
1395            ],
1396        );
1397        if let Some(item_capture_ix) = item_capture_ix {
1398            grammar.embedding_config = Some(EmbeddingConfig {
1399                query,
1400                item_capture_ix,
1401                name_capture_ix,
1402                context_capture_ix,
1403                collapse_capture_ix,
1404                keep_capture_ix,
1405            });
1406        }
1407        Ok(self)
1408    }
1409
1410    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1411        let grammar = self.grammar_mut();
1412        let query = Query::new(&grammar.ts_language, source)?;
1413        let mut open_capture_ix = None;
1414        let mut close_capture_ix = None;
1415        get_capture_indices(
1416            &query,
1417            &mut [
1418                ("open", &mut open_capture_ix),
1419                ("close", &mut close_capture_ix),
1420            ],
1421        );
1422        if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1423            grammar.brackets_config = Some(BracketConfig {
1424                query,
1425                open_capture_ix,
1426                close_capture_ix,
1427            });
1428        }
1429        Ok(self)
1430    }
1431
1432    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1433        let grammar = self.grammar_mut();
1434        let query = Query::new(&grammar.ts_language, source)?;
1435        let mut indent_capture_ix = None;
1436        let mut start_capture_ix = None;
1437        let mut end_capture_ix = None;
1438        let mut outdent_capture_ix = None;
1439        get_capture_indices(
1440            &query,
1441            &mut [
1442                ("indent", &mut indent_capture_ix),
1443                ("start", &mut start_capture_ix),
1444                ("end", &mut end_capture_ix),
1445                ("outdent", &mut outdent_capture_ix),
1446            ],
1447        );
1448        if let Some(indent_capture_ix) = indent_capture_ix {
1449            grammar.indents_config = Some(IndentConfig {
1450                query,
1451                indent_capture_ix,
1452                start_capture_ix,
1453                end_capture_ix,
1454                outdent_capture_ix,
1455            });
1456        }
1457        Ok(self)
1458    }
1459
1460    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1461        let grammar = self.grammar_mut();
1462        let query = Query::new(&grammar.ts_language, source)?;
1463        let mut language_capture_ix = None;
1464        let mut content_capture_ix = None;
1465        get_capture_indices(
1466            &query,
1467            &mut [
1468                ("language", &mut language_capture_ix),
1469                ("content", &mut content_capture_ix),
1470            ],
1471        );
1472        let patterns = (0..query.pattern_count())
1473            .map(|ix| {
1474                let mut config = InjectionPatternConfig::default();
1475                for setting in query.property_settings(ix) {
1476                    match setting.key.as_ref() {
1477                        "language" => {
1478                            config.language = setting.value.clone();
1479                        }
1480                        "combined" => {
1481                            config.combined = true;
1482                        }
1483                        _ => {}
1484                    }
1485                }
1486                config
1487            })
1488            .collect();
1489        if let Some(content_capture_ix) = content_capture_ix {
1490            grammar.injection_config = Some(InjectionConfig {
1491                query,
1492                language_capture_ix,
1493                content_capture_ix,
1494                patterns,
1495            });
1496        }
1497        Ok(self)
1498    }
1499
1500    pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1501        let query = Query::new(&self.grammar_mut().ts_language, source)?;
1502
1503        let mut override_configs_by_id = HashMap::default();
1504        for (ix, name) in query.capture_names().iter().enumerate() {
1505            if !name.starts_with('_') {
1506                let value = self.config.overrides.remove(*name).unwrap_or_default();
1507                for server_name in &value.opt_into_language_servers {
1508                    if !self
1509                        .config
1510                        .scope_opt_in_language_servers
1511                        .contains(server_name)
1512                    {
1513                        util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1514                    }
1515                }
1516
1517                override_configs_by_id.insert(ix as u32, (name.to_string(), value));
1518            }
1519        }
1520
1521        if !self.config.overrides.is_empty() {
1522            let keys = self.config.overrides.keys().collect::<Vec<_>>();
1523            Err(anyhow!(
1524                "language {:?} has overrides in config not in query: {keys:?}",
1525                self.config.name
1526            ))?;
1527        }
1528
1529        for disabled_scope_name in self
1530            .config
1531            .brackets
1532            .disabled_scopes_by_bracket_ix
1533            .iter()
1534            .flatten()
1535        {
1536            if !override_configs_by_id
1537                .values()
1538                .any(|(scope_name, _)| scope_name == disabled_scope_name)
1539            {
1540                Err(anyhow!(
1541                    "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1542                    self.config.name
1543                ))?;
1544            }
1545        }
1546
1547        for (name, override_config) in override_configs_by_id.values_mut() {
1548            override_config.disabled_bracket_ixs = self
1549                .config
1550                .brackets
1551                .disabled_scopes_by_bracket_ix
1552                .iter()
1553                .enumerate()
1554                .filter_map(|(ix, disabled_scope_names)| {
1555                    if disabled_scope_names.contains(name) {
1556                        Some(ix as u16)
1557                    } else {
1558                        None
1559                    }
1560                })
1561                .collect();
1562        }
1563
1564        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1565        self.grammar_mut().override_config = Some(OverrideConfig {
1566            query,
1567            values: override_configs_by_id,
1568        });
1569        Ok(self)
1570    }
1571
1572    fn grammar_mut(&mut self) -> &mut Grammar {
1573        Arc::get_mut(self.grammar.as_mut().unwrap()).unwrap()
1574    }
1575
1576    pub async fn with_lsp_adapters(mut self, lsp_adapters: Vec<Arc<dyn LspAdapter>>) -> Self {
1577        for adapter in lsp_adapters {
1578            self.adapters.push(CachedLspAdapter::new(adapter).await);
1579        }
1580        self
1581    }
1582
1583    #[cfg(any(test, feature = "test-support"))]
1584    pub async fn set_fake_lsp_adapter(
1585        &mut self,
1586        fake_lsp_adapter: Arc<FakeLspAdapter>,
1587    ) -> mpsc::UnboundedReceiver<lsp::FakeLanguageServer> {
1588        let (servers_tx, servers_rx) = mpsc::unbounded();
1589        self.fake_adapter = Some((servers_tx, fake_lsp_adapter.clone()));
1590        let adapter = CachedLspAdapter::new(Arc::new(fake_lsp_adapter)).await;
1591        self.adapters = vec![adapter];
1592        servers_rx
1593    }
1594
1595    pub fn name(&self) -> Arc<str> {
1596        self.config.name.clone()
1597    }
1598
1599    pub async fn disk_based_diagnostic_sources(&self) -> &[String] {
1600        match self.adapters.first().as_ref() {
1601            Some(adapter) => &adapter.disk_based_diagnostic_sources,
1602            None => &[],
1603        }
1604    }
1605
1606    pub async fn disk_based_diagnostics_progress_token(&self) -> Option<&str> {
1607        for adapter in &self.adapters {
1608            let token = adapter.disk_based_diagnostics_progress_token.as_deref();
1609            if token.is_some() {
1610                return token;
1611            }
1612        }
1613
1614        None
1615    }
1616
1617    pub async fn process_completion(self: &Arc<Self>, completion: &mut lsp::CompletionItem) {
1618        for adapter in &self.adapters {
1619            adapter.process_completion(completion).await;
1620        }
1621    }
1622
1623    pub async fn label_for_completion(
1624        self: &Arc<Self>,
1625        completion: &lsp::CompletionItem,
1626    ) -> Option<CodeLabel> {
1627        self.adapters
1628            .first()
1629            .as_ref()?
1630            .label_for_completion(completion, self)
1631            .await
1632    }
1633
1634    pub async fn label_for_symbol(
1635        self: &Arc<Self>,
1636        name: &str,
1637        kind: lsp::SymbolKind,
1638    ) -> Option<CodeLabel> {
1639        self.adapters
1640            .first()
1641            .as_ref()?
1642            .label_for_symbol(name, kind, self)
1643            .await
1644    }
1645
1646    pub fn highlight_text<'a>(
1647        self: &'a Arc<Self>,
1648        text: &'a Rope,
1649        range: Range<usize>,
1650    ) -> Vec<(Range<usize>, HighlightId)> {
1651        let mut result = Vec::new();
1652        if let Some(grammar) = &self.grammar {
1653            let tree = grammar.parse_text(text, None);
1654            let captures =
1655                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1656                    grammar.highlights_query.as_ref()
1657                });
1658            let highlight_maps = vec![grammar.highlight_map()];
1659            let mut offset = 0;
1660            for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1661                let end_offset = offset + chunk.text.len();
1662                if let Some(highlight_id) = chunk.syntax_highlight_id {
1663                    if !highlight_id.is_default() {
1664                        result.push((offset..end_offset, highlight_id));
1665                    }
1666                }
1667                offset = end_offset;
1668            }
1669        }
1670        result
1671    }
1672
1673    pub fn path_suffixes(&self) -> &[String] {
1674        &self.config.path_suffixes
1675    }
1676
1677    pub fn should_autoclose_before(&self, c: char) -> bool {
1678        c.is_whitespace() || self.config.autoclose_before.contains(c)
1679    }
1680
1681    pub fn set_theme(&self, theme: &SyntaxTheme) {
1682        if let Some(grammar) = self.grammar.as_ref() {
1683            if let Some(highlights_query) = &grammar.highlights_query {
1684                *grammar.highlight_map.lock() =
1685                    HighlightMap::new(highlights_query.capture_names(), theme);
1686            }
1687        }
1688    }
1689
1690    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1691        self.grammar.as_ref()
1692    }
1693
1694    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1695        LanguageScope {
1696            language: self.clone(),
1697            override_id: None,
1698        }
1699    }
1700
1701    pub fn prettier_parser_name(&self) -> Option<&str> {
1702        self.config.prettier_parser_name.as_deref()
1703    }
1704}
1705
1706impl LanguageScope {
1707    pub fn collapsed_placeholder(&self) -> &str {
1708        self.language.config.collapsed_placeholder.as_ref()
1709    }
1710
1711    /// Returns line prefix that is inserted in e.g. line continuations or
1712    /// in `toggle comments` action.
1713    pub fn line_comment_prefix(&self) -> Option<&Arc<str>> {
1714        Override::as_option(
1715            self.config_override().map(|o| &o.line_comment),
1716            self.language.config.line_comment.as_ref(),
1717        )
1718    }
1719
1720    pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1721        Override::as_option(
1722            self.config_override().map(|o| &o.block_comment),
1723            self.language.config.block_comment.as_ref(),
1724        )
1725        .map(|e| (&e.0, &e.1))
1726    }
1727
1728    /// Returns a list of language-specific word characters.
1729    ///
1730    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1731    /// the purpose of actions like 'move to next word end` or whole-word search.
1732    /// It additionally accounts for language's additional word characters.
1733    pub fn word_characters(&self) -> Option<&HashSet<char>> {
1734        Override::as_option(
1735            self.config_override().map(|o| &o.word_characters),
1736            Some(&self.language.config.word_characters),
1737        )
1738    }
1739
1740    /// Returns a list of bracket pairs for a given language with an additional
1741    /// piece of information about whether the particular bracket pair is currently active for a given language.
1742    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1743        let mut disabled_ids = self
1744            .config_override()
1745            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1746        self.language
1747            .config
1748            .brackets
1749            .pairs
1750            .iter()
1751            .enumerate()
1752            .map(move |(ix, bracket)| {
1753                let mut is_enabled = true;
1754                if let Some(next_disabled_ix) = disabled_ids.first() {
1755                    if ix == *next_disabled_ix as usize {
1756                        disabled_ids = &disabled_ids[1..];
1757                        is_enabled = false;
1758                    }
1759                }
1760                (bracket, is_enabled)
1761            })
1762    }
1763
1764    pub fn should_autoclose_before(&self, c: char) -> bool {
1765        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1766    }
1767
1768    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1769        let config = &self.language.config;
1770        let opt_in_servers = &config.scope_opt_in_language_servers;
1771        if opt_in_servers.iter().any(|o| *o == *name.0) {
1772            if let Some(over) = self.config_override() {
1773                over.opt_into_language_servers.iter().any(|o| *o == *name.0)
1774            } else {
1775                false
1776            }
1777        } else {
1778            true
1779        }
1780    }
1781
1782    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1783        let id = self.override_id?;
1784        let grammar = self.language.grammar.as_ref()?;
1785        let override_config = grammar.override_config.as_ref()?;
1786        override_config.values.get(&id).map(|e| &e.1)
1787    }
1788}
1789
1790impl Hash for Language {
1791    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1792        self.id().hash(state)
1793    }
1794}
1795
1796impl PartialEq for Language {
1797    fn eq(&self, other: &Self) -> bool {
1798        self.id().eq(&other.id())
1799    }
1800}
1801
1802impl Eq for Language {}
1803
1804impl Debug for Language {
1805    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1806        f.debug_struct("Language")
1807            .field("name", &self.config.name)
1808            .finish()
1809    }
1810}
1811
1812impl Grammar {
1813    pub fn id(&self) -> usize {
1814        self.id
1815    }
1816
1817    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1818        PARSER.with(|parser| {
1819            let mut parser = parser.borrow_mut();
1820            parser
1821                .set_language(&self.ts_language)
1822                .expect("incompatible grammar");
1823            let mut chunks = text.chunks_in_range(0..text.len());
1824            parser
1825                .parse_with(
1826                    &mut move |offset, _| {
1827                        chunks.seek(offset);
1828                        chunks.next().unwrap_or("").as_bytes()
1829                    },
1830                    old_tree.as_ref(),
1831                )
1832                .unwrap()
1833        })
1834    }
1835
1836    pub fn highlight_map(&self) -> HighlightMap {
1837        self.highlight_map.lock().clone()
1838    }
1839
1840    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1841        let capture_id = self
1842            .highlights_query
1843            .as_ref()?
1844            .capture_index_for_name(name)?;
1845        Some(self.highlight_map.lock().get(capture_id))
1846    }
1847}
1848
1849impl CodeLabel {
1850    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1851        let mut result = Self {
1852            runs: Vec::new(),
1853            filter_range: 0..text.len(),
1854            text,
1855        };
1856        if let Some(filter_text) = filter_text {
1857            if let Some(ix) = result.text.find(filter_text) {
1858                result.filter_range = ix..ix + filter_text.len();
1859            }
1860        }
1861        result
1862    }
1863}
1864
1865#[cfg(any(test, feature = "test-support"))]
1866impl Default for FakeLspAdapter {
1867    fn default() -> Self {
1868        Self {
1869            name: "the-fake-language-server",
1870            capabilities: lsp::LanguageServer::full_capabilities(),
1871            initializer: None,
1872            disk_based_diagnostics_progress_token: None,
1873            initialization_options: None,
1874            disk_based_diagnostics_sources: Vec::new(),
1875            prettier_plugins: Vec::new(),
1876        }
1877    }
1878}
1879
1880#[cfg(any(test, feature = "test-support"))]
1881#[async_trait]
1882impl LspAdapter for Arc<FakeLspAdapter> {
1883    fn name(&self) -> LanguageServerName {
1884        LanguageServerName(self.name.into())
1885    }
1886
1887    fn short_name(&self) -> &'static str {
1888        "FakeLspAdapter"
1889    }
1890
1891    async fn fetch_latest_server_version(
1892        &self,
1893        _: &dyn LspAdapterDelegate,
1894    ) -> Result<Box<dyn 'static + Send + Any>> {
1895        unreachable!();
1896    }
1897
1898    async fn fetch_server_binary(
1899        &self,
1900        _: Box<dyn 'static + Send + Any>,
1901        _: PathBuf,
1902        _: &dyn LspAdapterDelegate,
1903    ) -> Result<LanguageServerBinary> {
1904        unreachable!();
1905    }
1906
1907    async fn cached_server_binary(
1908        &self,
1909        _: PathBuf,
1910        _: &dyn LspAdapterDelegate,
1911    ) -> Option<LanguageServerBinary> {
1912        unreachable!();
1913    }
1914
1915    async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1916        unreachable!();
1917    }
1918
1919    fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1920
1921    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1922        self.disk_based_diagnostics_sources.clone()
1923    }
1924
1925    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1926        self.disk_based_diagnostics_progress_token.clone()
1927    }
1928
1929    fn initialization_options(&self) -> Option<Value> {
1930        self.initialization_options.clone()
1931    }
1932
1933    fn prettier_plugins(&self) -> &[&'static str] {
1934        &self.prettier_plugins
1935    }
1936}
1937
1938fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1939    for (ix, name) in query.capture_names().iter().enumerate() {
1940        for (capture_name, index) in captures.iter_mut() {
1941            if capture_name == name {
1942                **index = Some(ix as u32);
1943                break;
1944            }
1945        }
1946    }
1947}
1948
1949pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1950    lsp::Position::new(point.row, point.column)
1951}
1952
1953pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1954    Unclipped(PointUtf16::new(point.line, point.character))
1955}
1956
1957pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1958    lsp::Range {
1959        start: point_to_lsp(range.start),
1960        end: point_to_lsp(range.end),
1961    }
1962}
1963
1964pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1965    let mut start = point_from_lsp(range.start);
1966    let mut end = point_from_lsp(range.end);
1967    if start > end {
1968        mem::swap(&mut start, &mut end);
1969    }
1970    start..end
1971}
1972
1973#[cfg(test)]
1974mod tests {
1975    use super::*;
1976    use gpui::TestAppContext;
1977
1978    #[gpui::test(iterations = 10)]
1979    async fn test_first_line_pattern(cx: &mut TestAppContext) {
1980        let mut languages = LanguageRegistry::test();
1981
1982        languages.set_executor(cx.executor());
1983        let languages = Arc::new(languages);
1984        languages.register(
1985            "/javascript",
1986            LanguageConfig {
1987                name: "JavaScript".into(),
1988                path_suffixes: vec!["js".into()],
1989                first_line_pattern: Some(Regex::new(r"\bnode\b").unwrap()),
1990                ..Default::default()
1991            },
1992            tree_sitter_typescript::language_tsx(),
1993            vec![],
1994            |_| Default::default(),
1995        );
1996
1997        languages
1998            .language_for_file("the/script", None)
1999            .await
2000            .unwrap_err();
2001        languages
2002            .language_for_file("the/script", Some(&"nothing".into()))
2003            .await
2004            .unwrap_err();
2005        assert_eq!(
2006            languages
2007                .language_for_file("the/script", Some(&"#!/bin/env node".into()))
2008                .await
2009                .unwrap()
2010                .name()
2011                .as_ref(),
2012            "JavaScript"
2013        );
2014    }
2015
2016    #[gpui::test(iterations = 10)]
2017    async fn test_language_loading(cx: &mut TestAppContext) {
2018        let mut languages = LanguageRegistry::test();
2019        languages.set_executor(cx.executor());
2020        let languages = Arc::new(languages);
2021        languages.register(
2022            "/JSON",
2023            LanguageConfig {
2024                name: "JSON".into(),
2025                path_suffixes: vec!["json".into()],
2026                ..Default::default()
2027            },
2028            tree_sitter_json::language(),
2029            vec![],
2030            |_| Default::default(),
2031        );
2032        languages.register(
2033            "/rust",
2034            LanguageConfig {
2035                name: "Rust".into(),
2036                path_suffixes: vec!["rs".into()],
2037                ..Default::default()
2038            },
2039            tree_sitter_rust::language(),
2040            vec![],
2041            |_| Default::default(),
2042        );
2043        assert_eq!(
2044            languages.language_names(),
2045            &[
2046                "JSON".to_string(),
2047                "Plain Text".to_string(),
2048                "Rust".to_string(),
2049            ]
2050        );
2051
2052        let rust1 = languages.language_for_name("Rust");
2053        let rust2 = languages.language_for_name("Rust");
2054
2055        // Ensure language is still listed even if it's being loaded.
2056        assert_eq!(
2057            languages.language_names(),
2058            &[
2059                "JSON".to_string(),
2060                "Plain Text".to_string(),
2061                "Rust".to_string(),
2062            ]
2063        );
2064
2065        let (rust1, rust2) = futures::join!(rust1, rust2);
2066        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2067
2068        // Ensure language is still listed even after loading it.
2069        assert_eq!(
2070            languages.language_names(),
2071            &[
2072                "JSON".to_string(),
2073                "Plain Text".to_string(),
2074                "Rust".to_string(),
2075            ]
2076        );
2077
2078        // Loading an unknown language returns an error.
2079        assert!(languages.language_for_name("Unknown").await.is_err());
2080    }
2081}