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