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