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