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};
  59use task::RunnableTag;
  60pub use task_context::{
  61    BasicContextProvider, ContextProvider, ContextProviderWithTasks, RunnableRange,
  62};
  63use theme::SyntaxTheme;
  64use tree_sitter::{self, wasmtime, Query, QueryCursor, WasmStore};
  65use util::http::HttpClient;
  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    /// The name of a Prettier parser that should be used for this language.
 606    #[serde(default)]
 607    pub prettier_parser_name: Option<String>,
 608    /// The names of any Prettier plugins that should be used for this language.
 609    #[serde(default)]
 610    pub prettier_plugins: Vec<Arc<str>>,
 611
 612    /// Whether to indent lines using tab characters, as opposed to multiple
 613    /// spaces.
 614    #[serde(default)]
 615    pub hard_tabs: Option<bool>,
 616    /// How many columns a tab should occupy.
 617    #[serde(default)]
 618    pub tab_size: Option<NonZeroU32>,
 619    /// How to soft-wrap long lines of text.
 620    #[serde(default)]
 621    pub soft_wrap: Option<SoftWrap>,
 622}
 623
 624#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
 625pub struct LanguageMatcher {
 626    /// 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`.
 627    #[serde(default)]
 628    pub path_suffixes: Vec<String>,
 629    /// A regex pattern that determines whether the language should be assigned to a file or not.
 630    #[serde(
 631        default,
 632        serialize_with = "serialize_regex",
 633        deserialize_with = "deserialize_regex"
 634    )]
 635    #[schemars(schema_with = "regex_json_schema")]
 636    pub first_line_pattern: Option<Regex>,
 637}
 638
 639/// Represents a language for the given range. Some languages (e.g. HTML)
 640/// interleave several languages together, thus a single buffer might actually contain
 641/// several nested scopes.
 642#[derive(Clone, Debug)]
 643pub struct LanguageScope {
 644    language: Arc<Language>,
 645    override_id: Option<u32>,
 646}
 647
 648#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
 649pub struct LanguageConfigOverride {
 650    #[serde(default)]
 651    pub line_comments: Override<Vec<Arc<str>>>,
 652    #[serde(default)]
 653    pub block_comment: Override<(Arc<str>, Arc<str>)>,
 654    #[serde(skip_deserializing)]
 655    #[schemars(skip)]
 656    pub disabled_bracket_ixs: Vec<u16>,
 657    #[serde(default)]
 658    pub word_characters: Override<HashSet<char>>,
 659    #[serde(default)]
 660    pub opt_into_language_servers: Vec<String>,
 661}
 662
 663#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
 664#[serde(untagged)]
 665pub enum Override<T> {
 666    Remove { remove: bool },
 667    Set(T),
 668}
 669
 670impl<T> Default for Override<T> {
 671    fn default() -> Self {
 672        Override::Remove { remove: false }
 673    }
 674}
 675
 676impl<T> Override<T> {
 677    fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
 678        match this {
 679            Some(Self::Set(value)) => Some(value),
 680            Some(Self::Remove { remove: true }) => None,
 681            Some(Self::Remove { remove: false }) | None => original,
 682        }
 683    }
 684}
 685
 686impl Default for LanguageConfig {
 687    fn default() -> Self {
 688        Self {
 689            name: "".into(),
 690            code_fence_block_name: None,
 691            grammar: None,
 692            matcher: LanguageMatcher::default(),
 693            brackets: Default::default(),
 694            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
 695            increase_indent_pattern: Default::default(),
 696            decrease_indent_pattern: Default::default(),
 697            autoclose_before: Default::default(),
 698            line_comments: Default::default(),
 699            block_comment: Default::default(),
 700            scope_opt_in_language_servers: Default::default(),
 701            overrides: Default::default(),
 702            word_characters: Default::default(),
 703            prettier_parser_name: None,
 704            prettier_plugins: Default::default(),
 705            collapsed_placeholder: Default::default(),
 706            hard_tabs: Default::default(),
 707            tab_size: Default::default(),
 708            soft_wrap: Default::default(),
 709        }
 710    }
 711}
 712
 713fn auto_indent_using_last_non_empty_line_default() -> bool {
 714    true
 715}
 716
 717fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
 718    let source = Option::<String>::deserialize(d)?;
 719    if let Some(source) = source {
 720        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
 721    } else {
 722        Ok(None)
 723    }
 724}
 725
 726fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
 727    Schema::Object(SchemaObject {
 728        instance_type: Some(InstanceType::String.into()),
 729        ..Default::default()
 730    })
 731}
 732
 733fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
 734where
 735    S: Serializer,
 736{
 737    match regex {
 738        Some(regex) => serializer.serialize_str(regex.as_str()),
 739        None => serializer.serialize_none(),
 740    }
 741}
 742
 743#[doc(hidden)]
 744#[cfg(any(test, feature = "test-support"))]
 745pub struct FakeLspAdapter {
 746    pub name: &'static str,
 747    pub initialization_options: Option<Value>,
 748    pub capabilities: lsp::ServerCapabilities,
 749    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
 750    pub disk_based_diagnostics_progress_token: Option<String>,
 751    pub disk_based_diagnostics_sources: Vec<String>,
 752    pub prettier_plugins: Vec<&'static str>,
 753    pub language_server_binary: LanguageServerBinary,
 754}
 755
 756/// Configuration of handling bracket pairs for a given language.
 757///
 758/// This struct includes settings for defining which pairs of characters are considered brackets and
 759/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
 760#[derive(Clone, Debug, Default, JsonSchema)]
 761pub struct BracketPairConfig {
 762    /// A list of character pairs that should be treated as brackets in the context of a given language.
 763    pub pairs: Vec<BracketPair>,
 764    /// A list of tree-sitter scopes for which a given bracket should not be active.
 765    /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
 766    #[schemars(skip)]
 767    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
 768}
 769
 770fn bracket_pair_config_json_schema(gen: &mut SchemaGenerator) -> Schema {
 771    Option::<Vec<BracketPairContent>>::json_schema(gen)
 772}
 773
 774#[derive(Deserialize, JsonSchema)]
 775pub struct BracketPairContent {
 776    #[serde(flatten)]
 777    pub bracket_pair: BracketPair,
 778    #[serde(default)]
 779    pub not_in: Vec<String>,
 780}
 781
 782impl<'de> Deserialize<'de> for BracketPairConfig {
 783    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 784    where
 785        D: Deserializer<'de>,
 786    {
 787        let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
 788        let mut brackets = Vec::with_capacity(result.len());
 789        let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
 790        for entry in result {
 791            brackets.push(entry.bracket_pair);
 792            disabled_scopes_by_bracket_ix.push(entry.not_in);
 793        }
 794
 795        Ok(BracketPairConfig {
 796            pairs: brackets,
 797            disabled_scopes_by_bracket_ix,
 798        })
 799    }
 800}
 801
 802/// Describes a single bracket pair and how an editor should react to e.g. inserting
 803/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
 804#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
 805pub struct BracketPair {
 806    /// Starting substring for a bracket.
 807    pub start: String,
 808    /// Ending substring for a bracket.
 809    pub end: String,
 810    /// True if `end` should be automatically inserted right after `start` characters.
 811    pub close: bool,
 812    /// True if an extra newline should be inserted while the cursor is in the middle
 813    /// of that bracket pair.
 814    pub newline: bool,
 815}
 816
 817#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 818pub(crate) struct LanguageId(usize);
 819
 820impl LanguageId {
 821    pub(crate) fn new() -> Self {
 822        Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
 823    }
 824}
 825
 826pub struct Language {
 827    pub(crate) id: LanguageId,
 828    pub(crate) config: LanguageConfig,
 829    pub(crate) grammar: Option<Arc<Grammar>>,
 830    pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
 831}
 832
 833#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 834pub struct GrammarId(pub usize);
 835
 836impl GrammarId {
 837    pub(crate) fn new() -> Self {
 838        Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
 839    }
 840}
 841
 842pub struct Grammar {
 843    id: GrammarId,
 844    pub ts_language: tree_sitter::Language,
 845    pub(crate) error_query: Query,
 846    pub(crate) highlights_query: Option<Query>,
 847    pub(crate) brackets_config: Option<BracketConfig>,
 848    pub(crate) redactions_config: Option<RedactionConfig>,
 849    pub(crate) runnable_config: Option<RunnableConfig>,
 850    pub(crate) indents_config: Option<IndentConfig>,
 851    pub outline_config: Option<OutlineConfig>,
 852    pub embedding_config: Option<EmbeddingConfig>,
 853    pub(crate) injection_config: Option<InjectionConfig>,
 854    pub(crate) override_config: Option<OverrideConfig>,
 855    pub(crate) highlight_map: Mutex<HighlightMap>,
 856}
 857
 858struct IndentConfig {
 859    query: Query,
 860    indent_capture_ix: u32,
 861    start_capture_ix: Option<u32>,
 862    end_capture_ix: Option<u32>,
 863    outdent_capture_ix: Option<u32>,
 864}
 865
 866pub struct OutlineConfig {
 867    pub query: Query,
 868    pub item_capture_ix: u32,
 869    pub name_capture_ix: u32,
 870    pub context_capture_ix: Option<u32>,
 871    pub extra_context_capture_ix: Option<u32>,
 872}
 873
 874#[derive(Debug)]
 875pub struct EmbeddingConfig {
 876    pub query: Query,
 877    pub item_capture_ix: u32,
 878    pub name_capture_ix: Option<u32>,
 879    pub context_capture_ix: Option<u32>,
 880    pub collapse_capture_ix: Option<u32>,
 881    pub keep_capture_ix: Option<u32>,
 882}
 883
 884struct InjectionConfig {
 885    query: Query,
 886    content_capture_ix: u32,
 887    language_capture_ix: Option<u32>,
 888    patterns: Vec<InjectionPatternConfig>,
 889}
 890
 891struct RedactionConfig {
 892    pub query: Query,
 893    pub redaction_capture_ix: u32,
 894}
 895
 896struct RunnableConfig {
 897    pub query: Query,
 898    /// A mapping from captures indices to known test tags
 899    pub runnable_tags: HashMap<u32, RunnableTag>,
 900    /// index of the capture that corresponds to @run
 901    pub run_capture_ix: u32,
 902}
 903
 904struct OverrideConfig {
 905    query: Query,
 906    values: HashMap<u32, (String, LanguageConfigOverride)>,
 907}
 908
 909#[derive(Default, Clone)]
 910struct InjectionPatternConfig {
 911    language: Option<Box<str>>,
 912    combined: bool,
 913}
 914
 915struct BracketConfig {
 916    query: Query,
 917    open_capture_ix: u32,
 918    close_capture_ix: u32,
 919}
 920
 921impl Language {
 922    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
 923        Self::new_with_id(LanguageId::new(), config, ts_language)
 924    }
 925
 926    fn new_with_id(
 927        id: LanguageId,
 928        config: LanguageConfig,
 929        ts_language: Option<tree_sitter::Language>,
 930    ) -> Self {
 931        Self {
 932            id,
 933            config,
 934            grammar: ts_language.map(|ts_language| {
 935                Arc::new(Grammar {
 936                    id: GrammarId::new(),
 937                    highlights_query: None,
 938                    brackets_config: None,
 939                    outline_config: None,
 940                    embedding_config: None,
 941                    indents_config: None,
 942                    injection_config: None,
 943                    override_config: None,
 944                    redactions_config: None,
 945                    runnable_config: None,
 946                    error_query: Query::new(&ts_language, "(ERROR) @error").unwrap(),
 947                    ts_language,
 948                    highlight_map: Default::default(),
 949                })
 950            }),
 951            context_provider: None,
 952        }
 953    }
 954
 955    pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
 956        self.context_provider = provider;
 957        self
 958    }
 959
 960    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
 961        if let Some(query) = queries.highlights {
 962            self = self
 963                .with_highlights_query(query.as_ref())
 964                .context("Error loading highlights query")?;
 965        }
 966        if let Some(query) = queries.brackets {
 967            self = self
 968                .with_brackets_query(query.as_ref())
 969                .context("Error loading brackets query")?;
 970        }
 971        if let Some(query) = queries.indents {
 972            self = self
 973                .with_indents_query(query.as_ref())
 974                .context("Error loading indents query")?;
 975        }
 976        if let Some(query) = queries.outline {
 977            self = self
 978                .with_outline_query(query.as_ref())
 979                .context("Error loading outline query")?;
 980        }
 981        if let Some(query) = queries.embedding {
 982            self = self
 983                .with_embedding_query(query.as_ref())
 984                .context("Error loading embedding query")?;
 985        }
 986        if let Some(query) = queries.injections {
 987            self = self
 988                .with_injection_query(query.as_ref())
 989                .context("Error loading injection query")?;
 990        }
 991        if let Some(query) = queries.overrides {
 992            self = self
 993                .with_override_query(query.as_ref())
 994                .context("Error loading override query")?;
 995        }
 996        if let Some(query) = queries.redactions {
 997            self = self
 998                .with_redaction_query(query.as_ref())
 999                .context("Error loading redaction query")?;
1000        }
1001        if let Some(query) = queries.runnables {
1002            self = self
1003                .with_runnable_query(query.as_ref())
1004                .context("Error loading tests query")?;
1005        }
1006        Ok(self)
1007    }
1008
1009    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1010        let grammar = self
1011            .grammar_mut()
1012            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1013        grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1014        Ok(self)
1015    }
1016
1017    pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1018        let grammar = self
1019            .grammar_mut()
1020            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1021
1022        let query = Query::new(&grammar.ts_language, source)?;
1023        let mut run_capture_index = None;
1024        let mut runnable_tags = HashMap::default();
1025        for (ix, name) in query.capture_names().iter().enumerate() {
1026            if *name == "run" {
1027                run_capture_index = Some(ix as u32);
1028            } else if !name.starts_with('_') {
1029                runnable_tags.insert(ix as u32, RunnableTag(name.to_string().into()));
1030            }
1031        }
1032
1033        if let Some(run_capture_ix) = run_capture_index {
1034            grammar.runnable_config = Some(RunnableConfig {
1035                query,
1036                run_capture_ix,
1037                runnable_tags,
1038            });
1039        }
1040
1041        Ok(self)
1042    }
1043
1044    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1045        let grammar = self
1046            .grammar_mut()
1047            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1048        let query = Query::new(&grammar.ts_language, source)?;
1049        let mut item_capture_ix = None;
1050        let mut name_capture_ix = None;
1051        let mut context_capture_ix = None;
1052        let mut extra_context_capture_ix = None;
1053        get_capture_indices(
1054            &query,
1055            &mut [
1056                ("item", &mut item_capture_ix),
1057                ("name", &mut name_capture_ix),
1058                ("context", &mut context_capture_ix),
1059                ("context.extra", &mut extra_context_capture_ix),
1060            ],
1061        );
1062        if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1063            grammar.outline_config = Some(OutlineConfig {
1064                query,
1065                item_capture_ix,
1066                name_capture_ix,
1067                context_capture_ix,
1068                extra_context_capture_ix,
1069            });
1070        }
1071        Ok(self)
1072    }
1073
1074    pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1075        let grammar = self
1076            .grammar_mut()
1077            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1078        let query = Query::new(&grammar.ts_language, source)?;
1079        let mut item_capture_ix = None;
1080        let mut name_capture_ix = None;
1081        let mut context_capture_ix = None;
1082        let mut collapse_capture_ix = None;
1083        let mut keep_capture_ix = None;
1084        get_capture_indices(
1085            &query,
1086            &mut [
1087                ("item", &mut item_capture_ix),
1088                ("name", &mut name_capture_ix),
1089                ("context", &mut context_capture_ix),
1090                ("keep", &mut keep_capture_ix),
1091                ("collapse", &mut collapse_capture_ix),
1092            ],
1093        );
1094        if let Some(item_capture_ix) = item_capture_ix {
1095            grammar.embedding_config = Some(EmbeddingConfig {
1096                query,
1097                item_capture_ix,
1098                name_capture_ix,
1099                context_capture_ix,
1100                collapse_capture_ix,
1101                keep_capture_ix,
1102            });
1103        }
1104        Ok(self)
1105    }
1106
1107    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1108        let grammar = self
1109            .grammar_mut()
1110            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1111        let query = Query::new(&grammar.ts_language, source)?;
1112        let mut open_capture_ix = None;
1113        let mut close_capture_ix = None;
1114        get_capture_indices(
1115            &query,
1116            &mut [
1117                ("open", &mut open_capture_ix),
1118                ("close", &mut close_capture_ix),
1119            ],
1120        );
1121        if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1122            grammar.brackets_config = Some(BracketConfig {
1123                query,
1124                open_capture_ix,
1125                close_capture_ix,
1126            });
1127        }
1128        Ok(self)
1129    }
1130
1131    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1132        let grammar = self
1133            .grammar_mut()
1134            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1135        let query = Query::new(&grammar.ts_language, source)?;
1136        let mut indent_capture_ix = None;
1137        let mut start_capture_ix = None;
1138        let mut end_capture_ix = None;
1139        let mut outdent_capture_ix = None;
1140        get_capture_indices(
1141            &query,
1142            &mut [
1143                ("indent", &mut indent_capture_ix),
1144                ("start", &mut start_capture_ix),
1145                ("end", &mut end_capture_ix),
1146                ("outdent", &mut outdent_capture_ix),
1147            ],
1148        );
1149        if let Some(indent_capture_ix) = indent_capture_ix {
1150            grammar.indents_config = Some(IndentConfig {
1151                query,
1152                indent_capture_ix,
1153                start_capture_ix,
1154                end_capture_ix,
1155                outdent_capture_ix,
1156            });
1157        }
1158        Ok(self)
1159    }
1160
1161    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1162        let grammar = self
1163            .grammar_mut()
1164            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1165        let query = Query::new(&grammar.ts_language, source)?;
1166        let mut language_capture_ix = None;
1167        let mut content_capture_ix = None;
1168        get_capture_indices(
1169            &query,
1170            &mut [
1171                ("language", &mut language_capture_ix),
1172                ("content", &mut content_capture_ix),
1173            ],
1174        );
1175        let patterns = (0..query.pattern_count())
1176            .map(|ix| {
1177                let mut config = InjectionPatternConfig::default();
1178                for setting in query.property_settings(ix) {
1179                    match setting.key.as_ref() {
1180                        "language" => {
1181                            config.language.clone_from(&setting.value);
1182                        }
1183                        "combined" => {
1184                            config.combined = true;
1185                        }
1186                        _ => {}
1187                    }
1188                }
1189                config
1190            })
1191            .collect();
1192        if let Some(content_capture_ix) = content_capture_ix {
1193            grammar.injection_config = Some(InjectionConfig {
1194                query,
1195                language_capture_ix,
1196                content_capture_ix,
1197                patterns,
1198            });
1199        }
1200        Ok(self)
1201    }
1202
1203    pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1204        let query = {
1205            let grammar = self
1206                .grammar
1207                .as_ref()
1208                .ok_or_else(|| anyhow!("no grammar for language"))?;
1209            Query::new(&grammar.ts_language, source)?
1210        };
1211
1212        let mut override_configs_by_id = HashMap::default();
1213        for (ix, name) in query.capture_names().iter().enumerate() {
1214            if !name.starts_with('_') {
1215                let value = self.config.overrides.remove(*name).unwrap_or_default();
1216                for server_name in &value.opt_into_language_servers {
1217                    if !self
1218                        .config
1219                        .scope_opt_in_language_servers
1220                        .contains(server_name)
1221                    {
1222                        util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1223                    }
1224                }
1225
1226                override_configs_by_id.insert(ix as u32, (name.to_string(), value));
1227            }
1228        }
1229
1230        if !self.config.overrides.is_empty() {
1231            let keys = self.config.overrides.keys().collect::<Vec<_>>();
1232            Err(anyhow!(
1233                "language {:?} has overrides in config not in query: {keys:?}",
1234                self.config.name
1235            ))?;
1236        }
1237
1238        for disabled_scope_name in self
1239            .config
1240            .brackets
1241            .disabled_scopes_by_bracket_ix
1242            .iter()
1243            .flatten()
1244        {
1245            if !override_configs_by_id
1246                .values()
1247                .any(|(scope_name, _)| scope_name == disabled_scope_name)
1248            {
1249                Err(anyhow!(
1250                    "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1251                    self.config.name
1252                ))?;
1253            }
1254        }
1255
1256        for (name, override_config) in override_configs_by_id.values_mut() {
1257            override_config.disabled_bracket_ixs = self
1258                .config
1259                .brackets
1260                .disabled_scopes_by_bracket_ix
1261                .iter()
1262                .enumerate()
1263                .filter_map(|(ix, disabled_scope_names)| {
1264                    if disabled_scope_names.contains(name) {
1265                        Some(ix as u16)
1266                    } else {
1267                        None
1268                    }
1269                })
1270                .collect();
1271        }
1272
1273        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1274
1275        let grammar = self
1276            .grammar_mut()
1277            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1278        grammar.override_config = Some(OverrideConfig {
1279            query,
1280            values: override_configs_by_id,
1281        });
1282        Ok(self)
1283    }
1284
1285    pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1286        let grammar = self
1287            .grammar_mut()
1288            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1289
1290        let query = Query::new(&grammar.ts_language, source)?;
1291        let mut redaction_capture_ix = None;
1292        get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1293
1294        if let Some(redaction_capture_ix) = redaction_capture_ix {
1295            grammar.redactions_config = Some(RedactionConfig {
1296                query,
1297                redaction_capture_ix,
1298            });
1299        }
1300
1301        Ok(self)
1302    }
1303
1304    fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1305        Arc::get_mut(self.grammar.as_mut()?)
1306    }
1307
1308    pub fn name(&self) -> Arc<str> {
1309        self.config.name.clone()
1310    }
1311
1312    pub fn code_fence_block_name(&self) -> Arc<str> {
1313        self.config
1314            .code_fence_block_name
1315            .clone()
1316            .unwrap_or_else(|| self.config.name.to_lowercase().into())
1317    }
1318
1319    pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1320        self.context_provider.clone()
1321    }
1322
1323    pub fn highlight_text<'a>(
1324        self: &'a Arc<Self>,
1325        text: &'a Rope,
1326        range: Range<usize>,
1327    ) -> Vec<(Range<usize>, HighlightId)> {
1328        let mut result = Vec::new();
1329        if let Some(grammar) = &self.grammar {
1330            let tree = grammar.parse_text(text, None);
1331            let captures =
1332                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1333                    grammar.highlights_query.as_ref()
1334                });
1335            let highlight_maps = vec![grammar.highlight_map()];
1336            let mut offset = 0;
1337            for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1338                let end_offset = offset + chunk.text.len();
1339                if let Some(highlight_id) = chunk.syntax_highlight_id {
1340                    if !highlight_id.is_default() {
1341                        result.push((offset..end_offset, highlight_id));
1342                    }
1343                }
1344                offset = end_offset;
1345            }
1346        }
1347        result
1348    }
1349
1350    pub fn path_suffixes(&self) -> &[String] {
1351        &self.config.matcher.path_suffixes
1352    }
1353
1354    pub fn should_autoclose_before(&self, c: char) -> bool {
1355        c.is_whitespace() || self.config.autoclose_before.contains(c)
1356    }
1357
1358    pub fn set_theme(&self, theme: &SyntaxTheme) {
1359        if let Some(grammar) = self.grammar.as_ref() {
1360            if let Some(highlights_query) = &grammar.highlights_query {
1361                *grammar.highlight_map.lock() =
1362                    HighlightMap::new(highlights_query.capture_names(), theme);
1363            }
1364        }
1365    }
1366
1367    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1368        self.grammar.as_ref()
1369    }
1370
1371    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1372        LanguageScope {
1373            language: self.clone(),
1374            override_id: None,
1375        }
1376    }
1377
1378    pub fn prettier_parser_name(&self) -> Option<&str> {
1379        self.config.prettier_parser_name.as_deref()
1380    }
1381
1382    pub fn prettier_plugins(&self) -> &Vec<Arc<str>> {
1383        &self.config.prettier_plugins
1384    }
1385
1386    pub fn lsp_id(&self) -> String {
1387        match self.config.name.as_ref() {
1388            "Plain Text" => "plaintext".to_string(),
1389            language_name => language_name.to_lowercase(),
1390        }
1391    }
1392}
1393
1394impl LanguageScope {
1395    pub fn collapsed_placeholder(&self) -> &str {
1396        self.language.config.collapsed_placeholder.as_ref()
1397    }
1398
1399    /// Returns line prefix that is inserted in e.g. line continuations or
1400    /// in `toggle comments` action.
1401    pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1402        Override::as_option(
1403            self.config_override().map(|o| &o.line_comments),
1404            Some(&self.language.config.line_comments),
1405        )
1406        .map_or(&[] as &[_], |e| e.as_slice())
1407    }
1408
1409    pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1410        Override::as_option(
1411            self.config_override().map(|o| &o.block_comment),
1412            self.language.config.block_comment.as_ref(),
1413        )
1414        .map(|e| (&e.0, &e.1))
1415    }
1416
1417    /// Returns a list of language-specific word characters.
1418    ///
1419    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1420    /// the purpose of actions like 'move to next word end` or whole-word search.
1421    /// It additionally accounts for language's additional word characters.
1422    pub fn word_characters(&self) -> Option<&HashSet<char>> {
1423        Override::as_option(
1424            self.config_override().map(|o| &o.word_characters),
1425            Some(&self.language.config.word_characters),
1426        )
1427    }
1428
1429    /// Returns a list of bracket pairs for a given language with an additional
1430    /// piece of information about whether the particular bracket pair is currently active for a given language.
1431    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1432        let mut disabled_ids = self
1433            .config_override()
1434            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1435        self.language
1436            .config
1437            .brackets
1438            .pairs
1439            .iter()
1440            .enumerate()
1441            .map(move |(ix, bracket)| {
1442                let mut is_enabled = true;
1443                if let Some(next_disabled_ix) = disabled_ids.first() {
1444                    if ix == *next_disabled_ix as usize {
1445                        disabled_ids = &disabled_ids[1..];
1446                        is_enabled = false;
1447                    }
1448                }
1449                (bracket, is_enabled)
1450            })
1451    }
1452
1453    pub fn should_autoclose_before(&self, c: char) -> bool {
1454        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1455    }
1456
1457    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1458        let config = &self.language.config;
1459        let opt_in_servers = &config.scope_opt_in_language_servers;
1460        if opt_in_servers.iter().any(|o| *o == *name.0) {
1461            if let Some(over) = self.config_override() {
1462                over.opt_into_language_servers.iter().any(|o| *o == *name.0)
1463            } else {
1464                false
1465            }
1466        } else {
1467            true
1468        }
1469    }
1470
1471    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1472        let id = self.override_id?;
1473        let grammar = self.language.grammar.as_ref()?;
1474        let override_config = grammar.override_config.as_ref()?;
1475        override_config.values.get(&id).map(|e| &e.1)
1476    }
1477}
1478
1479impl Hash for Language {
1480    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1481        self.id.hash(state)
1482    }
1483}
1484
1485impl PartialEq for Language {
1486    fn eq(&self, other: &Self) -> bool {
1487        self.id.eq(&other.id)
1488    }
1489}
1490
1491impl Eq for Language {}
1492
1493impl Debug for Language {
1494    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1495        f.debug_struct("Language")
1496            .field("name", &self.config.name)
1497            .finish()
1498    }
1499}
1500
1501impl Grammar {
1502    pub fn id(&self) -> GrammarId {
1503        self.id
1504    }
1505
1506    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1507        with_parser(|parser| {
1508            parser
1509                .set_language(&self.ts_language)
1510                .expect("incompatible grammar");
1511            let mut chunks = text.chunks_in_range(0..text.len());
1512            parser
1513                .parse_with(
1514                    &mut move |offset, _| {
1515                        chunks.seek(offset);
1516                        chunks.next().unwrap_or("").as_bytes()
1517                    },
1518                    old_tree.as_ref(),
1519                )
1520                .unwrap()
1521        })
1522    }
1523
1524    pub fn highlight_map(&self) -> HighlightMap {
1525        self.highlight_map.lock().clone()
1526    }
1527
1528    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1529        let capture_id = self
1530            .highlights_query
1531            .as_ref()?
1532            .capture_index_for_name(name)?;
1533        Some(self.highlight_map.lock().get(capture_id))
1534    }
1535}
1536
1537impl CodeLabel {
1538    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1539        let mut result = Self {
1540            runs: Vec::new(),
1541            filter_range: 0..text.len(),
1542            text,
1543        };
1544        if let Some(filter_text) = filter_text {
1545            if let Some(ix) = result.text.find(filter_text) {
1546                result.filter_range = ix..ix + filter_text.len();
1547            }
1548        }
1549        result
1550    }
1551}
1552
1553impl Ord for LanguageMatcher {
1554    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1555        self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1556            self.first_line_pattern
1557                .as_ref()
1558                .map(Regex::as_str)
1559                .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1560        })
1561    }
1562}
1563
1564impl PartialOrd for LanguageMatcher {
1565    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1566        Some(self.cmp(other))
1567    }
1568}
1569
1570impl Eq for LanguageMatcher {}
1571
1572impl PartialEq for LanguageMatcher {
1573    fn eq(&self, other: &Self) -> bool {
1574        self.path_suffixes == other.path_suffixes
1575            && self.first_line_pattern.as_ref().map(Regex::as_str)
1576                == other.first_line_pattern.as_ref().map(Regex::as_str)
1577    }
1578}
1579
1580#[cfg(any(test, feature = "test-support"))]
1581impl Default for FakeLspAdapter {
1582    fn default() -> Self {
1583        Self {
1584            name: "the-fake-language-server",
1585            capabilities: lsp::LanguageServer::full_capabilities(),
1586            initializer: None,
1587            disk_based_diagnostics_progress_token: None,
1588            initialization_options: None,
1589            disk_based_diagnostics_sources: Vec::new(),
1590            prettier_plugins: Vec::new(),
1591            language_server_binary: LanguageServerBinary {
1592                path: "/the/fake/lsp/path".into(),
1593                arguments: vec![],
1594                env: Default::default(),
1595            },
1596        }
1597    }
1598}
1599
1600#[cfg(any(test, feature = "test-support"))]
1601#[async_trait(?Send)]
1602impl LspAdapter for FakeLspAdapter {
1603    fn name(&self) -> LanguageServerName {
1604        LanguageServerName(self.name.into())
1605    }
1606
1607    fn get_language_server_command<'a>(
1608        self: Arc<Self>,
1609        _: Arc<Language>,
1610        _: Arc<Path>,
1611        _: Arc<dyn LspAdapterDelegate>,
1612        _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
1613        _: &'a mut AsyncAppContext,
1614    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
1615        async move { Ok(self.language_server_binary.clone()) }.boxed_local()
1616    }
1617
1618    async fn fetch_latest_server_version(
1619        &self,
1620        _: &dyn LspAdapterDelegate,
1621    ) -> Result<Box<dyn 'static + Send + Any>> {
1622        unreachable!();
1623    }
1624
1625    async fn fetch_server_binary(
1626        &self,
1627        _: Box<dyn 'static + Send + Any>,
1628        _: PathBuf,
1629        _: &dyn LspAdapterDelegate,
1630    ) -> Result<LanguageServerBinary> {
1631        unreachable!();
1632    }
1633
1634    async fn cached_server_binary(
1635        &self,
1636        _: PathBuf,
1637        _: &dyn LspAdapterDelegate,
1638    ) -> Option<LanguageServerBinary> {
1639        unreachable!();
1640    }
1641
1642    async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1643        unreachable!();
1644    }
1645
1646    fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1647
1648    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1649        self.disk_based_diagnostics_sources.clone()
1650    }
1651
1652    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1653        self.disk_based_diagnostics_progress_token.clone()
1654    }
1655
1656    async fn initialization_options(
1657        self: Arc<Self>,
1658        _: &Arc<dyn LspAdapterDelegate>,
1659    ) -> Result<Option<Value>> {
1660        Ok(self.initialization_options.clone())
1661    }
1662
1663    fn as_fake(&self) -> Option<&FakeLspAdapter> {
1664        Some(self)
1665    }
1666}
1667
1668fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1669    for (ix, name) in query.capture_names().iter().enumerate() {
1670        for (capture_name, index) in captures.iter_mut() {
1671            if capture_name == name {
1672                **index = Some(ix as u32);
1673                break;
1674            }
1675        }
1676    }
1677}
1678
1679pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1680    lsp::Position::new(point.row, point.column)
1681}
1682
1683pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1684    Unclipped(PointUtf16::new(point.line, point.character))
1685}
1686
1687pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1688    lsp::Range {
1689        start: point_to_lsp(range.start),
1690        end: point_to_lsp(range.end),
1691    }
1692}
1693
1694pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1695    let mut start = point_from_lsp(range.start);
1696    let mut end = point_from_lsp(range.end);
1697    if start > end {
1698        mem::swap(&mut start, &mut end);
1699    }
1700    start..end
1701}
1702
1703#[cfg(test)]
1704mod tests {
1705    use super::*;
1706    use gpui::TestAppContext;
1707
1708    #[gpui::test(iterations = 10)]
1709    async fn test_language_loading(cx: &mut TestAppContext) {
1710        let languages = LanguageRegistry::test(cx.executor());
1711        let languages = Arc::new(languages);
1712        languages.register_native_grammars([
1713            ("json", tree_sitter_json::language()),
1714            ("rust", tree_sitter_rust::language()),
1715        ]);
1716        languages.register_test_language(LanguageConfig {
1717            name: "JSON".into(),
1718            grammar: Some("json".into()),
1719            matcher: LanguageMatcher {
1720                path_suffixes: vec!["json".into()],
1721                ..Default::default()
1722            },
1723            ..Default::default()
1724        });
1725        languages.register_test_language(LanguageConfig {
1726            name: "Rust".into(),
1727            grammar: Some("rust".into()),
1728            matcher: LanguageMatcher {
1729                path_suffixes: vec!["rs".into()],
1730                ..Default::default()
1731            },
1732            ..Default::default()
1733        });
1734        assert_eq!(
1735            languages.language_names(),
1736            &[
1737                "JSON".to_string(),
1738                "Plain Text".to_string(),
1739                "Rust".to_string(),
1740            ]
1741        );
1742
1743        let rust1 = languages.language_for_name("Rust");
1744        let rust2 = languages.language_for_name("Rust");
1745
1746        // Ensure language is still listed even if it's being loaded.
1747        assert_eq!(
1748            languages.language_names(),
1749            &[
1750                "JSON".to_string(),
1751                "Plain Text".to_string(),
1752                "Rust".to_string(),
1753            ]
1754        );
1755
1756        let (rust1, rust2) = futures::join!(rust1, rust2);
1757        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1758
1759        // Ensure language is still listed even after loading it.
1760        assert_eq!(
1761            languages.language_names(),
1762            &[
1763                "JSON".to_string(),
1764                "Plain Text".to_string(),
1765                "Rust".to_string(),
1766            ]
1767        );
1768
1769        // Loading an unknown language returns an error.
1770        assert!(languages.language_for_name("Unknown").await.is_err());
1771    }
1772}