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