language.rs

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