Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T04:59:51.284Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

language.rs

1978 lines · 70.8 KB · rust
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 available_languages;
10mod buffer;
11mod diagnostic;
12mod diagnostic_set;
13mod file_content;
14mod language_registry;
15
16pub mod language_settings;
17mod manifest;
18pub mod modeline;
19mod outline;
20pub mod proto;
21mod runnable;
22mod syntax_map;
23mod task_context;
24mod text_diff;
25mod toolchain;
26
27#[cfg(test)]
28pub mod buffer_tests;
29
30pub use crate::language_settings::{
31    AutoIndentMode, EditPredictionPromptFormat, EditPredictionsMode, IndentGuideSettings,
32    ZetaVersion,
33};
34use anyhow::{Context as _, Result};
35use async_trait::async_trait;
36use collections::{HashMap, HashSet};
37use futures::Future;
38use futures::future::LocalBoxFuture;
39use futures::lock::OwnedMutexGuard;
40use gpui::{App, AsyncApp, Entity};
41use http_client::HttpClient;
42
43pub use language_core::{
44    SymbolKind,
45    highlight_map::{HighlightId, HighlightMap},
46};
47
48use futures::future::FutureExt as _;
49pub use language_core::{
50    BlockCommentConfig, BracketPair, BracketPairConfig, BracketPairContent, BracketsConfig,
51    BracketsPatternConfig, CodeLabel, CodeLabelBuilder, DebugVariablesConfig, DebuggerTextObject,
52    DecreaseIndentConfig, Grammar, GrammarId, HighlightsConfig, IndentConfig, InjectionConfig,
53    InjectionPatternConfig, JsxTagAutoCloseConfig, LanguageConfig, LanguageConfigOverride,
54    LanguageId, LanguageMatcher, OrderedListConfig, OutlineConfig, Override, OverrideConfig,
55    OverrideEntry, RedactionConfig, RunnableCapture, RunnableConfig, SoftWrap, Symbol,
56    TaskListConfig, TextObject, TextObjectConfig, WrapCharactersConfig, default_true,
57    deserialize_regex, deserialize_regex_vec, regex_json_schema, regex_vec_json_schema,
58    serialize_regex,
59};
60pub use language_registry::{
61    LanguageName, LanguageServerStatusUpdate, LoadedLanguage, ServerHealth,
62};
63use lsp::{
64    CodeActionKind, InitializeParams, LanguageServerBinary, LanguageServerBinaryOptions, Uri,
65};
66pub use manifest::{ManifestDelegate, ManifestName, ManifestProvider, ManifestQuery};
67pub use modeline::{ModelineSettings, parse_modeline};
68use parking_lot::Mutex;
69use regex::Regex;
70pub use runnable::{ResolvedRunnable, RunnableMatchCapture, RunnableRange, RunnableResolver};
71use semver::Version;
72use serde_json::Value;
73use settings::WorktreeId;
74use std::{
75    ffi::OsStr,
76    fmt::Debug,
77    hash::Hash,
78    mem,
79    ops::{DerefMut, Range},
80    path::{Path, PathBuf},
81    str,
82    sync::{Arc, LazyLock},
83};
84use syntax_map::{QueryCursorHandle, SyntaxSnapshot};
85use task::RunnableTag;
86pub use task_context::{ContextLocation, ContextProvider};
87pub use text_diff::{
88    DiffOptions, apply_diff_patch, apply_reversed_diff_patch, char_diff, line_diff, text_diff,
89    text_diff_with_options, unified_diff, unified_diff_with_context, unified_diff_with_offsets,
90    word_diff_ranges,
91};
92use theme::SyntaxTheme;
93pub use toolchain::{
94    LanguageToolchainStore, LocalLanguageToolchainStore, Toolchain, ToolchainList, ToolchainLister,
95    ToolchainMetadata, ToolchainScope,
96};
97use tree_sitter::{self, QueryCursor, WasmStore, wasmtime};
98use util::rel_path::RelPath;
99
100pub use available_languages::AvailableLanguage;
101pub use buffer::Operation;
102pub use buffer::*;
103pub use diagnostic::{Diagnostic, DiagnosticSourceKind};
104pub use diagnostic_set::{DiagnosticEntry, DiagnosticEntryRef, DiagnosticGroup};
105pub use file_content::{ByteContent, FILE_ANALYSIS_BYTES, analyze_byte_content};
106pub use language_registry::{
107    BinaryStatus, LanguageNotFound, LanguageQueries, LanguageRegistry, QUERY_FILENAME_PREFIXES,
108};
109pub use lsp::{LanguageServerId, LanguageServerName};
110pub use outline::*;
111pub use syntax_map::{
112    OwnedSyntaxLayer, SyntaxLayer, SyntaxMapMatches, ToTreeSitterPoint, TreeSitterOptions,
113};
114pub use text::{AnchorRangeExt, LineEnding};
115pub use tree_sitter::{Node, Parser, QueryCapture, Tree, TreeCursor};
116
117pub(crate) fn to_settings_soft_wrap(value: language_core::SoftWrap) -> settings::SoftWrap {
118    match value {
119        language_core::SoftWrap::None => settings::SoftWrap::None,
120        language_core::SoftWrap::PreferLine => settings::SoftWrap::PreferLine,
121        language_core::SoftWrap::EditorWidth => settings::SoftWrap::EditorWidth,
122        language_core::SoftWrap::Bounded => settings::SoftWrap::Bounded,
123    }
124}
125
126static QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Mutex::new(vec![]);
127static PARSERS: Mutex<Vec<Parser>> = Mutex::new(vec![]);
128
129#[ztracing::instrument(skip_all)]
130pub fn with_parser<F, R>(func: F) -> R
131where
132    F: FnOnce(&mut Parser) -> R,
133{
134    let mut parser = PARSERS.lock().pop().unwrap_or_else(|| {
135        let mut parser = Parser::new();
136        parser
137            .set_wasm_store(WasmStore::new(&WASM_ENGINE).unwrap())
138            .unwrap();
139        parser
140    });
141    // Tree-sitter auto-resets the parser at the end of a successful parse,
142    // but the cancellation paths (progress callback returning `Break`,
143    // cancelled balancing) leave outstanding state on the parser. The next
144    // call to `parse_with_options` would then *resume* that cancelled parse
145    // instead of starting fresh.
146    parser.reset();
147    parser.set_included_ranges(&[]).unwrap();
148    let result = func(&mut parser);
149    PARSERS.lock().push(parser);
150    result
151}
152
153pub fn with_query_cursor<F, R>(func: F) -> R
154where
155    F: FnOnce(&mut QueryCursor) -> R,
156{
157    let mut cursor = QueryCursorHandle::new();
158    func(cursor.deref_mut())
159}
160
161static WASM_ENGINE: LazyLock<wasmtime::Engine> = LazyLock::new(|| {
162    wasmtime::Engine::new(&wasmtime::Config::new()).expect("Failed to create Wasmtime engine")
163});
164
165/// A shared grammar for plain text, exposed for reuse by downstream crates.
166pub static PLAIN_TEXT: LazyLock<Arc<Language>> = LazyLock::new(|| {
167    Arc::new(Language::new(
168        LanguageConfig {
169            name: "Plain Text".into(),
170            soft_wrap: Some(SoftWrap::EditorWidth),
171            autoclose_before: ")]}".into(),
172            matcher: (LanguageMatcher {
173                path_suffixes: vec!["txt".to_owned()],
174                first_line_pattern: None,
175                modeline_aliases: vec!["text".to_owned(), "txt".to_owned()],
176            })
177            .into(),
178            brackets: BracketPairConfig {
179                pairs: vec![
180                    BracketPair {
181                        start: "(".to_string(),
182                        end: ")".to_string(),
183                        close: true,
184                        surround: true,
185                        newline: false,
186                    },
187                    BracketPair {
188                        start: "[".to_string(),
189                        end: "]".to_string(),
190                        close: true,
191                        surround: true,
192                        newline: false,
193                    },
194                    BracketPair {
195                        start: "{".to_string(),
196                        end: "}".to_string(),
197                        close: true,
198                        surround: true,
199                        newline: false,
200                    },
201                    BracketPair {
202                        start: "\"".to_string(),
203                        end: "\"".to_string(),
204                        close: true,
205                        surround: true,
206                        newline: false,
207                    },
208                    BracketPair {
209                        start: "'".to_string(),
210                        end: "'".to_string(),
211                        close: true,
212                        surround: true,
213                        newline: false,
214                    },
215                ],
216                disabled_scopes_by_bracket_ix: Default::default(),
217            },
218            ..Default::default()
219        },
220        None,
221    ))
222});
223
224pub fn symbol_kind_to_lsp(kind: SymbolKind) -> lsp::SymbolKind {
225    match kind {
226        SymbolKind::File => lsp::SymbolKind::FILE,
227        SymbolKind::Module => lsp::SymbolKind::MODULE,
228        SymbolKind::Namespace => lsp::SymbolKind::NAMESPACE,
229        SymbolKind::Package => lsp::SymbolKind::PACKAGE,
230        SymbolKind::Class => lsp::SymbolKind::CLASS,
231        SymbolKind::Method => lsp::SymbolKind::METHOD,
232        SymbolKind::Property => lsp::SymbolKind::PROPERTY,
233        SymbolKind::Field => lsp::SymbolKind::FIELD,
234        SymbolKind::Constructor => lsp::SymbolKind::CONSTRUCTOR,
235        SymbolKind::Enum => lsp::SymbolKind::ENUM,
236        SymbolKind::Interface => lsp::SymbolKind::INTERFACE,
237        SymbolKind::Function => lsp::SymbolKind::FUNCTION,
238        SymbolKind::Variable => lsp::SymbolKind::VARIABLE,
239        SymbolKind::Constant => lsp::SymbolKind::CONSTANT,
240        SymbolKind::String => lsp::SymbolKind::STRING,
241        SymbolKind::Number => lsp::SymbolKind::NUMBER,
242        SymbolKind::Boolean => lsp::SymbolKind::BOOLEAN,
243        SymbolKind::Array => lsp::SymbolKind::ARRAY,
244        SymbolKind::Object => lsp::SymbolKind::OBJECT,
245        SymbolKind::Key => lsp::SymbolKind::KEY,
246        SymbolKind::Null => lsp::SymbolKind::NULL,
247        SymbolKind::EnumMember => lsp::SymbolKind::ENUM_MEMBER,
248        SymbolKind::Struct => lsp::SymbolKind::STRUCT,
249        SymbolKind::Event => lsp::SymbolKind::EVENT,
250        SymbolKind::Operator => lsp::SymbolKind::OPERATOR,
251        SymbolKind::TypeParameter => lsp::SymbolKind::TYPE_PARAMETER,
252    }
253}
254
255pub fn lsp_to_symbol_kind(kind: lsp::SymbolKind) -> SymbolKind {
256    match kind {
257        lsp::SymbolKind::FILE => SymbolKind::File,
258        lsp::SymbolKind::MODULE => SymbolKind::Module,
259        lsp::SymbolKind::NAMESPACE => SymbolKind::Namespace,
260        lsp::SymbolKind::PACKAGE => SymbolKind::Package,
261        lsp::SymbolKind::CLASS => SymbolKind::Class,
262        lsp::SymbolKind::METHOD => SymbolKind::Method,
263        lsp::SymbolKind::PROPERTY => SymbolKind::Property,
264        lsp::SymbolKind::FIELD => SymbolKind::Field,
265        lsp::SymbolKind::CONSTRUCTOR => SymbolKind::Constructor,
266        lsp::SymbolKind::ENUM => SymbolKind::Enum,
267        lsp::SymbolKind::INTERFACE => SymbolKind::Interface,
268        lsp::SymbolKind::FUNCTION => SymbolKind::Function,
269        lsp::SymbolKind::VARIABLE => SymbolKind::Variable,
270        lsp::SymbolKind::CONSTANT => SymbolKind::Constant,
271        lsp::SymbolKind::STRING => SymbolKind::String,
272        lsp::SymbolKind::NUMBER => SymbolKind::Number,
273        lsp::SymbolKind::BOOLEAN => SymbolKind::Boolean,
274        lsp::SymbolKind::ARRAY => SymbolKind::Array,
275        lsp::SymbolKind::OBJECT => SymbolKind::Object,
276        lsp::SymbolKind::KEY => SymbolKind::Key,
277        lsp::SymbolKind::NULL => SymbolKind::Null,
278        lsp::SymbolKind::ENUM_MEMBER => SymbolKind::EnumMember,
279        lsp::SymbolKind::STRUCT => SymbolKind::Struct,
280        lsp::SymbolKind::EVENT => SymbolKind::Event,
281        lsp::SymbolKind::OPERATOR => SymbolKind::Operator,
282        lsp::SymbolKind::TYPE_PARAMETER => SymbolKind::TypeParameter,
283        _ => SymbolKind::Null,
284    }
285}
286
287/// Commands that the client (editor) handles locally rather than forwarding
288/// to the language server. Servers embed these in code lens and code action
289/// responses when they want the editor to perform a well-known UI action.
290#[derive(Debug, Clone)]
291pub enum ClientCommand {
292    /// Open a location list (references panel / peek view).
293    ShowLocations,
294    /// Schedule a task from an LSP command's arguments.
295    ScheduleTask(task::TaskTemplate),
296}
297
298#[derive(Debug, Clone, PartialEq, Eq, Hash)]
299pub struct Location {
300    pub buffer: Entity<Buffer>,
301    pub range: Range<Anchor>,
302}
303
304/// Context provided to LSP adapters when a user responds to a ShowMessageRequest prompt.
305/// This allows adapters to intercept preference selections (like "Always" or "Never")
306/// and potentially persist them to Zed's settings.
307#[derive(Debug, Clone)]
308pub struct PromptResponseContext {
309    /// The original message shown to the user
310    pub message: String,
311    /// The action (button) the user selected
312    pub selected_action: lsp::MessageActionItem,
313}
314
315type ServerBinaryCache = futures::lock::Mutex<Option<(bool, LanguageServerBinary)>>;
316type DownloadableLanguageServerBinary = LocalBoxFuture<'static, Result<LanguageServerBinary>>;
317pub type LanguageServerBinaryLocations = LocalBoxFuture<
318    'static,
319    (
320        Result<LanguageServerBinary>,
321        Option<DownloadableLanguageServerBinary>,
322    ),
323>;
324/// Represents a Language Server, with certain cached sync properties.
325/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
326/// once at startup, and caches the results.
327pub struct CachedLspAdapter {
328    pub name: LanguageServerName,
329    pub disk_based_diagnostic_sources: Vec<String>,
330    pub disk_based_diagnostics_progress_token: Option<String>,
331    language_ids: HashMap<LanguageName, String>,
332    pub adapter: Arc<dyn LspAdapter>,
333    cached_binary: Arc<ServerBinaryCache>,
334}
335
336impl Debug for CachedLspAdapter {
337    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
338        f.debug_struct("CachedLspAdapter")
339            .field("name", &self.name)
340            .field(
341                "disk_based_diagnostic_sources",
342                &self.disk_based_diagnostic_sources,
343            )
344            .field(
345                "disk_based_diagnostics_progress_token",
346                &self.disk_based_diagnostics_progress_token,
347            )
348            .field("language_ids", &self.language_ids)
349            .finish_non_exhaustive()
350    }
351}
352
353impl CachedLspAdapter {
354    pub fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
355        let name = adapter.name();
356        let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
357        let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
358        let language_ids = adapter.language_ids();
359
360        Arc::new(CachedLspAdapter {
361            name,
362            disk_based_diagnostic_sources,
363            disk_based_diagnostics_progress_token,
364            language_ids,
365            adapter,
366            cached_binary: Default::default(),
367        })
368    }
369
370    pub fn name(&self) -> LanguageServerName {
371        self.adapter.name()
372    }
373
374    pub async fn get_language_server_command(
375        self: Arc<Self>,
376        delegate: Arc<dyn LspAdapterDelegate>,
377        toolchains: Option<Toolchain>,
378        binary_options: LanguageServerBinaryOptions,
379        cx: &mut AsyncApp,
380    ) -> LanguageServerBinaryLocations {
381        let cached_binary = self.cached_binary.clone().lock_owned().await;
382        self.adapter.clone().get_language_server_command(
383            delegate,
384            toolchains,
385            binary_options,
386            cached_binary,
387            cx.clone(),
388        )
389    }
390
391    pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
392        self.adapter.code_action_kinds()
393    }
394
395    pub fn process_diagnostics(
396        &self,
397        params: &mut lsp::PublishDiagnosticsParams,
398        server_id: LanguageServerId,
399    ) {
400        self.adapter.process_diagnostics(params, server_id)
401    }
402
403    pub fn retain_old_diagnostic(&self, previous_diagnostic: &Diagnostic) -> bool {
404        self.adapter.retain_old_diagnostic(previous_diagnostic)
405    }
406
407    pub fn underline_diagnostic(&self, diagnostic: &lsp::Diagnostic) -> bool {
408        self.adapter.underline_diagnostic(diagnostic)
409    }
410
411    pub fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
412        self.adapter.diagnostic_message_to_markdown(message)
413    }
414
415    pub async fn process_completions(&self, completion_items: &mut [lsp::CompletionItem]) {
416        self.adapter.process_completions(completion_items).await
417    }
418
419    pub async fn labels_for_completions(
420        &self,
421        completion_items: &[lsp::CompletionItem],
422        language: &Arc<Language>,
423    ) -> Result<Vec<Option<CodeLabel>>> {
424        self.adapter
425            .clone()
426            .labels_for_completions(completion_items, language)
427            .await
428    }
429
430    pub async fn labels_for_symbols(
431        &self,
432        symbols: &[Symbol],
433        language: &Arc<Language>,
434    ) -> Result<Vec<Option<CodeLabel>>> {
435        self.adapter
436            .clone()
437            .labels_for_symbols(symbols, language)
438            .await
439    }
440
441    pub fn language_id(&self, language_name: &LanguageName) -> String {
442        self.language_ids
443            .get(language_name)
444            .cloned()
445            .unwrap_or_else(|| language_name.lsp_id())
446    }
447
448    pub async fn initialization_options_schema(
449        &self,
450        delegate: &Arc<dyn LspAdapterDelegate>,
451        cx: &mut AsyncApp,
452    ) -> Option<serde_json::Value> {
453        self.adapter
454            .clone()
455            .initialization_options_schema(
456                delegate,
457                self.cached_binary.clone().lock_owned().await,
458                cx,
459            )
460            .await
461    }
462
463    pub async fn settings_schema(
464        &self,
465        delegate: &Arc<dyn LspAdapterDelegate>,
466        cx: &mut AsyncApp,
467    ) -> Option<serde_json::Value> {
468        self.adapter
469            .clone()
470            .settings_schema(delegate, self.cached_binary.clone().lock_owned().await, cx)
471            .await
472    }
473
474    pub fn process_prompt_response(&self, context: &PromptResponseContext, cx: &mut AsyncApp) {
475        self.adapter.process_prompt_response(context, cx)
476    }
477}
478
479/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
480// e.g. to display a notification or fetch data from the web.
481#[async_trait]
482pub trait LspAdapterDelegate: Send + Sync {
483    fn show_notification(&self, message: &str, cx: &mut App);
484    fn http_client(&self) -> Arc<dyn HttpClient>;
485    fn worktree_id(&self) -> WorktreeId;
486    fn worktree_root_path(&self) -> &Path;
487    fn resolve_relative_path(&self, path: PathBuf) -> PathBuf;
488    fn update_status(&self, language: LanguageServerName, status: BinaryStatus);
489    fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>>;
490    async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>>;
491
492    async fn npm_package_installed_version(
493        &self,
494        package_name: &str,
495    ) -> Result<Option<(PathBuf, Version)>>;
496    async fn which(&self, command: &OsStr) -> Option<PathBuf>;
497    async fn shell_env(&self) -> HashMap<String, String>;
498    async fn read_text_file(&self, path: &RelPath) -> Result<String>;
499    async fn try_exec(&self, binary: LanguageServerBinary) -> Result<()>;
500}
501
502#[async_trait(?Send)]
503pub trait LspAdapter: 'static + Send + Sync + DynLspInstaller {
504    fn name(&self) -> LanguageServerName;
505
506    fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams, _: LanguageServerId) {}
507
508    /// When processing new `lsp::PublishDiagnosticsParams` diagnostics, whether to retain previous one(s) or not.
509    fn retain_old_diagnostic(&self, _previous_diagnostic: &Diagnostic) -> bool {
510        false
511    }
512
513    /// Whether to underline a given diagnostic or not, when rendering in the editor.
514    ///
515    /// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnosticTag
516    /// states that
517    /// > Clients are allowed to render diagnostics with this tag faded out instead of having an error squiggle.
518    /// for the unnecessary diagnostics, so do not underline them.
519    fn underline_diagnostic(&self, _diagnostic: &lsp::Diagnostic) -> bool {
520        true
521    }
522
523    /// Post-processes completions provided by the language server.
524    async fn process_completions(&self, _: &mut [lsp::CompletionItem]) {}
525
526    fn diagnostic_message_to_markdown(&self, _message: &str) -> Option<String> {
527        None
528    }
529
530    async fn labels_for_completions(
531        self: Arc<Self>,
532        completions: &[lsp::CompletionItem],
533        language: &Arc<Language>,
534    ) -> Result<Vec<Option<CodeLabel>>> {
535        let mut labels = Vec::new();
536        for (ix, completion) in completions.iter().enumerate() {
537            let label = self.label_for_completion(completion, language).await;
538            if let Some(label) = label {
539                labels.resize(ix + 1, None);
540                *labels.last_mut().unwrap() = Some(label);
541            }
542        }
543        Ok(labels)
544    }
545
546    async fn label_for_completion(
547        &self,
548        _: &lsp::CompletionItem,
549        _: &Arc<Language>,
550    ) -> Option<CodeLabel> {
551        None
552    }
553
554    async fn labels_for_symbols(
555        self: Arc<Self>,
556        symbols: &[Symbol],
557        language: &Arc<Language>,
558    ) -> Result<Vec<Option<CodeLabel>>> {
559        let mut labels = Vec::new();
560        for (ix, symbol) in symbols.iter().enumerate() {
561            let label = self.label_for_symbol(symbol, language).await;
562            if let Some(label) = label {
563                labels.resize(ix + 1, None);
564                *labels.last_mut().unwrap() = Some(label);
565            }
566        }
567        Ok(labels)
568    }
569
570    async fn label_for_symbol(
571        &self,
572        _symbol: &Symbol,
573        _language: &Arc<Language>,
574    ) -> Option<CodeLabel> {
575        None
576    }
577
578    /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp::InitializeParams`]
579    async fn initialization_options(
580        self: Arc<Self>,
581        _: &Arc<dyn LspAdapterDelegate>,
582        _cx: &mut AsyncApp,
583    ) -> Result<Option<Value>> {
584        Ok(None)
585    }
586
587    /// Returns the JSON schema of the initialization_options for the language server.
588    async fn initialization_options_schema(
589        self: Arc<Self>,
590        _delegate: &Arc<dyn LspAdapterDelegate>,
591        _cached_binary: OwnedMutexGuard<Option<(bool, LanguageServerBinary)>>,
592        _cx: &mut AsyncApp,
593    ) -> Option<serde_json::Value> {
594        None
595    }
596
597    /// Returns the JSON schema of the settings for the language server.
598    /// This corresponds to the `settings` field in `LspSettings`, which is used
599    /// to respond to `workspace/configuration` requests from the language server.
600    async fn settings_schema(
601        self: Arc<Self>,
602        _delegate: &Arc<dyn LspAdapterDelegate>,
603        _cached_binary: OwnedMutexGuard<Option<(bool, LanguageServerBinary)>>,
604        _cx: &mut AsyncApp,
605    ) -> Option<serde_json::Value> {
606        None
607    }
608
609    async fn workspace_configuration(
610        self: Arc<Self>,
611        _: &Arc<dyn LspAdapterDelegate>,
612        _: Option<Toolchain>,
613        _: Option<Uri>,
614        _cx: &mut AsyncApp,
615    ) -> Result<Value> {
616        Ok(serde_json::json!({}))
617    }
618
619    async fn additional_initialization_options(
620        self: Arc<Self>,
621        _target_language_server_id: LanguageServerName,
622        _: &Arc<dyn LspAdapterDelegate>,
623    ) -> Result<Option<Value>> {
624        Ok(None)
625    }
626
627    async fn additional_workspace_configuration(
628        self: Arc<Self>,
629        _target_language_server_id: LanguageServerName,
630        _: &Arc<dyn LspAdapterDelegate>,
631        _cx: &mut AsyncApp,
632    ) -> Result<Option<Value>> {
633        Ok(None)
634    }
635
636    /// Returns a list of code actions supported by a given LspAdapter
637    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
638        None
639    }
640
641    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
642        Default::default()
643    }
644
645    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
646        None
647    }
648
649    fn language_ids(&self) -> HashMap<LanguageName, String> {
650        HashMap::default()
651    }
652
653    /// Support custom initialize params.
654    fn prepare_initialize_params(
655        &self,
656        original: InitializeParams,
657        _: &App,
658    ) -> Result<InitializeParams> {
659        Ok(original)
660    }
661
662    fn client_command(
663        &self,
664        _command_name: &str,
665        _arguments: &[serde_json::Value],
666    ) -> Option<ClientCommand> {
667        None
668    }
669
670    /// Method only implemented by the default JSON language server adapter.
671    /// Used to provide dynamic reloading of the JSON schemas used to
672    /// provide autocompletion and diagnostics in Zed setting and keybind
673    /// files
674    fn is_primary_zed_json_schema_adapter(&self) -> bool {
675        false
676    }
677
678    /// True for the extension adapter and false otherwise.
679    fn is_extension(&self) -> bool {
680        false
681    }
682
683    /// Called when a user responds to a ShowMessageRequest from this language server.
684    /// This allows adapters to intercept preference selections (like "Always" or "Never")
685    /// for settings that should be persisted to Zed's settings file.
686    fn process_prompt_response(&self, _context: &PromptResponseContext, _cx: &mut AsyncApp) {}
687}
688
689pub trait LspInstaller {
690    type BinaryVersion;
691    fn check_if_user_installed(
692        &self,
693        _: &Arc<dyn LspAdapterDelegate>,
694        _: Option<Toolchain>,
695        _: &AsyncApp,
696    ) -> impl Future<Output = Option<LanguageServerBinary>> {
697        async { None }
698    }
699
700    fn fetch_latest_server_version(
701        &self,
702        delegate: &Arc<dyn LspAdapterDelegate>,
703        pre_release: bool,
704        cx: &mut AsyncApp,
705    ) -> impl Future<Output = Result<Self::BinaryVersion>>;
706
707    fn check_if_version_installed(
708        &self,
709        _version: &Self::BinaryVersion,
710        _container_dir: &PathBuf,
711        _delegate: &Arc<dyn LspAdapterDelegate>,
712    ) -> impl Send + Future<Output = Option<LanguageServerBinary>> + use<Self> {
713        async { None }
714    }
715
716    fn fetch_server_binary(
717        &self,
718        latest_version: Self::BinaryVersion,
719        container_dir: PathBuf,
720        _delegate: &Arc<dyn LspAdapterDelegate>,
721    ) -> impl Send + Future<Output = Result<LanguageServerBinary>> + use<Self>;
722
723    fn cached_server_binary(
724        &self,
725        container_dir: PathBuf,
726        delegate: &dyn LspAdapterDelegate,
727    ) -> impl Future<Output = Option<LanguageServerBinary>>;
728}
729
730#[async_trait(?Send)]
731pub trait DynLspInstaller {
732    async fn try_fetch_server_binary(
733        &self,
734        delegate: &Arc<dyn LspAdapterDelegate>,
735        container_dir: PathBuf,
736        pre_release: bool,
737        cx: &mut AsyncApp,
738    ) -> Result<LanguageServerBinary>;
739
740    fn get_language_server_command(
741        self: Arc<Self>,
742        delegate: Arc<dyn LspAdapterDelegate>,
743        toolchains: Option<Toolchain>,
744        binary_options: LanguageServerBinaryOptions,
745        cached_binary: OwnedMutexGuard<Option<(bool, LanguageServerBinary)>>,
746        cx: AsyncApp,
747    ) -> LanguageServerBinaryLocations;
748}
749
750#[async_trait(?Send)]
751impl<LI, BinaryVersion> DynLspInstaller for LI
752where
753    BinaryVersion: Send + Sync,
754    LI: LspInstaller<BinaryVersion = BinaryVersion> + LspAdapter,
755{
756    async fn try_fetch_server_binary(
757        &self,
758        delegate: &Arc<dyn LspAdapterDelegate>,
759        container_dir: PathBuf,
760        pre_release: bool,
761        cx: &mut AsyncApp,
762    ) -> Result<LanguageServerBinary> {
763        let name = self.name();
764
765        log::debug!("fetching latest version of language server {:?}", name.0);
766        delegate.update_status(name.clone(), BinaryStatus::CheckingForUpdate);
767
768        let latest_version = self
769            .fetch_latest_server_version(delegate, pre_release, cx)
770            .await?;
771
772        if let Some(binary) = cx
773            .background_executor()
774            .spawn(self.check_if_version_installed(&latest_version, &container_dir, &delegate))
775            .await
776        {
777            log::debug!("language server {:?} is already installed", name.0);
778            delegate.update_status(name.clone(), BinaryStatus::None);
779            Ok(binary)
780        } else {
781            log::debug!("downloading language server {:?}", name.0);
782            delegate.update_status(name.clone(), BinaryStatus::Downloading);
783            let binary = cx
784                .background_executor()
785                .spawn(self.fetch_server_binary(latest_version, container_dir, delegate))
786                .await;
787
788            delegate.update_status(name.clone(), BinaryStatus::None);
789            binary
790        }
791    }
792    fn get_language_server_command(
793        self: Arc<Self>,
794        delegate: Arc<dyn LspAdapterDelegate>,
795        toolchain: Option<Toolchain>,
796        binary_options: LanguageServerBinaryOptions,
797        mut cached_binary: OwnedMutexGuard<Option<(bool, LanguageServerBinary)>>,
798        mut cx: AsyncApp,
799    ) -> LanguageServerBinaryLocations {
800        async move {
801            let cached_binary_deref = cached_binary.deref_mut();
802            // First we check whether the adapter can give us a user-installed binary.
803            // If so, we do *not* want to cache that, because each worktree might give us a different
804            // binary:
805            //
806            //      worktree 1: user-installed at `.bin/gopls`
807            //      worktree 2: user-installed at `~/bin/gopls`
808            //      worktree 3: no gopls found in PATH -> fallback to Zed installation
809            //
810            // We only want to cache when we fall back to the global one,
811            // because we don't want to download and overwrite our global one
812            // for each worktree we might have open.
813            if binary_options.allow_path_lookup
814                && let Some(binary) = self
815                    .check_if_user_installed(&delegate, toolchain, &mut cx)
816                    .await
817            {
818                log::info!(
819                    "found user-installed language server for {}. path: {:?}, arguments: {:?}",
820                    self.name().0,
821                    binary.path,
822                    binary.arguments
823                );
824                return (Ok(binary), None);
825            }
826
827            if let Some((pre_release, cached_binary)) = cached_binary_deref
828                && *pre_release == binary_options.pre_release
829            {
830                return (Ok(cached_binary.clone()), None);
831            }
832
833            if !binary_options.allow_binary_download {
834                return (
835                    Err(anyhow::anyhow!("downloading language servers disabled")),
836                    None,
837                );
838            }
839
840            let Some(container_dir) = delegate.language_server_download_dir(&self.name()).await
841            else {
842                return (
843                    Err(anyhow::anyhow!("no language server download dir defined")),
844                    None,
845                );
846            };
847
848            let last_downloaded_binary = self
849                .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
850                .await
851                .context(
852                    "did not find existing language server binary, falling back to downloading",
853                );
854            let download_binary = async move {
855                let mut binary = self
856                    .try_fetch_server_binary(
857                        &delegate,
858                        container_dir.to_path_buf(),
859                        binary_options.pre_release,
860                        &mut cx,
861                    )
862                    .await;
863
864                if let Err(error) = binary.as_ref() {
865                    if let Some(prev_downloaded_binary) = self
866                        .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
867                        .await
868                    {
869                        log::info!(
870                            "failed to fetch newest version of language server {:?}. \
871                            error: {:?}, falling back to using {:?}",
872                            self.name(),
873                            error,
874                            prev_downloaded_binary.path
875                        );
876                        binary = Ok(prev_downloaded_binary);
877                    } else {
878                        delegate.update_status(
879                            self.name(),
880                            BinaryStatus::Failed {
881                                error: format!("{error:?}"),
882                            },
883                        );
884                    }
885                }
886
887                if let Ok(binary) = &binary {
888                    *cached_binary = Some((binary_options.pre_release, binary.clone()));
889                }
890
891                binary
892            }
893            .boxed_local();
894            (last_downloaded_binary, Some(download_binary))
895        }
896        .boxed_local()
897    }
898}
899
900/// Represents a language for the given range. Some languages (e.g. HTML)
901/// interleave several languages together, thus a single buffer might actually contain
902/// several nested scopes.
903#[derive(Clone, Debug)]
904pub struct LanguageScope {
905    language: Arc<Language>,
906    override_id: Option<u32>,
907}
908
909#[doc(hidden)]
910#[cfg(any(test, feature = "test-support"))]
911pub struct FakeLspAdapter {
912    pub name: &'static str,
913    pub initialization_options: Option<Value>,
914    pub prettier_plugins: Vec<&'static str>,
915    pub disk_based_diagnostics_progress_token: Option<String>,
916    pub disk_based_diagnostics_sources: Vec<String>,
917    pub language_server_binary: LanguageServerBinary,
918
919    pub capabilities: lsp::ServerCapabilities,
920    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
921    pub label_for_completion: Option<
922        Box<
923            dyn 'static
924                + Send
925                + Sync
926                + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
927        >,
928    >,
929}
930
931pub struct Language {
932    pub(crate) id: LanguageId,
933    pub(crate) config: LanguageConfig,
934    pub(crate) grammar: Option<Arc<Grammar>>,
935    pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
936    pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
937    pub(crate) manifest_name: Option<ManifestName>,
938}
939
940impl Language {
941    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
942        Self::new_with_id(LanguageId::new(), config, ts_language)
943    }
944
945    pub fn id(&self) -> LanguageId {
946        self.id
947    }
948
949    fn new_with_id(
950        id: LanguageId,
951        config: LanguageConfig,
952        ts_language: Option<tree_sitter::Language>,
953    ) -> Self {
954        Self {
955            id,
956            config,
957            grammar: ts_language.map(|ts_language| Arc::new(Grammar::new(ts_language))),
958            context_provider: None,
959            toolchain: None,
960            manifest_name: None,
961        }
962    }
963
964    pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
965        self.context_provider = provider;
966        self
967    }
968
969    pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
970        self.toolchain = provider;
971        self
972    }
973
974    pub fn with_manifest(mut self, name: Option<ManifestName>) -> Self {
975        self.manifest_name = name;
976        self
977    }
978
979    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
980        if let Some(grammar) = self.grammar.take() {
981            let grammar =
982                Arc::try_unwrap(grammar).map_err(|_| anyhow::anyhow!("cannot mutate grammar"))?;
983            let grammar = grammar.with_queries(queries, &mut self.config)?;
984            self.grammar = Some(Arc::new(grammar));
985        }
986        Ok(self)
987    }
988
989    pub fn with_highlights_query(self, source: &str) -> Result<Self> {
990        self.with_grammar_query(|grammar| grammar.with_highlights_query(source))
991    }
992
993    pub fn with_runnable_query(self, source: &str) -> Result<Self> {
994        self.with_grammar_query(|grammar| grammar.with_runnable_query(source))
995    }
996
997    pub fn with_outline_query(self, source: &str) -> Result<Self> {
998        self.with_grammar_query_and_name(|grammar, name| grammar.with_outline_query(source, name))
999    }
1000
1001    pub fn with_text_object_query(self, source: &str) -> Result<Self> {
1002        self.with_grammar_query_and_name(|grammar, name| {
1003            grammar.with_text_object_query(source, name)
1004        })
1005    }
1006
1007    pub fn with_debug_variables_query(self, source: &str) -> Result<Self> {
1008        self.with_grammar_query_and_name(|grammar, name| {
1009            grammar.with_debug_variables_query(source, name)
1010        })
1011    }
1012
1013    pub fn with_brackets_query(self, source: &str) -> Result<Self> {
1014        self.with_grammar_query_and_name(|grammar, name| grammar.with_brackets_query(source, name))
1015    }
1016
1017    pub fn with_indents_query(self, source: &str) -> Result<Self> {
1018        self.with_grammar_query_and_name(|grammar, name| grammar.with_indents_query(source, name))
1019    }
1020
1021    pub fn with_injection_query(self, source: &str) -> Result<Self> {
1022        self.with_grammar_query_and_name(|grammar, name| grammar.with_injection_query(source, name))
1023    }
1024
1025    pub fn with_override_query(mut self, source: &str) -> Result<Self> {
1026        if let Some(grammar_arc) = self.grammar.take() {
1027            let grammar = Arc::try_unwrap(grammar_arc)
1028                .map_err(|_| anyhow::anyhow!("cannot mutate grammar"))?;
1029            let grammar = grammar.with_override_query(
1030                source,
1031                &self.config.name,
1032                &self.config.overrides,
1033                &mut self.config.brackets,
1034                &self.config.scope_opt_in_language_servers,
1035            )?;
1036            self.grammar = Some(Arc::new(grammar));
1037        }
1038        Ok(self)
1039    }
1040
1041    pub fn with_redaction_query(self, source: &str) -> Result<Self> {
1042        self.with_grammar_query_and_name(|grammar, name| grammar.with_redaction_query(source, name))
1043    }
1044
1045    fn with_grammar_query(
1046        mut self,
1047        build: impl FnOnce(Grammar) -> Result<Grammar>,
1048    ) -> Result<Self> {
1049        if let Some(grammar_arc) = self.grammar.take() {
1050            let grammar = Arc::try_unwrap(grammar_arc)
1051                .map_err(|_| anyhow::anyhow!("cannot mutate grammar"))?;
1052            self.grammar = Some(Arc::new(build(grammar)?));
1053        }
1054        Ok(self)
1055    }
1056
1057    fn with_grammar_query_and_name(
1058        mut self,
1059        build: impl FnOnce(Grammar, &LanguageName) -> Result<Grammar>,
1060    ) -> Result<Self> {
1061        if let Some(grammar_arc) = self.grammar.take() {
1062            let grammar = Arc::try_unwrap(grammar_arc)
1063                .map_err(|_| anyhow::anyhow!("cannot mutate grammar"))?;
1064            self.grammar = Some(Arc::new(build(grammar, &self.config.name)?));
1065        }
1066        Ok(self)
1067    }
1068
1069    pub fn name(&self) -> LanguageName {
1070        self.config.name.clone()
1071    }
1072    pub fn manifest(&self) -> Option<&ManifestName> {
1073        self.manifest_name.as_ref()
1074    }
1075
1076    pub fn code_fence_block_name(&self) -> Arc<str> {
1077        self.config
1078            .code_fence_block_name
1079            .clone()
1080            .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1081    }
1082
1083    pub fn matches_kernel_language(&self, kernel_language: &str) -> bool {
1084        let kernel_language_lower = kernel_language.to_lowercase();
1085
1086        if self.code_fence_block_name().to_lowercase() == kernel_language_lower {
1087            return true;
1088        }
1089
1090        if self.config.name.as_ref().to_lowercase() == kernel_language_lower {
1091            return true;
1092        }
1093
1094        self.config
1095            .kernel_language_names
1096            .iter()
1097            .any(|name| name.to_lowercase() == kernel_language_lower)
1098    }
1099
1100    pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1101        self.context_provider.clone()
1102    }
1103
1104    pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1105        self.toolchain.clone()
1106    }
1107
1108    pub fn highlight_text<'a>(
1109        self: &'a Arc<Self>,
1110        text: &'a Rope,
1111        range: Range<usize>,
1112    ) -> Vec<(Range<usize>, HighlightId)> {
1113        let mut result = Vec::new();
1114        if let Some(grammar) = &self.grammar {
1115            let tree = parse_text(grammar, text, None);
1116            let captures =
1117                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1118                    grammar
1119                        .highlights_config
1120                        .as_ref()
1121                        .map(|config| &config.query)
1122                });
1123            let highlight_maps = vec![grammar.highlight_map()];
1124            let mut offset = 0;
1125            for chunk in
1126                BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1127            {
1128                let end_offset = offset + chunk.text.len();
1129                if let Some(highlight_id) = chunk.syntax_highlight_id {
1130                    result.push((offset..end_offset, highlight_id));
1131                }
1132                offset = end_offset;
1133            }
1134        }
1135        result
1136    }
1137
1138    pub fn path_suffixes(&self) -> &[String] {
1139        &self.config.matcher.path_suffixes
1140    }
1141
1142    pub fn should_autoclose_before(&self, c: char) -> bool {
1143        c.is_whitespace() || self.config.autoclose_before.contains(c)
1144    }
1145
1146    pub fn set_theme(&self, theme: &SyntaxTheme) {
1147        if let Some(grammar) = self.grammar.as_ref()
1148            && let Some(highlights_config) = &grammar.highlights_config
1149        {
1150            *grammar.highlight_map.lock() =
1151                build_highlight_map(highlights_config.query.capture_names(), theme);
1152        }
1153    }
1154
1155    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1156        self.grammar.as_ref()
1157    }
1158
1159    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1160        LanguageScope {
1161            language: self.clone(),
1162            override_id: None,
1163        }
1164    }
1165
1166    pub fn lsp_id(&self) -> String {
1167        self.config.name.lsp_id()
1168    }
1169
1170    pub fn snippet_scope_id(&self) -> String {
1171        self.config.name.snippet_scope_id()
1172    }
1173
1174    pub fn prettier_parser_name(&self) -> Option<&str> {
1175        self.config.prettier_parser_name.as_deref()
1176    }
1177
1178    pub fn config(&self) -> &LanguageConfig {
1179        &self.config
1180    }
1181}
1182
1183#[inline]
1184pub fn build_highlight_map(capture_names: &[&str], theme: &SyntaxTheme) -> HighlightMap {
1185    HighlightMap::from_ids(
1186        capture_names
1187            .iter()
1188            .map(|capture_name| theme.highlight_id(capture_name).map(HighlightId::new)),
1189    )
1190}
1191
1192impl LanguageScope {
1193    pub fn path_suffixes(&self) -> &[String] {
1194        self.language.path_suffixes()
1195    }
1196
1197    pub fn language_name(&self) -> LanguageName {
1198        self.language.config.name.clone()
1199    }
1200
1201    pub fn collapsed_placeholder(&self) -> &str {
1202        self.language.config.collapsed_placeholder.as_ref()
1203    }
1204
1205    /// Returns line prefix that is inserted in e.g. line continuations or
1206    /// in `toggle comments` action.
1207    pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1208        Override::as_option(
1209            self.config_override().map(|o| &o.line_comments),
1210            Some(&self.language.config.line_comments),
1211        )
1212        .map_or([].as_slice(), |e| e.as_slice())
1213    }
1214
1215    /// Config for block comments for this language.
1216    pub fn block_comment(&self) -> Option<&BlockCommentConfig> {
1217        Override::as_option(
1218            self.config_override().map(|o| &o.block_comment),
1219            self.language.config.block_comment.as_ref(),
1220        )
1221    }
1222
1223    /// Config for documentation-style block comments for this language.
1224    pub fn documentation_comment(&self) -> Option<&BlockCommentConfig> {
1225        self.language.config.documentation_comment.as_ref()
1226    }
1227
1228    /// Returns list markers that are inserted unchanged on newline (e.g., `- `, `* `, `+ `).
1229    pub fn unordered_list(&self) -> &[Arc<str>] {
1230        &self.language.config.unordered_list
1231    }
1232
1233    /// Returns configuration for ordered lists with auto-incrementing numbers (e.g., `1. ` becomes `2. `).
1234    pub fn ordered_list(&self) -> &[OrderedListConfig] {
1235        &self.language.config.ordered_list
1236    }
1237
1238    /// Returns configuration for task list continuation, if any (e.g., `- [x] ` continues as `- [ ] `).
1239    pub fn task_list(&self) -> Option<&TaskListConfig> {
1240        self.language.config.task_list.as_ref()
1241    }
1242
1243    /// Returns additional regex patterns that act as prefix markers for creating
1244    /// boundaries during rewrapping.
1245    ///
1246    /// By default, Zed treats as paragraph and comment prefixes as boundaries.
1247    pub fn rewrap_prefixes(&self) -> &[Regex] {
1248        &self.language.config.rewrap_prefixes
1249    }
1250
1251    /// Returns a list of language-specific word characters.
1252    ///
1253    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1254    /// the purpose of actions like 'move to next word end` or whole-word search.
1255    /// It additionally accounts for language's additional word characters.
1256    pub fn word_characters(&self) -> Option<&HashSet<char>> {
1257        Override::as_option(
1258            self.config_override().map(|o| &o.word_characters),
1259            Some(&self.language.config.word_characters),
1260        )
1261    }
1262
1263    /// Returns a list of language-specific characters that are considered part of
1264    /// a completion query.
1265    pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
1266        Override::as_option(
1267            self.config_override()
1268                .map(|o| &o.completion_query_characters),
1269            Some(&self.language.config.completion_query_characters),
1270        )
1271    }
1272
1273    /// Returns a list of language-specific characters that are considered part of
1274    /// identifiers during linked editing operations.
1275    pub fn linked_edit_characters(&self) -> Option<&HashSet<char>> {
1276        Override::as_option(
1277            self.config_override().map(|o| &o.linked_edit_characters),
1278            Some(&self.language.config.linked_edit_characters),
1279        )
1280    }
1281
1282    /// Returns whether to prefer snippet `label` over `new_text` to replace text when
1283    /// completion is accepted.
1284    ///
1285    /// In cases like when cursor is in string or renaming existing function,
1286    /// you don't want to expand function signature instead just want function name
1287    /// to replace existing one.
1288    pub fn prefers_label_for_snippet_in_completion(&self) -> bool {
1289        self.config_override()
1290            .and_then(|o| o.prefer_label_for_snippet)
1291            .unwrap_or(false)
1292    }
1293
1294    /// Returns a list of bracket pairs for a given language with an additional
1295    /// piece of information about whether the particular bracket pair is currently active for a given language.
1296    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1297        let mut disabled_ids = self
1298            .config_override()
1299            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1300        self.language
1301            .config
1302            .brackets
1303            .pairs
1304            .iter()
1305            .enumerate()
1306            .map(move |(ix, bracket)| {
1307                let mut is_enabled = true;
1308                if let Some(next_disabled_ix) = disabled_ids.first()
1309                    && ix == *next_disabled_ix as usize
1310                {
1311                    disabled_ids = &disabled_ids[1..];
1312                    is_enabled = false;
1313                }
1314                (bracket, is_enabled)
1315            })
1316    }
1317
1318    pub fn should_autoclose_before(&self, c: char) -> bool {
1319        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1320    }
1321
1322    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1323        let config = &self.language.config;
1324        let opt_in_servers = &config.scope_opt_in_language_servers;
1325        if opt_in_servers.contains(&name.0) {
1326            if let Some(over) = self.config_override() {
1327                over.opt_into_language_servers.contains(&name.0)
1328            } else {
1329                false
1330            }
1331        } else {
1332            true
1333        }
1334    }
1335
1336    pub fn override_name(&self) -> Option<&str> {
1337        let id = self.override_id?;
1338        let grammar = self.language.grammar.as_ref()?;
1339        let override_config = grammar.override_config.as_ref()?;
1340        override_config.values.get(&id).map(|e| e.name.as_str())
1341    }
1342
1343    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1344        let id = self.override_id?;
1345        let grammar = self.language.grammar.as_ref()?;
1346        let override_config = grammar.override_config.as_ref()?;
1347        override_config.values.get(&id).map(|e| &e.value)
1348    }
1349}
1350
1351impl Hash for Language {
1352    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1353        self.id.hash(state)
1354    }
1355}
1356
1357impl PartialEq for Language {
1358    fn eq(&self, other: &Self) -> bool {
1359        self.id.eq(&other.id)
1360    }
1361}
1362
1363impl Eq for Language {}
1364
1365impl Debug for Language {
1366    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1367        f.debug_struct("Language")
1368            .field("name", &self.config.name)
1369            .finish()
1370    }
1371}
1372
1373pub(crate) fn parse_text(grammar: &Grammar, text: &Rope, old_tree: Option<Tree>) -> Tree {
1374    with_parser(|parser| {
1375        parser
1376            .set_language(&grammar.ts_language)
1377            .expect("incompatible grammar");
1378        let mut chunks = text.chunks_in_range(0..text.len());
1379        parser
1380            .parse_with_options(
1381                &mut move |offset, _| {
1382                    chunks.seek(offset);
1383                    chunks.next().unwrap_or("").as_bytes()
1384                },
1385                old_tree.as_ref(),
1386                None,
1387            )
1388            .unwrap()
1389    })
1390}
1391
1392pub trait CodeLabelExt {
1393    fn fallback_for_completion(
1394        item: &lsp::CompletionItem,
1395        language: Option<&Language>,
1396    ) -> CodeLabel;
1397}
1398
1399impl CodeLabelExt for CodeLabel {
1400    fn fallback_for_completion(
1401        item: &lsp::CompletionItem,
1402        language: Option<&Language>,
1403    ) -> CodeLabel {
1404        let highlight_id = item.kind.and_then(|kind| {
1405            let grammar = language?.grammar()?;
1406            use lsp::CompletionItemKind as Kind;
1407            match kind {
1408                Kind::CLASS => grammar.highlight_id_for_name("type"),
1409                Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
1410                Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
1411                Kind::ENUM => grammar
1412                    .highlight_id_for_name("enum")
1413                    .or_else(|| grammar.highlight_id_for_name("type")),
1414                Kind::ENUM_MEMBER => grammar
1415                    .highlight_id_for_name("variant")
1416                    .or_else(|| grammar.highlight_id_for_name("property")),
1417                Kind::FIELD => grammar.highlight_id_for_name("property"),
1418                Kind::FUNCTION => grammar.highlight_id_for_name("function"),
1419                Kind::INTERFACE => grammar.highlight_id_for_name("type"),
1420                Kind::METHOD => grammar
1421                    .highlight_id_for_name("function.method")
1422                    .or_else(|| grammar.highlight_id_for_name("function")),
1423                Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
1424                Kind::PROPERTY => grammar.highlight_id_for_name("property"),
1425                Kind::STRUCT => grammar.highlight_id_for_name("type"),
1426                Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
1427                Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
1428                _ => None,
1429            }
1430        });
1431
1432        let label = &item.label;
1433        let label_length = label.len();
1434        let runs = highlight_id
1435            .map(|highlight_id| vec![(0..label_length, highlight_id)])
1436            .unwrap_or_default();
1437        let text = if let Some(detail) = item.detail.as_deref().filter(|detail| detail != label) {
1438            format!("{label} {detail}")
1439        } else if let Some(description) = item
1440            .label_details
1441            .as_ref()
1442            .and_then(|label_details| label_details.description.as_deref())
1443            .filter(|description| description != label)
1444        {
1445            format!("{label} {description}")
1446        } else {
1447            label.clone()
1448        };
1449        let filter_range = item
1450            .filter_text
1451            .as_deref()
1452            .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
1453            .unwrap_or(0..label_length);
1454        CodeLabel {
1455            text,
1456            runs,
1457            filter_range,
1458        }
1459    }
1460}
1461
1462#[cfg(any(test, feature = "test-support"))]
1463impl Default for FakeLspAdapter {
1464    fn default() -> Self {
1465        Self {
1466            name: "the-fake-language-server",
1467            capabilities: lsp::LanguageServer::full_capabilities(),
1468            initializer: None,
1469            disk_based_diagnostics_progress_token: None,
1470            initialization_options: None,
1471            disk_based_diagnostics_sources: Vec::new(),
1472            prettier_plugins: Vec::new(),
1473            language_server_binary: LanguageServerBinary {
1474                path: "/the/fake/lsp/path".into(),
1475                arguments: vec![],
1476                env: Default::default(),
1477            },
1478            label_for_completion: None,
1479        }
1480    }
1481}
1482
1483#[cfg(any(test, feature = "test-support"))]
1484impl LspInstaller for FakeLspAdapter {
1485    type BinaryVersion = ();
1486
1487    async fn fetch_latest_server_version(
1488        &self,
1489        _: &Arc<dyn LspAdapterDelegate>,
1490        _: bool,
1491        _: &mut AsyncApp,
1492    ) -> Result<Self::BinaryVersion> {
1493        unreachable!()
1494    }
1495
1496    async fn check_if_user_installed(
1497        &self,
1498        _: &Arc<dyn LspAdapterDelegate>,
1499        _: Option<Toolchain>,
1500        _: &AsyncApp,
1501    ) -> Option<LanguageServerBinary> {
1502        Some(self.language_server_binary.clone())
1503    }
1504
1505    fn fetch_server_binary(
1506        &self,
1507        _: (),
1508        _: PathBuf,
1509        _: &Arc<dyn LspAdapterDelegate>,
1510    ) -> impl Send + Future<Output = Result<LanguageServerBinary>> + use<> {
1511        async {
1512            unreachable!();
1513        }
1514    }
1515
1516    async fn cached_server_binary(
1517        &self,
1518        _: PathBuf,
1519        _: &dyn LspAdapterDelegate,
1520    ) -> Option<LanguageServerBinary> {
1521        unreachable!();
1522    }
1523}
1524
1525#[cfg(any(test, feature = "test-support"))]
1526#[async_trait(?Send)]
1527impl LspAdapter for FakeLspAdapter {
1528    fn name(&self) -> LanguageServerName {
1529        LanguageServerName(self.name.into())
1530    }
1531
1532    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1533        self.disk_based_diagnostics_sources.clone()
1534    }
1535
1536    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1537        self.disk_based_diagnostics_progress_token.clone()
1538    }
1539
1540    async fn initialization_options(
1541        self: Arc<Self>,
1542        _: &Arc<dyn LspAdapterDelegate>,
1543        _cx: &mut AsyncApp,
1544    ) -> Result<Option<Value>> {
1545        Ok(self.initialization_options.clone())
1546    }
1547
1548    async fn label_for_completion(
1549        &self,
1550        item: &lsp::CompletionItem,
1551        language: &Arc<Language>,
1552    ) -> Option<CodeLabel> {
1553        let label_for_completion = self.label_for_completion.as_ref()?;
1554        label_for_completion(item, language)
1555    }
1556
1557    fn is_extension(&self) -> bool {
1558        false
1559    }
1560}
1561
1562pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1563    lsp::Position::new(point.row, point.column)
1564}
1565
1566pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1567    Unclipped(PointUtf16::new(point.line, point.character))
1568}
1569
1570pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
1571    anyhow::ensure!(
1572        range.start <= range.end,
1573        "Inverted range provided to an LSP request: {:?}-{:?}",
1574        range.start,
1575        range.end
1576    );
1577    Ok(lsp::Range {
1578        start: point_to_lsp(range.start),
1579        end: point_to_lsp(range.end),
1580    })
1581}
1582
1583pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1584    let mut start = point_from_lsp(range.start);
1585    let mut end = point_from_lsp(range.end);
1586    if start > end {
1587        // We debug instead of warn so that this is not logged by default unless explicitly requested.
1588        // Using warn would write to the log file, and since we receive an enormous amount of
1589        // range_from_lsp calls (especially during completions), that can hang the main thread.
1590        //
1591        // See issue #36223.
1592        zlog::debug!("range_from_lsp called with inverted range {start:?}-{end:?}");
1593        mem::swap(&mut start, &mut end);
1594    }
1595    start..end
1596}
1597
1598#[doc(hidden)]
1599#[cfg(any(test, feature = "test-support"))]
1600pub fn rust_lang() -> Arc<Language> {
1601    test_language("rust", tree_sitter_rust::LANGUAGE.into())
1602}
1603
1604#[doc(hidden)]
1605#[cfg(any(test, feature = "test-support"))]
1606pub fn json_lang() -> Arc<Language> {
1607    test_language("json", tree_sitter_json::LANGUAGE.into())
1608}
1609
1610#[doc(hidden)]
1611#[cfg(any(test, feature = "test-support"))]
1612pub fn markdown_lang() -> Arc<Language> {
1613    test_language("markdown", tree_sitter_md::LANGUAGE.into())
1614}
1615
1616#[cfg(any(test, feature = "test-support"))]
1617fn test_language(name: &str, grammar: tree_sitter::Language) -> Arc<Language> {
1618    Arc::new(
1619        Language::new(grammars::load_config(name), Some(grammar))
1620            .with_queries(grammars::load_queries(name))
1621            .unwrap_or_else(|error| panic!("could not parse queries for language {name}: {error}")),
1622    )
1623}
1624
1625#[cfg(test)]
1626mod tests {
1627    use super::*;
1628    use gpui::{TestAppContext, rgba};
1629    use pretty_assertions::assert_matches;
1630
1631    #[test]
1632    fn test_highlight_map() {
1633        let theme = SyntaxTheme::new(
1634            [
1635                ("function", rgba(0x100000ff)),
1636                ("function.method", rgba(0x200000ff)),
1637                ("function.async", rgba(0x300000ff)),
1638                ("variable.builtin.self.rust", rgba(0x400000ff)),
1639                ("variable.builtin", rgba(0x500000ff)),
1640                ("variable", rgba(0x600000ff)),
1641            ]
1642            .iter()
1643            .map(|(name, color)| (name.to_string(), (*color).into())),
1644        );
1645
1646        let capture_names = &[
1647            "function.special",
1648            "function.async.rust",
1649            "variable.builtin.self",
1650        ];
1651
1652        let map = build_highlight_map(capture_names, &theme);
1653        assert_eq!(
1654            theme.get_capture_name(map.get(0).unwrap()),
1655            Some("function")
1656        );
1657        assert_eq!(
1658            theme.get_capture_name(map.get(1).unwrap()),
1659            Some("function.async")
1660        );
1661        assert_eq!(
1662            theme.get_capture_name(map.get(2).unwrap()),
1663            Some("variable.builtin")
1664        );
1665    }
1666
1667    #[test]
1668    fn test_with_parser_resets_after_cancellation() {
1669        use std::ops::ControlFlow;
1670        use tree_sitter::{Language as TsLanguage, ParseOptions};
1671
1672        let rust_language: TsLanguage = tree_sitter_rust::LANGUAGE.into();
1673
1674        // Drain the shared pool so this test sees a deterministic LIFO order:
1675        // the parser we push at the end of the first `with_parser` call is the
1676        // one we pop at the start of the second call.
1677        PARSERS.lock().clear();
1678
1679        // Large enough that tree-sitter invokes the progress callback before
1680        // the parse completes; otherwise the cancellation never fires.
1681        let large_input = format!("fn a() {{ {} }}", "b(c, d); e(f, g); ".repeat(5000));
1682        let small_input = "fn z() {}";
1683
1684        // Cancel a parse via the progress callback. Tree-sitter retains the
1685        // in-progress parse state on the parser (its `canceled_balancing` flag
1686        // and/or non-empty parse stack), and the next call to
1687        // `parse_with_options` will *resume* that parse unless the parser is
1688        // reset first.
1689        let cancelled = with_parser(|parser| {
1690            parser.set_language(&rust_language).unwrap();
1691            let bytes = large_input.as_bytes();
1692            let mut break_immediately = |_: &_| ControlFlow::Break(());
1693            parser.parse_with_options(
1694                &mut |offset, _| {
1695                    if offset < bytes.len() {
1696                        &bytes[offset..]
1697                    } else {
1698                        &[]
1699                    }
1700                },
1701                None,
1702                Some(ParseOptions {
1703                    progress_callback: Some(&mut break_immediately),
1704                }),
1705            )
1706        });
1707        assert!(
1708            cancelled.is_none(),
1709            "first parse should be cancelled by the progress callback"
1710        );
1711
1712        // Deliberately do NOT call `set_language` here: tree-sitter's
1713        // `ts_parser_set_language` internally calls `ts_parser_reset`, which
1714        // would mask the very bug we're checking for. Instead we rely on the
1715        // language being preserved across `parser.reset()` (it is) and verify
1716        // that `with_parser` itself produces a clean parser for the next user.
1717        let tree = with_parser(|parser| {
1718            let bytes = small_input.as_bytes();
1719            parser
1720                .parse_with_options(
1721                    &mut |offset, _| {
1722                        if offset < bytes.len() {
1723                            &bytes[offset..]
1724                        } else {
1725                            &[]
1726                        }
1727                    },
1728                    None,
1729                    None,
1730                )
1731                .expect("parse of small_input should succeed")
1732        });
1733
1734        assert_eq!(tree.root_node().byte_range(), 0..small_input.len());
1735        assert_eq!(tree.root_node().kind(), "source_file");
1736        assert!(
1737            !tree.root_node().has_error(),
1738            "tree should be error-free, got: {}",
1739            tree.root_node().to_sexp()
1740        );
1741    }
1742
1743    #[gpui::test(iterations = 10)]
1744
1745    async fn test_language_loading(cx: &mut TestAppContext) {
1746        let languages = LanguageRegistry::test(cx.executor());
1747        let languages = Arc::new(languages);
1748        languages.register_native_grammars([
1749            ("json", tree_sitter_json::LANGUAGE),
1750            ("rust", tree_sitter_rust::LANGUAGE),
1751        ]);
1752        languages.register_test_language(LanguageConfig {
1753            name: "JSON".into(),
1754            grammar: Some("json".into()),
1755            matcher: (LanguageMatcher {
1756                path_suffixes: vec!["json".into()],
1757                ..Default::default()
1758            })
1759            .into(),
1760            ..Default::default()
1761        });
1762        languages.register_test_language(LanguageConfig {
1763            name: "Rust".into(),
1764            grammar: Some("rust".into()),
1765            matcher: (LanguageMatcher {
1766                path_suffixes: vec!["rs".into()],
1767                ..Default::default()
1768            })
1769            .into(),
1770            ..Default::default()
1771        });
1772        assert_eq!(
1773            languages.language_names(),
1774            &[
1775                LanguageName::new_static("JSON"),
1776                LanguageName::new_static("Plain Text"),
1777                LanguageName::new_static("Rust"),
1778            ]
1779        );
1780
1781        let rust1 = languages.language_for_name("Rust");
1782        let rust2 = languages.language_for_name("Rust");
1783
1784        // Ensure language is still listed even if it's being loaded.
1785        assert_eq!(
1786            languages.language_names(),
1787            &[
1788                LanguageName::new_static("JSON"),
1789                LanguageName::new_static("Plain Text"),
1790                LanguageName::new_static("Rust"),
1791            ]
1792        );
1793
1794        let (rust1, rust2) = futures::join!(rust1, rust2);
1795        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1796
1797        // Ensure language is still listed even after loading it.
1798        assert_eq!(
1799            languages.language_names(),
1800            &[
1801                LanguageName::new_static("JSON"),
1802                LanguageName::new_static("Plain Text"),
1803                LanguageName::new_static("Rust"),
1804            ]
1805        );
1806
1807        // Loading an unknown language returns an error.
1808        assert!(languages.language_for_name("Unknown").await.is_err());
1809    }
1810
1811    #[gpui::test]
1812    async fn test_completion_label_omits_duplicate_data() {
1813        let regular_completion_item_1 = lsp::CompletionItem {
1814            label: "regular1".to_string(),
1815            detail: Some("detail1".to_string()),
1816            label_details: Some(lsp::CompletionItemLabelDetails {
1817                detail: None,
1818                description: Some("description 1".to_string()),
1819            }),
1820            ..lsp::CompletionItem::default()
1821        };
1822
1823        let regular_completion_item_2 = lsp::CompletionItem {
1824            label: "regular2".to_string(),
1825            label_details: Some(lsp::CompletionItemLabelDetails {
1826                detail: None,
1827                description: Some("description 2".to_string()),
1828            }),
1829            ..lsp::CompletionItem::default()
1830        };
1831
1832        let completion_item_with_duplicate_detail_and_proper_description = lsp::CompletionItem {
1833            detail: Some(regular_completion_item_1.label.clone()),
1834            ..regular_completion_item_1.clone()
1835        };
1836
1837        let completion_item_with_duplicate_detail = lsp::CompletionItem {
1838            detail: Some(regular_completion_item_1.label.clone()),
1839            label_details: None,
1840            ..regular_completion_item_1.clone()
1841        };
1842
1843        let completion_item_with_duplicate_description = lsp::CompletionItem {
1844            label_details: Some(lsp::CompletionItemLabelDetails {
1845                detail: None,
1846                description: Some(regular_completion_item_2.label.clone()),
1847            }),
1848            ..regular_completion_item_2.clone()
1849        };
1850
1851        assert_eq!(
1852            CodeLabel::fallback_for_completion(&regular_completion_item_1, None).text,
1853            format!(
1854                "{} {}",
1855                regular_completion_item_1.label,
1856                regular_completion_item_1.detail.unwrap()
1857            ),
1858            "LSP completion items with both detail and label_details.description should prefer detail"
1859        );
1860        assert_eq!(
1861            CodeLabel::fallback_for_completion(&regular_completion_item_2, None).text,
1862            format!(
1863                "{} {}",
1864                regular_completion_item_2.label,
1865                regular_completion_item_2
1866                    .label_details
1867                    .as_ref()
1868                    .unwrap()
1869                    .description
1870                    .as_ref()
1871                    .unwrap()
1872            ),
1873            "LSP completion items without detail but with label_details.description should use that"
1874        );
1875        assert_eq!(
1876            CodeLabel::fallback_for_completion(
1877                &completion_item_with_duplicate_detail_and_proper_description,
1878                None
1879            )
1880            .text,
1881            format!(
1882                "{} {}",
1883                regular_completion_item_1.label,
1884                regular_completion_item_1
1885                    .label_details
1886                    .as_ref()
1887                    .unwrap()
1888                    .description
1889                    .as_ref()
1890                    .unwrap()
1891            ),
1892            "LSP completion items with both detail and label_details.description should prefer description only if the detail duplicates the completion label"
1893        );
1894        assert_eq!(
1895            CodeLabel::fallback_for_completion(&completion_item_with_duplicate_detail, None).text,
1896            regular_completion_item_1.label,
1897            "LSP completion items with duplicate label and detail, should omit the detail"
1898        );
1899        assert_eq!(
1900            CodeLabel::fallback_for_completion(&completion_item_with_duplicate_description, None)
1901                .text,
1902            regular_completion_item_2.label,
1903            "LSP completion items with duplicate label and detail, should omit the detail"
1904        );
1905    }
1906
1907    #[test]
1908    fn test_deserializing_comments_backwards_compat() {
1909        // current version of `block_comment` and `documentation_comment` work
1910        {
1911            let config: LanguageConfig = ::toml::from_str(
1912                r#"
1913                name = "Foo"
1914                block_comment = { start = "a", end = "b", prefix = "c", tab_size = 1 }
1915                documentation_comment = { start = "d", end = "e", prefix = "f", tab_size = 2 }
1916                "#,
1917            )
1918            .unwrap();
1919            assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
1920            assert_matches!(
1921                config.documentation_comment,
1922                Some(BlockCommentConfig { .. })
1923            );
1924
1925            let block_config = config.block_comment.unwrap();
1926            assert_eq!(block_config.start.as_ref(), "a");
1927            assert_eq!(block_config.end.as_ref(), "b");
1928            assert_eq!(block_config.prefix.as_ref(), "c");
1929            assert_eq!(block_config.tab_size, 1);
1930
1931            let doc_config = config.documentation_comment.unwrap();
1932            assert_eq!(doc_config.start.as_ref(), "d");
1933            assert_eq!(doc_config.end.as_ref(), "e");
1934            assert_eq!(doc_config.prefix.as_ref(), "f");
1935            assert_eq!(doc_config.tab_size, 2);
1936        }
1937
1938        // former `documentation` setting is read into `documentation_comment`
1939        {
1940            let config: LanguageConfig = ::toml::from_str(
1941                r#"
1942                name = "Foo"
1943                documentation = { start = "a", end = "b", prefix = "c", tab_size = 1}
1944                "#,
1945            )
1946            .unwrap();
1947            assert_matches!(
1948                config.documentation_comment,
1949                Some(BlockCommentConfig { .. })
1950            );
1951
1952            let config = config.documentation_comment.unwrap();
1953            assert_eq!(config.start.as_ref(), "a");
1954            assert_eq!(config.end.as_ref(), "b");
1955            assert_eq!(config.prefix.as_ref(), "c");
1956            assert_eq!(config.tab_size, 1);
1957        }
1958
1959        // old block_comment format is read into BlockCommentConfig
1960        {
1961            let config: LanguageConfig = ::toml::from_str(
1962                r#"
1963                name = "Foo"
1964                block_comment = ["a", "b"]
1965                "#,
1966            )
1967            .unwrap();
1968            assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
1969
1970            let config = config.block_comment.unwrap();
1971            assert_eq!(config.start.as_ref(), "a");
1972            assert_eq!(config.end.as_ref(), "b");
1973            assert_eq!(config.prefix.as_ref(), "");
1974            assert_eq!(config.tab_size, 0);
1975        }
1976    }
1977}
1978
Served at tenant.openagents/omega Member data and write actions are omitted.