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