language.rs

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