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)]
 666    pub disabled_bracket_ixs: Vec<u16>,
 667    #[serde(default)]
 668    pub word_characters: Override<HashSet<char>>,
 669    #[serde(default)]
 670    pub opt_into_language_servers: Vec<LanguageServerName>,
 671}
 672
 673#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
 674#[serde(untagged)]
 675pub enum Override<T> {
 676    Remove { remove: bool },
 677    Set(T),
 678}
 679
 680impl<T> Default for Override<T> {
 681    fn default() -> Self {
 682        Override::Remove { remove: false }
 683    }
 684}
 685
 686impl<T> Override<T> {
 687    fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
 688        match this {
 689            Some(Self::Set(value)) => Some(value),
 690            Some(Self::Remove { remove: true }) => None,
 691            Some(Self::Remove { remove: false }) | None => original,
 692        }
 693    }
 694}
 695
 696impl Default for LanguageConfig {
 697    fn default() -> Self {
 698        Self {
 699            name: LanguageName::new(""),
 700            code_fence_block_name: None,
 701            grammar: None,
 702            matcher: LanguageMatcher::default(),
 703            brackets: Default::default(),
 704            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
 705            auto_indent_on_paste: None,
 706            increase_indent_pattern: Default::default(),
 707            decrease_indent_pattern: Default::default(),
 708            autoclose_before: Default::default(),
 709            line_comments: Default::default(),
 710            block_comment: Default::default(),
 711            scope_opt_in_language_servers: Default::default(),
 712            overrides: Default::default(),
 713            word_characters: Default::default(),
 714            collapsed_placeholder: Default::default(),
 715            hard_tabs: None,
 716            tab_size: None,
 717            soft_wrap: None,
 718            prettier_parser_name: None,
 719            hidden: false,
 720        }
 721    }
 722}
 723
 724fn auto_indent_using_last_non_empty_line_default() -> bool {
 725    true
 726}
 727
 728fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
 729    let source = Option::<String>::deserialize(d)?;
 730    if let Some(source) = source {
 731        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
 732    } else {
 733        Ok(None)
 734    }
 735}
 736
 737fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
 738    Schema::Object(SchemaObject {
 739        instance_type: Some(InstanceType::String.into()),
 740        ..Default::default()
 741    })
 742}
 743
 744fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
 745where
 746    S: Serializer,
 747{
 748    match regex {
 749        Some(regex) => serializer.serialize_str(regex.as_str()),
 750        None => serializer.serialize_none(),
 751    }
 752}
 753
 754#[doc(hidden)]
 755#[cfg(any(test, feature = "test-support"))]
 756pub struct FakeLspAdapter {
 757    pub name: &'static str,
 758    pub initialization_options: Option<Value>,
 759    pub prettier_plugins: Vec<&'static str>,
 760    pub disk_based_diagnostics_progress_token: Option<String>,
 761    pub disk_based_diagnostics_sources: Vec<String>,
 762    pub language_server_binary: LanguageServerBinary,
 763
 764    pub capabilities: lsp::ServerCapabilities,
 765    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
 766    pub label_for_completion: Option<
 767        Box<
 768            dyn 'static
 769                + Send
 770                + Sync
 771                + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
 772        >,
 773    >,
 774}
 775
 776/// Configuration of handling bracket pairs for a given language.
 777///
 778/// This struct includes settings for defining which pairs of characters are considered brackets and
 779/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
 780#[derive(Clone, Debug, Default, JsonSchema)]
 781pub struct BracketPairConfig {
 782    /// A list of character pairs that should be treated as brackets in the context of a given language.
 783    pub pairs: Vec<BracketPair>,
 784    /// A list of tree-sitter scopes for which a given bracket should not be active.
 785    /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
 786    #[serde(skip)]
 787    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
 788}
 789
 790fn bracket_pair_config_json_schema(gen: &mut SchemaGenerator) -> Schema {
 791    Option::<Vec<BracketPairContent>>::json_schema(gen)
 792}
 793
 794#[derive(Deserialize, JsonSchema)]
 795pub struct BracketPairContent {
 796    #[serde(flatten)]
 797    pub bracket_pair: BracketPair,
 798    #[serde(default)]
 799    pub not_in: Vec<String>,
 800}
 801
 802impl<'de> Deserialize<'de> for BracketPairConfig {
 803    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 804    where
 805        D: Deserializer<'de>,
 806    {
 807        let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
 808        let mut brackets = Vec::with_capacity(result.len());
 809        let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
 810        for entry in result {
 811            brackets.push(entry.bracket_pair);
 812            disabled_scopes_by_bracket_ix.push(entry.not_in);
 813        }
 814
 815        Ok(BracketPairConfig {
 816            pairs: brackets,
 817            disabled_scopes_by_bracket_ix,
 818        })
 819    }
 820}
 821
 822/// Describes a single bracket pair and how an editor should react to e.g. inserting
 823/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
 824#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
 825pub struct BracketPair {
 826    /// Starting substring for a bracket.
 827    pub start: String,
 828    /// Ending substring for a bracket.
 829    pub end: String,
 830    /// True if `end` should be automatically inserted right after `start` characters.
 831    pub close: bool,
 832    /// True if selected text should be surrounded by `start` and `end` characters.
 833    #[serde(default = "default_true")]
 834    pub surround: bool,
 835    /// True if an extra newline should be inserted while the cursor is in the middle
 836    /// of that bracket pair.
 837    pub newline: bool,
 838}
 839
 840#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 841pub(crate) struct LanguageId(usize);
 842
 843impl LanguageId {
 844    pub(crate) fn new() -> Self {
 845        Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
 846    }
 847}
 848
 849pub struct Language {
 850    pub(crate) id: LanguageId,
 851    pub(crate) config: LanguageConfig,
 852    pub(crate) grammar: Option<Arc<Grammar>>,
 853    pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
 854    pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
 855}
 856
 857#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 858pub struct GrammarId(pub usize);
 859
 860impl GrammarId {
 861    pub(crate) fn new() -> Self {
 862        Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
 863    }
 864}
 865
 866pub struct Grammar {
 867    id: GrammarId,
 868    pub ts_language: tree_sitter::Language,
 869    pub(crate) error_query: Query,
 870    pub(crate) highlights_query: Option<Query>,
 871    pub(crate) brackets_config: Option<BracketConfig>,
 872    pub(crate) redactions_config: Option<RedactionConfig>,
 873    pub(crate) runnable_config: Option<RunnableConfig>,
 874    pub(crate) indents_config: Option<IndentConfig>,
 875    pub outline_config: Option<OutlineConfig>,
 876    pub text_object_config: Option<TextObjectConfig>,
 877    pub embedding_config: Option<EmbeddingConfig>,
 878    pub(crate) injection_config: Option<InjectionConfig>,
 879    pub(crate) override_config: Option<OverrideConfig>,
 880    pub(crate) highlight_map: Mutex<HighlightMap>,
 881}
 882
 883struct IndentConfig {
 884    query: Query,
 885    indent_capture_ix: u32,
 886    start_capture_ix: Option<u32>,
 887    end_capture_ix: Option<u32>,
 888    outdent_capture_ix: Option<u32>,
 889}
 890
 891pub struct OutlineConfig {
 892    pub query: Query,
 893    pub item_capture_ix: u32,
 894    pub name_capture_ix: u32,
 895    pub context_capture_ix: Option<u32>,
 896    pub extra_context_capture_ix: Option<u32>,
 897    pub open_capture_ix: Option<u32>,
 898    pub close_capture_ix: Option<u32>,
 899    pub annotation_capture_ix: Option<u32>,
 900}
 901
 902#[derive(Debug, Clone, Copy, PartialEq)]
 903pub enum TextObject {
 904    InsideFunction,
 905    AroundFunction,
 906    InsideClass,
 907    AroundClass,
 908    InsideComment,
 909    AroundComment,
 910}
 911
 912impl TextObject {
 913    pub fn from_capture_name(name: &str) -> Option<TextObject> {
 914        match name {
 915            "function.inside" => Some(TextObject::InsideFunction),
 916            "function.around" => Some(TextObject::AroundFunction),
 917            "class.inside" => Some(TextObject::InsideClass),
 918            "class.around" => Some(TextObject::AroundClass),
 919            "comment.inside" => Some(TextObject::InsideComment),
 920            "comment.around" => Some(TextObject::AroundComment),
 921            _ => None,
 922        }
 923    }
 924
 925    pub fn around(&self) -> Option<Self> {
 926        match self {
 927            TextObject::InsideFunction => Some(TextObject::AroundFunction),
 928            TextObject::InsideClass => Some(TextObject::AroundClass),
 929            TextObject::InsideComment => Some(TextObject::AroundComment),
 930            _ => None,
 931        }
 932    }
 933}
 934
 935pub struct TextObjectConfig {
 936    pub query: Query,
 937    pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
 938}
 939
 940#[derive(Debug)]
 941pub struct EmbeddingConfig {
 942    pub query: Query,
 943    pub item_capture_ix: u32,
 944    pub name_capture_ix: Option<u32>,
 945    pub context_capture_ix: Option<u32>,
 946    pub collapse_capture_ix: Option<u32>,
 947    pub keep_capture_ix: Option<u32>,
 948}
 949
 950struct InjectionConfig {
 951    query: Query,
 952    content_capture_ix: u32,
 953    language_capture_ix: Option<u32>,
 954    patterns: Vec<InjectionPatternConfig>,
 955}
 956
 957struct RedactionConfig {
 958    pub query: Query,
 959    pub redaction_capture_ix: u32,
 960}
 961
 962#[derive(Clone, Debug, PartialEq)]
 963enum RunnableCapture {
 964    Named(SharedString),
 965    Run,
 966}
 967
 968struct RunnableConfig {
 969    pub query: Query,
 970    /// A mapping from capture indice to capture kind
 971    pub extra_captures: Vec<RunnableCapture>,
 972}
 973
 974struct OverrideConfig {
 975    query: Query,
 976    values: HashMap<u32, OverrideEntry>,
 977}
 978
 979#[derive(Debug)]
 980struct OverrideEntry {
 981    name: String,
 982    range_is_inclusive: bool,
 983    value: LanguageConfigOverride,
 984}
 985
 986#[derive(Default, Clone)]
 987struct InjectionPatternConfig {
 988    language: Option<Box<str>>,
 989    combined: bool,
 990}
 991
 992struct BracketConfig {
 993    query: Query,
 994    open_capture_ix: u32,
 995    close_capture_ix: u32,
 996}
 997
 998impl Language {
 999    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1000        Self::new_with_id(LanguageId::new(), config, ts_language)
1001    }
1002
1003    fn new_with_id(
1004        id: LanguageId,
1005        config: LanguageConfig,
1006        ts_language: Option<tree_sitter::Language>,
1007    ) -> Self {
1008        Self {
1009            id,
1010            config,
1011            grammar: ts_language.map(|ts_language| {
1012                Arc::new(Grammar {
1013                    id: GrammarId::new(),
1014                    highlights_query: None,
1015                    brackets_config: None,
1016                    outline_config: None,
1017                    text_object_config: None,
1018                    embedding_config: None,
1019                    indents_config: None,
1020                    injection_config: None,
1021                    override_config: None,
1022                    redactions_config: None,
1023                    runnable_config: None,
1024                    error_query: Query::new(&ts_language, "(ERROR) @error").unwrap(),
1025                    ts_language,
1026                    highlight_map: Default::default(),
1027                })
1028            }),
1029            context_provider: None,
1030            toolchain: None,
1031        }
1032    }
1033
1034    pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1035        self.context_provider = provider;
1036        self
1037    }
1038
1039    pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1040        self.toolchain = provider;
1041        self
1042    }
1043
1044    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1045        if let Some(query) = queries.highlights {
1046            self = self
1047                .with_highlights_query(query.as_ref())
1048                .context("Error loading highlights query")?;
1049        }
1050        if let Some(query) = queries.brackets {
1051            self = self
1052                .with_brackets_query(query.as_ref())
1053                .context("Error loading brackets query")?;
1054        }
1055        if let Some(query) = queries.indents {
1056            self = self
1057                .with_indents_query(query.as_ref())
1058                .context("Error loading indents query")?;
1059        }
1060        if let Some(query) = queries.outline {
1061            self = self
1062                .with_outline_query(query.as_ref())
1063                .context("Error loading outline query")?;
1064        }
1065        if let Some(query) = queries.embedding {
1066            self = self
1067                .with_embedding_query(query.as_ref())
1068                .context("Error loading embedding query")?;
1069        }
1070        if let Some(query) = queries.injections {
1071            self = self
1072                .with_injection_query(query.as_ref())
1073                .context("Error loading injection query")?;
1074        }
1075        if let Some(query) = queries.overrides {
1076            self = self
1077                .with_override_query(query.as_ref())
1078                .context("Error loading override query")?;
1079        }
1080        if let Some(query) = queries.redactions {
1081            self = self
1082                .with_redaction_query(query.as_ref())
1083                .context("Error loading redaction query")?;
1084        }
1085        if let Some(query) = queries.runnables {
1086            self = self
1087                .with_runnable_query(query.as_ref())
1088                .context("Error loading runnables query")?;
1089        }
1090        if let Some(query) = queries.text_objects {
1091            self = self
1092                .with_text_object_query(query.as_ref())
1093                .context("Error loading textobject query")?;
1094        }
1095        Ok(self)
1096    }
1097
1098    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1099        let grammar = self
1100            .grammar_mut()
1101            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1102        grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1103        Ok(self)
1104    }
1105
1106    pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1107        let grammar = self
1108            .grammar_mut()
1109            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1110
1111        let query = Query::new(&grammar.ts_language, source)?;
1112        let mut extra_captures = Vec::with_capacity(query.capture_names().len());
1113
1114        for name in query.capture_names().iter() {
1115            let kind = if *name == "run" {
1116                RunnableCapture::Run
1117            } else {
1118                RunnableCapture::Named(name.to_string().into())
1119            };
1120            extra_captures.push(kind);
1121        }
1122
1123        grammar.runnable_config = Some(RunnableConfig {
1124            extra_captures,
1125            query,
1126        });
1127
1128        Ok(self)
1129    }
1130
1131    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1132        let grammar = self
1133            .grammar_mut()
1134            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1135        let query = Query::new(&grammar.ts_language, source)?;
1136        let mut item_capture_ix = None;
1137        let mut name_capture_ix = None;
1138        let mut context_capture_ix = None;
1139        let mut extra_context_capture_ix = None;
1140        let mut open_capture_ix = None;
1141        let mut close_capture_ix = None;
1142        let mut annotation_capture_ix = None;
1143        get_capture_indices(
1144            &query,
1145            &mut [
1146                ("item", &mut item_capture_ix),
1147                ("name", &mut name_capture_ix),
1148                ("context", &mut context_capture_ix),
1149                ("context.extra", &mut extra_context_capture_ix),
1150                ("open", &mut open_capture_ix),
1151                ("close", &mut close_capture_ix),
1152                ("annotation", &mut annotation_capture_ix),
1153            ],
1154        );
1155        if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1156            grammar.outline_config = Some(OutlineConfig {
1157                query,
1158                item_capture_ix,
1159                name_capture_ix,
1160                context_capture_ix,
1161                extra_context_capture_ix,
1162                open_capture_ix,
1163                close_capture_ix,
1164                annotation_capture_ix,
1165            });
1166        }
1167        Ok(self)
1168    }
1169
1170    pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1171        let grammar = self
1172            .grammar_mut()
1173            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1174        let query = Query::new(&grammar.ts_language, source)?;
1175
1176        let mut text_objects_by_capture_ix = Vec::new();
1177        for (ix, name) in query.capture_names().iter().enumerate() {
1178            if let Some(text_object) = TextObject::from_capture_name(name) {
1179                text_objects_by_capture_ix.push((ix as u32, text_object));
1180            }
1181        }
1182
1183        grammar.text_object_config = Some(TextObjectConfig {
1184            query,
1185            text_objects_by_capture_ix,
1186        });
1187        Ok(self)
1188    }
1189
1190    pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1191        let grammar = self
1192            .grammar_mut()
1193            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1194        let query = Query::new(&grammar.ts_language, source)?;
1195        let mut item_capture_ix = None;
1196        let mut name_capture_ix = None;
1197        let mut context_capture_ix = None;
1198        let mut collapse_capture_ix = None;
1199        let mut keep_capture_ix = None;
1200        get_capture_indices(
1201            &query,
1202            &mut [
1203                ("item", &mut item_capture_ix),
1204                ("name", &mut name_capture_ix),
1205                ("context", &mut context_capture_ix),
1206                ("keep", &mut keep_capture_ix),
1207                ("collapse", &mut collapse_capture_ix),
1208            ],
1209        );
1210        if let Some(item_capture_ix) = item_capture_ix {
1211            grammar.embedding_config = Some(EmbeddingConfig {
1212                query,
1213                item_capture_ix,
1214                name_capture_ix,
1215                context_capture_ix,
1216                collapse_capture_ix,
1217                keep_capture_ix,
1218            });
1219        }
1220        Ok(self)
1221    }
1222
1223    pub fn with_brackets_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 open_capture_ix = None;
1229        let mut close_capture_ix = None;
1230        get_capture_indices(
1231            &query,
1232            &mut [
1233                ("open", &mut open_capture_ix),
1234                ("close", &mut close_capture_ix),
1235            ],
1236        );
1237        if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1238            grammar.brackets_config = Some(BracketConfig {
1239                query,
1240                open_capture_ix,
1241                close_capture_ix,
1242            });
1243        }
1244        Ok(self)
1245    }
1246
1247    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1248        let grammar = self
1249            .grammar_mut()
1250            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1251        let query = Query::new(&grammar.ts_language, source)?;
1252        let mut indent_capture_ix = None;
1253        let mut start_capture_ix = None;
1254        let mut end_capture_ix = None;
1255        let mut outdent_capture_ix = None;
1256        get_capture_indices(
1257            &query,
1258            &mut [
1259                ("indent", &mut indent_capture_ix),
1260                ("start", &mut start_capture_ix),
1261                ("end", &mut end_capture_ix),
1262                ("outdent", &mut outdent_capture_ix),
1263            ],
1264        );
1265        if let Some(indent_capture_ix) = indent_capture_ix {
1266            grammar.indents_config = Some(IndentConfig {
1267                query,
1268                indent_capture_ix,
1269                start_capture_ix,
1270                end_capture_ix,
1271                outdent_capture_ix,
1272            });
1273        }
1274        Ok(self)
1275    }
1276
1277    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1278        let grammar = self
1279            .grammar_mut()
1280            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1281        let query = Query::new(&grammar.ts_language, source)?;
1282        let mut language_capture_ix = None;
1283        let mut injection_language_capture_ix = None;
1284        let mut content_capture_ix = None;
1285        let mut injection_content_capture_ix = None;
1286        get_capture_indices(
1287            &query,
1288            &mut [
1289                ("language", &mut language_capture_ix),
1290                ("injection.language", &mut injection_language_capture_ix),
1291                ("content", &mut content_capture_ix),
1292                ("injection.content", &mut injection_content_capture_ix),
1293            ],
1294        );
1295        language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1296            (None, Some(ix)) => Some(ix),
1297            (Some(_), Some(_)) => {
1298                return Err(anyhow!(
1299                    "both language and injection.language captures are present"
1300                ));
1301            }
1302            _ => language_capture_ix,
1303        };
1304        content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1305            (None, Some(ix)) => Some(ix),
1306            (Some(_), Some(_)) => {
1307                return Err(anyhow!(
1308                    "both content and injection.content captures are present"
1309                ));
1310            }
1311            _ => content_capture_ix,
1312        };
1313        let patterns = (0..query.pattern_count())
1314            .map(|ix| {
1315                let mut config = InjectionPatternConfig::default();
1316                for setting in query.property_settings(ix) {
1317                    match setting.key.as_ref() {
1318                        "language" | "injection.language" => {
1319                            config.language.clone_from(&setting.value);
1320                        }
1321                        "combined" | "injection.combined" => {
1322                            config.combined = true;
1323                        }
1324                        _ => {}
1325                    }
1326                }
1327                config
1328            })
1329            .collect();
1330        if let Some(content_capture_ix) = content_capture_ix {
1331            grammar.injection_config = Some(InjectionConfig {
1332                query,
1333                language_capture_ix,
1334                content_capture_ix,
1335                patterns,
1336            });
1337        }
1338        Ok(self)
1339    }
1340
1341    pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1342        let query = {
1343            let grammar = self
1344                .grammar
1345                .as_ref()
1346                .ok_or_else(|| anyhow!("no grammar for language"))?;
1347            Query::new(&grammar.ts_language, source)?
1348        };
1349
1350        let mut override_configs_by_id = HashMap::default();
1351        for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1352            let mut range_is_inclusive = false;
1353            if name.starts_with('_') {
1354                continue;
1355            }
1356            if let Some(prefix) = name.strip_suffix(".inclusive") {
1357                name = prefix;
1358                range_is_inclusive = true;
1359            }
1360
1361            let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1362            for server_name in &value.opt_into_language_servers {
1363                if !self
1364                    .config
1365                    .scope_opt_in_language_servers
1366                    .contains(server_name)
1367                {
1368                    util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1369                }
1370            }
1371
1372            override_configs_by_id.insert(
1373                ix as u32,
1374                OverrideEntry {
1375                    name: name.to_string(),
1376                    range_is_inclusive,
1377                    value,
1378                },
1379            );
1380        }
1381
1382        let referenced_override_names = self.config.overrides.keys().chain(
1383            self.config
1384                .brackets
1385                .disabled_scopes_by_bracket_ix
1386                .iter()
1387                .flatten(),
1388        );
1389
1390        for referenced_name in referenced_override_names {
1391            if !override_configs_by_id
1392                .values()
1393                .any(|entry| entry.name == *referenced_name)
1394            {
1395                Err(anyhow!(
1396                    "language {:?} has overrides in config not in query: {referenced_name:?}",
1397                    self.config.name
1398                ))?;
1399            }
1400        }
1401
1402        for entry in override_configs_by_id.values_mut() {
1403            entry.value.disabled_bracket_ixs = self
1404                .config
1405                .brackets
1406                .disabled_scopes_by_bracket_ix
1407                .iter()
1408                .enumerate()
1409                .filter_map(|(ix, disabled_scope_names)| {
1410                    if disabled_scope_names.contains(&entry.name) {
1411                        Some(ix as u16)
1412                    } else {
1413                        None
1414                    }
1415                })
1416                .collect();
1417        }
1418
1419        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1420
1421        let grammar = self
1422            .grammar_mut()
1423            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1424        grammar.override_config = Some(OverrideConfig {
1425            query,
1426            values: override_configs_by_id,
1427        });
1428        Ok(self)
1429    }
1430
1431    pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1432        let grammar = self
1433            .grammar_mut()
1434            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1435
1436        let query = Query::new(&grammar.ts_language, source)?;
1437        let mut redaction_capture_ix = None;
1438        get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1439
1440        if let Some(redaction_capture_ix) = redaction_capture_ix {
1441            grammar.redactions_config = Some(RedactionConfig {
1442                query,
1443                redaction_capture_ix,
1444            });
1445        }
1446
1447        Ok(self)
1448    }
1449
1450    fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1451        Arc::get_mut(self.grammar.as_mut()?)
1452    }
1453
1454    pub fn name(&self) -> LanguageName {
1455        self.config.name.clone()
1456    }
1457
1458    pub fn code_fence_block_name(&self) -> Arc<str> {
1459        self.config
1460            .code_fence_block_name
1461            .clone()
1462            .unwrap_or_else(|| self.config.name.0.to_lowercase().into())
1463    }
1464
1465    pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1466        self.context_provider.clone()
1467    }
1468
1469    pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1470        self.toolchain.clone()
1471    }
1472
1473    pub fn highlight_text<'a>(
1474        self: &'a Arc<Self>,
1475        text: &'a Rope,
1476        range: Range<usize>,
1477    ) -> Vec<(Range<usize>, HighlightId)> {
1478        let mut result = Vec::new();
1479        if let Some(grammar) = &self.grammar {
1480            let tree = grammar.parse_text(text, None);
1481            let captures =
1482                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1483                    grammar.highlights_query.as_ref()
1484                });
1485            let highlight_maps = vec![grammar.highlight_map()];
1486            let mut offset = 0;
1487            for chunk in
1488                BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1489            {
1490                let end_offset = offset + chunk.text.len();
1491                if let Some(highlight_id) = chunk.syntax_highlight_id {
1492                    if !highlight_id.is_default() {
1493                        result.push((offset..end_offset, highlight_id));
1494                    }
1495                }
1496                offset = end_offset;
1497            }
1498        }
1499        result
1500    }
1501
1502    pub fn path_suffixes(&self) -> &[String] {
1503        &self.config.matcher.path_suffixes
1504    }
1505
1506    pub fn should_autoclose_before(&self, c: char) -> bool {
1507        c.is_whitespace() || self.config.autoclose_before.contains(c)
1508    }
1509
1510    pub fn set_theme(&self, theme: &SyntaxTheme) {
1511        if let Some(grammar) = self.grammar.as_ref() {
1512            if let Some(highlights_query) = &grammar.highlights_query {
1513                *grammar.highlight_map.lock() =
1514                    HighlightMap::new(highlights_query.capture_names(), theme);
1515            }
1516        }
1517    }
1518
1519    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1520        self.grammar.as_ref()
1521    }
1522
1523    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1524        LanguageScope {
1525            language: self.clone(),
1526            override_id: None,
1527        }
1528    }
1529
1530    pub fn lsp_id(&self) -> String {
1531        self.config.name.lsp_id()
1532    }
1533
1534    pub fn prettier_parser_name(&self) -> Option<&str> {
1535        self.config.prettier_parser_name.as_deref()
1536    }
1537
1538    pub fn config(&self) -> &LanguageConfig {
1539        &self.config
1540    }
1541}
1542
1543impl LanguageScope {
1544    pub fn path_suffixes(&self) -> &[String] {
1545        &self.language.path_suffixes()
1546    }
1547
1548    pub fn language_name(&self) -> LanguageName {
1549        self.language.config.name.clone()
1550    }
1551
1552    pub fn collapsed_placeholder(&self) -> &str {
1553        self.language.config.collapsed_placeholder.as_ref()
1554    }
1555
1556    /// Returns line prefix that is inserted in e.g. line continuations or
1557    /// in `toggle comments` action.
1558    pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1559        Override::as_option(
1560            self.config_override().map(|o| &o.line_comments),
1561            Some(&self.language.config.line_comments),
1562        )
1563        .map_or(&[] as &[_], |e| e.as_slice())
1564    }
1565
1566    pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1567        Override::as_option(
1568            self.config_override().map(|o| &o.block_comment),
1569            self.language.config.block_comment.as_ref(),
1570        )
1571        .map(|e| (&e.0, &e.1))
1572    }
1573
1574    /// Returns a list of language-specific word characters.
1575    ///
1576    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1577    /// the purpose of actions like 'move to next word end` or whole-word search.
1578    /// It additionally accounts for language's additional word characters.
1579    pub fn word_characters(&self) -> Option<&HashSet<char>> {
1580        Override::as_option(
1581            self.config_override().map(|o| &o.word_characters),
1582            Some(&self.language.config.word_characters),
1583        )
1584    }
1585
1586    /// Returns a list of bracket pairs for a given language with an additional
1587    /// piece of information about whether the particular bracket pair is currently active for a given language.
1588    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1589        let mut disabled_ids = self
1590            .config_override()
1591            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1592        self.language
1593            .config
1594            .brackets
1595            .pairs
1596            .iter()
1597            .enumerate()
1598            .map(move |(ix, bracket)| {
1599                let mut is_enabled = true;
1600                if let Some(next_disabled_ix) = disabled_ids.first() {
1601                    if ix == *next_disabled_ix as usize {
1602                        disabled_ids = &disabled_ids[1..];
1603                        is_enabled = false;
1604                    }
1605                }
1606                (bracket, is_enabled)
1607            })
1608    }
1609
1610    pub fn should_autoclose_before(&self, c: char) -> bool {
1611        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1612    }
1613
1614    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1615        let config = &self.language.config;
1616        let opt_in_servers = &config.scope_opt_in_language_servers;
1617        if opt_in_servers.iter().any(|o| *o == *name) {
1618            if let Some(over) = self.config_override() {
1619                over.opt_into_language_servers.iter().any(|o| *o == *name)
1620            } else {
1621                false
1622            }
1623        } else {
1624            true
1625        }
1626    }
1627
1628    pub fn override_name(&self) -> Option<&str> {
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.name.as_str())
1633    }
1634
1635    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1636        let id = self.override_id?;
1637        let grammar = self.language.grammar.as_ref()?;
1638        let override_config = grammar.override_config.as_ref()?;
1639        override_config.values.get(&id).map(|e| &e.value)
1640    }
1641}
1642
1643impl Hash for Language {
1644    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1645        self.id.hash(state)
1646    }
1647}
1648
1649impl PartialEq for Language {
1650    fn eq(&self, other: &Self) -> bool {
1651        self.id.eq(&other.id)
1652    }
1653}
1654
1655impl Eq for Language {}
1656
1657impl Debug for Language {
1658    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1659        f.debug_struct("Language")
1660            .field("name", &self.config.name)
1661            .finish()
1662    }
1663}
1664
1665impl Grammar {
1666    pub fn id(&self) -> GrammarId {
1667        self.id
1668    }
1669
1670    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1671        with_parser(|parser| {
1672            parser
1673                .set_language(&self.ts_language)
1674                .expect("incompatible grammar");
1675            let mut chunks = text.chunks_in_range(0..text.len());
1676            parser
1677                .parse_with(
1678                    &mut move |offset, _| {
1679                        chunks.seek(offset);
1680                        chunks.next().unwrap_or("").as_bytes()
1681                    },
1682                    old_tree.as_ref(),
1683                )
1684                .unwrap()
1685        })
1686    }
1687
1688    pub fn highlight_map(&self) -> HighlightMap {
1689        self.highlight_map.lock().clone()
1690    }
1691
1692    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1693        let capture_id = self
1694            .highlights_query
1695            .as_ref()?
1696            .capture_index_for_name(name)?;
1697        Some(self.highlight_map.lock().get(capture_id))
1698    }
1699}
1700
1701impl CodeLabel {
1702    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1703        let mut result = Self {
1704            runs: Vec::new(),
1705            filter_range: 0..text.len(),
1706            text,
1707        };
1708        if let Some(filter_text) = filter_text {
1709            if let Some(ix) = result.text.find(filter_text) {
1710                result.filter_range = ix..ix + filter_text.len();
1711            }
1712        }
1713        result
1714    }
1715
1716    pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
1717        let start_ix = self.text.len();
1718        self.text.push_str(text);
1719        let end_ix = self.text.len();
1720        if let Some(highlight) = highlight {
1721            self.runs.push((start_ix..end_ix, highlight));
1722        }
1723    }
1724
1725    pub fn text(&self) -> &str {
1726        self.text.as_str()
1727    }
1728
1729    pub fn filter_text(&self) -> &str {
1730        &self.text[self.filter_range.clone()]
1731    }
1732}
1733
1734impl From<String> for CodeLabel {
1735    fn from(value: String) -> Self {
1736        Self::plain(value, None)
1737    }
1738}
1739
1740impl From<&str> for CodeLabel {
1741    fn from(value: &str) -> Self {
1742        Self::plain(value.to_string(), None)
1743    }
1744}
1745
1746impl Ord for LanguageMatcher {
1747    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1748        self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1749            self.first_line_pattern
1750                .as_ref()
1751                .map(Regex::as_str)
1752                .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1753        })
1754    }
1755}
1756
1757impl PartialOrd for LanguageMatcher {
1758    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1759        Some(self.cmp(other))
1760    }
1761}
1762
1763impl Eq for LanguageMatcher {}
1764
1765impl PartialEq for LanguageMatcher {
1766    fn eq(&self, other: &Self) -> bool {
1767        self.path_suffixes == other.path_suffixes
1768            && self.first_line_pattern.as_ref().map(Regex::as_str)
1769                == other.first_line_pattern.as_ref().map(Regex::as_str)
1770    }
1771}
1772
1773#[cfg(any(test, feature = "test-support"))]
1774impl Default for FakeLspAdapter {
1775    fn default() -> Self {
1776        Self {
1777            name: "the-fake-language-server",
1778            capabilities: lsp::LanguageServer::full_capabilities(),
1779            initializer: None,
1780            disk_based_diagnostics_progress_token: None,
1781            initialization_options: None,
1782            disk_based_diagnostics_sources: Vec::new(),
1783            prettier_plugins: Vec::new(),
1784            language_server_binary: LanguageServerBinary {
1785                path: "/the/fake/lsp/path".into(),
1786                arguments: vec![],
1787                env: Default::default(),
1788            },
1789            label_for_completion: None,
1790        }
1791    }
1792}
1793
1794#[cfg(any(test, feature = "test-support"))]
1795#[async_trait(?Send)]
1796impl LspAdapter for FakeLspAdapter {
1797    fn name(&self) -> LanguageServerName {
1798        LanguageServerName(self.name.into())
1799    }
1800
1801    async fn check_if_user_installed(
1802        &self,
1803        _: &dyn LspAdapterDelegate,
1804        _: Arc<dyn LanguageToolchainStore>,
1805        _: &AsyncAppContext,
1806    ) -> Option<LanguageServerBinary> {
1807        Some(self.language_server_binary.clone())
1808    }
1809
1810    fn get_language_server_command<'a>(
1811        self: Arc<Self>,
1812        _: Arc<dyn LspAdapterDelegate>,
1813        _: Arc<dyn LanguageToolchainStore>,
1814        _: LanguageServerBinaryOptions,
1815        _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
1816        _: &'a mut AsyncAppContext,
1817    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
1818        async move { Ok(self.language_server_binary.clone()) }.boxed_local()
1819    }
1820
1821    async fn fetch_latest_server_version(
1822        &self,
1823        _: &dyn LspAdapterDelegate,
1824    ) -> Result<Box<dyn 'static + Send + Any>> {
1825        unreachable!();
1826    }
1827
1828    async fn fetch_server_binary(
1829        &self,
1830        _: Box<dyn 'static + Send + Any>,
1831        _: PathBuf,
1832        _: &dyn LspAdapterDelegate,
1833    ) -> Result<LanguageServerBinary> {
1834        unreachable!();
1835    }
1836
1837    async fn cached_server_binary(
1838        &self,
1839        _: PathBuf,
1840        _: &dyn LspAdapterDelegate,
1841    ) -> Option<LanguageServerBinary> {
1842        unreachable!();
1843    }
1844
1845    fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1846
1847    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1848        self.disk_based_diagnostics_sources.clone()
1849    }
1850
1851    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1852        self.disk_based_diagnostics_progress_token.clone()
1853    }
1854
1855    async fn initialization_options(
1856        self: Arc<Self>,
1857        _: &Arc<dyn LspAdapterDelegate>,
1858    ) -> Result<Option<Value>> {
1859        Ok(self.initialization_options.clone())
1860    }
1861
1862    async fn label_for_completion(
1863        &self,
1864        item: &lsp::CompletionItem,
1865        language: &Arc<Language>,
1866    ) -> Option<CodeLabel> {
1867        let label_for_completion = self.label_for_completion.as_ref()?;
1868        label_for_completion(item, language)
1869    }
1870}
1871
1872fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1873    for (ix, name) in query.capture_names().iter().enumerate() {
1874        for (capture_name, index) in captures.iter_mut() {
1875            if capture_name == name {
1876                **index = Some(ix as u32);
1877                break;
1878            }
1879        }
1880    }
1881}
1882
1883pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1884    lsp::Position::new(point.row, point.column)
1885}
1886
1887pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1888    Unclipped(PointUtf16::new(point.line, point.character))
1889}
1890
1891pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
1892    if range.start > range.end {
1893        Err(anyhow!(
1894            "Inverted range provided to an LSP request: {:?}-{:?}",
1895            range.start,
1896            range.end
1897        ))
1898    } else {
1899        Ok(lsp::Range {
1900            start: point_to_lsp(range.start),
1901            end: point_to_lsp(range.end),
1902        })
1903    }
1904}
1905
1906pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1907    let mut start = point_from_lsp(range.start);
1908    let mut end = point_from_lsp(range.end);
1909    if start > end {
1910        log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
1911        mem::swap(&mut start, &mut end);
1912    }
1913    start..end
1914}
1915
1916#[cfg(test)]
1917mod tests {
1918    use super::*;
1919    use gpui::TestAppContext;
1920
1921    #[gpui::test(iterations = 10)]
1922    async fn test_language_loading(cx: &mut TestAppContext) {
1923        let languages = LanguageRegistry::test(cx.executor());
1924        let languages = Arc::new(languages);
1925        languages.register_native_grammars([
1926            ("json", tree_sitter_json::LANGUAGE),
1927            ("rust", tree_sitter_rust::LANGUAGE),
1928        ]);
1929        languages.register_test_language(LanguageConfig {
1930            name: "JSON".into(),
1931            grammar: Some("json".into()),
1932            matcher: LanguageMatcher {
1933                path_suffixes: vec!["json".into()],
1934                ..Default::default()
1935            },
1936            ..Default::default()
1937        });
1938        languages.register_test_language(LanguageConfig {
1939            name: "Rust".into(),
1940            grammar: Some("rust".into()),
1941            matcher: LanguageMatcher {
1942                path_suffixes: vec!["rs".into()],
1943                ..Default::default()
1944            },
1945            ..Default::default()
1946        });
1947        assert_eq!(
1948            languages.language_names(),
1949            &[
1950                "JSON".to_string(),
1951                "Plain Text".to_string(),
1952                "Rust".to_string(),
1953            ]
1954        );
1955
1956        let rust1 = languages.language_for_name("Rust");
1957        let rust2 = languages.language_for_name("Rust");
1958
1959        // Ensure language is still listed even if it's being loaded.
1960        assert_eq!(
1961            languages.language_names(),
1962            &[
1963                "JSON".to_string(),
1964                "Plain Text".to_string(),
1965                "Rust".to_string(),
1966            ]
1967        );
1968
1969        let (rust1, rust2) = futures::join!(rust1, rust2);
1970        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1971
1972        // Ensure language is still listed even after loading it.
1973        assert_eq!(
1974            languages.language_names(),
1975            &[
1976                "JSON".to_string(),
1977                "Plain Text".to_string(),
1978                "Rust".to_string(),
1979            ]
1980        );
1981
1982        // Loading an unknown language returns an error.
1983        assert!(languages.language_for_name("Unknown").await.is_err());
1984    }
1985}