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